blob: 92ba5e4bd631ff7cb054998def2dd1ab827c9b6c [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
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800164 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165 &mPhysicalDeviceInfoMap[physicalId],
166 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700167 }
168 }
169
Yifan Hongf79b5542017-04-11 14:44:25 -0700170 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700171 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
172 [&queue](const auto& descriptor) {
173 queue = std::make_shared<RequestMetadataQueue>(descriptor);
174 if (!queue->isValid() || queue->availableToWrite() <= 0) {
175 ALOGE("HAL returns empty request metadata fmq, not use it");
176 queue = nullptr;
177 // don't use the queue onwards.
178 }
179 });
180 if (!requestQueueRet.isOk()) {
181 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
182 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700183 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700185
186 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700187 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700188 [&resQueue](const auto& descriptor) {
189 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
190 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192 resQueue = nullptr;
193 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 }
195 });
196 if (!resultQueueRet.isOk()) {
197 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
198 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700199 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700200 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700201 IF_ALOGV() {
202 session->interfaceChain([](
203 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
204 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800205 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700206 ALOGV(" %s", iface.c_str());
207 }
208 });
209 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700210
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800211 camera_metadata_entry bufMgrMode =
212 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
213 if (bufMgrMode.count > 0) {
214 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
215 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
216 }
217
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700218 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
219 for (size_t i = 0; i < capabilities.count; i++) {
220 uint8_t capability = capabilities.data.u8[i];
221 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
222 mSupportOfflineProcessing = true;
223 }
224 }
225
226 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000227 std::string providerType;
228 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000229 mTagMonitor.initialize(mVendorTagId);
230 if (!monitorTags.isEmpty()) {
231 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
232 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800233
Shuzhen Wang268a1362018-10-16 16:32:59 -0700234 // Metadata tags needs fixup for monochrome camera device version less
235 // than 3.5.
236 hardware::hidl_version maxVersion{0,0};
237 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
238 if (res != OK) {
239 ALOGE("%s: Error in getting camera device version id: %s (%d)",
240 __FUNCTION__, strerror(-res), res);
241 return res;
242 }
243 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
244 maxVersion.get_major(), maxVersion.get_minor());
245
246 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700247 for (size_t i = 0; i < capabilities.count; i++) {
248 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
250 isMonochrome = true;
251 }
252 }
253 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
254
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800255 return initializeCommonLocked();
256}
257
258status_t Camera3Device::initializeCommonLocked() {
259
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 /** Start up status tracker thread */
261 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 if (res != OK) {
264 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
265 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 mStatusTracker.clear();
268 return res;
269 }
270
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700271 /** Register in-flight map to the status tracker */
272 mInFlightStatusId = mStatusTracker->addComponent();
273
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700274 if (mUseHalBufManager) {
275 res = mRequestBufferSM.initialize(mStatusTracker);
276 if (res != OK) {
277 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
278 strerror(-res), res);
279 mInterface->close();
280 mStatusTracker.clear();
281 return res;
282 }
283 }
284
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800285 /** Create buffer manager */
286 mBufferManager = new Camera3BufferManager();
287
288 Vector<int32_t> sessionParamKeys;
289 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
290 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
291 if (sessionKeysEntry.count > 0) {
292 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
293 }
294
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700295 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700296 mRequestThread = new RequestThread(
297 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800298 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800299 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700300 SET_ERR_L("Unable to start request queue thread: %s (%d)",
301 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800302 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304 return res;
305 }
306
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700307 mPreparerThread = new PreparerThread();
308
Ruben Brunk183f0562015-08-12 12:55:02 -0700309 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700311 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700312 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700313 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800314
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800315 // Measure the clock domain offset between camera and video/hw_composer
316 camera_metadata_entry timestampSource =
317 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
318 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
319 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
320 mTimestampOffset = getMonoToBoottimeOffset();
321 }
322
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700323 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100324 camera_metadata_entry partialResultsCount =
325 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
326 if (partialResultsCount.count > 0) {
327 mNumPartialResults = partialResultsCount.data.i32[0];
328 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700329 }
330
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700331 camera_metadata_entry configs =
332 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
333 for (uint32_t i = 0; i < configs.count; i += 4) {
334 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
335 configs.data.i32[i + 3] ==
336 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
337 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
338 configs.data.i32[i + 2]));
339 }
340 }
341
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800342 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
343 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700344 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700345 if (res != OK) {
346 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
347 return res;
348 }
349 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800351 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800353
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800354 return OK;
355}
356
357status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700358 return disconnectImpl();
359}
360
361status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800362 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800364
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700365 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800366
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700367 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700368 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700369 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370 {
371 Mutex::Autolock l(mLock);
372 if (mStatus == STATUS_UNINITIALIZED) return res;
373
374 if (mStatus == STATUS_ACTIVE ||
375 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
376 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700377 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700379 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700381 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700383 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
384 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 // Continue to close device even in case of error
386 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700387 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800388 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800389
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700390 if (mStatus == STATUS_ERROR) {
391 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700392 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700393
394 if (mStatusTracker != NULL) {
395 mStatusTracker->requestExit();
396 }
397
398 if (mRequestThread != NULL) {
399 mRequestThread->requestExit();
400 }
401
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700402 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
403 for (size_t i = 0; i < mOutputStreams.size(); i++) {
404 streams.push_back(mOutputStreams[i]);
405 }
406 if (mInputStream != nullptr) {
407 streams.push_back(mInputStream);
408 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700409 }
410
411 // Joining done without holding mLock, otherwise deadlocks may ensue
412 // as the threads try to access parent state
413 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
414 // HAL may be in a bad state, so waiting for request thread
415 // (which may be stuck in the HAL processCaptureRequest call)
416 // could be dangerous.
417 mRequestThread->join();
418 }
419
420 if (mStatusTracker != NULL) {
421 mStatusTracker->join();
422 }
423
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800424 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 {
426 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800427 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100428 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700429 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800430 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700431 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800432
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700433 // Call close without internal mutex held, as the HAL close may need to
434 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800435 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700436
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700437 flushInflightRequests();
438
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700439 {
440 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800441 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700442 mOutputStreams.clear();
443 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700444 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700445 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700446 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700447 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800448
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700449 for (auto& weakStream : streams) {
450 sp<Camera3StreamInterface> stream = weakStream.promote();
451 if (stream != nullptr) {
452 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
453 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
454 }
455 }
456
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700457 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700458 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800459}
460
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700461// For dumping/debugging only -
462// try to acquire a lock a few times, eventually give up to proceed with
463// debug/dump operations
464bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
465 bool gotLock = false;
466 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
467 if (lock.tryLock() == NO_ERROR) {
468 gotLock = true;
469 break;
470 } else {
471 usleep(kDumpSleepDuration);
472 }
473 }
474 return gotLock;
475}
476
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700477Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
478 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100479 const int STREAM_CONFIGURATION_SIZE = 4;
480 const int STREAM_FORMAT_OFFSET = 0;
481 const int STREAM_WIDTH_OFFSET = 1;
482 const int STREAM_HEIGHT_OFFSET = 2;
483 const int STREAM_IS_INPUT_OFFSET = 3;
484 camera_metadata_ro_entry_t availableStreamConfigs =
485 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
486 if (availableStreamConfigs.count == 0 ||
487 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
488 return Size(0, 0);
489 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700490
Emilian Peev08dd2452017-04-06 16:55:14 +0100491 // Get max jpeg size (area-wise).
492 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
493 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
494 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
495 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
496 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
497 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
498 && format == HAL_PIXEL_FORMAT_BLOB &&
499 (width * height > maxJpegWidth * maxJpegHeight)) {
500 maxJpegWidth = width;
501 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700502 }
503 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100504
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700505 return Size(maxJpegWidth, maxJpegHeight);
506}
507
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800508nsecs_t Camera3Device::getMonoToBoottimeOffset() {
509 // try three times to get the clock offset, choose the one
510 // with the minimum gap in measurements.
511 const int tries = 3;
512 nsecs_t bestGap, measured;
513 for (int i = 0; i < tries; ++i) {
514 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
515 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
516 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
517 const nsecs_t gap = tmono2 - tmono;
518 if (i == 0 || gap < bestGap) {
519 bestGap = gap;
520 measured = tbase - ((tmono + tmono2) >> 1);
521 }
522 }
523 return measured;
524}
525
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800526hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
527 int frameworkFormat) {
528 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
529}
530
531DataspaceFlags Camera3Device::mapToHidlDataspace(
532 android_dataspace dataSpace) {
533 return dataSpace;
534}
535
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700536BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100537 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700538 return usage;
539}
540
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800541StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
542 switch (rotation) {
543 case CAMERA3_STREAM_ROTATION_0:
544 return StreamRotation::ROTATION_0;
545 case CAMERA3_STREAM_ROTATION_90:
546 return StreamRotation::ROTATION_90;
547 case CAMERA3_STREAM_ROTATION_180:
548 return StreamRotation::ROTATION_180;
549 case CAMERA3_STREAM_ROTATION_270:
550 return StreamRotation::ROTATION_270;
551 }
552 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
553 return StreamRotation::ROTATION_0;
554}
555
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800556status_t Camera3Device::mapToStreamConfigurationMode(
557 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
558 if (mode == nullptr) return BAD_VALUE;
559 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
560 switch(operationMode) {
561 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
562 *mode = StreamConfigurationMode::NORMAL_MODE;
563 break;
564 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
565 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
566 break;
567 default:
568 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
569 return BAD_VALUE;
570 }
571 } else {
572 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800573 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800574 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800575}
576
577camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
578 switch (status) {
579 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
580 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
581 }
582 return CAMERA3_BUFFER_STATUS_ERROR;
583}
584
585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700606 // Get max jpeg size (area-wise).
607 Size maxJpegResolution = getMaxJpegResolution();
608 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
610 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 return BAD_VALUE;
612 }
613
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 // Get max jpeg buffer size
615 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
617 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
619 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700620 return BAD_VALUE;
621 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700622 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800623 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700624
625 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 float scaleFactor = ((float) (width * height)) /
627 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800628 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
629 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 if (jpegBufferSize > maxJpegBufferSize) {
631 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 }
633
634 return jpegBufferSize;
635}
636
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637ssize_t Camera3Device::getPointCloudBufferSize() const {
638 const int FLOATS_PER_POINT=4;
639 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
640 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
642 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700643 return BAD_VALUE;
644 }
645 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
646 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
647 return maxBytesForPointCloud;
648}
649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800650ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 const int PER_CONFIGURATION_SIZE = 3;
652 const int WIDTH_OFFSET = 0;
653 const int HEIGHT_OFFSET = 1;
654 const int SIZE_OFFSET = 2;
655 camera_metadata_ro_entry rawOpaqueSizes =
656 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800657 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800658 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800659 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
660 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 return BAD_VALUE;
662 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800664 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
665 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
666 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
667 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
668 }
669 }
670
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
672 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 return BAD_VALUE;
674}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700675
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
677 ATRACE_CALL();
678 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700679
680 // Try to lock, but continue in case of failure (to avoid blocking in
681 // deadlocks)
682 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
683 bool gotLock = tryLockSpinRightRound(mLock);
684
685 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
687 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700688 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800689 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
690 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800692 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700693
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800694 String16 templatesOption("-t");
695 int n = args.size();
696 for (int i = 0; i < n; i++) {
697 if (args[i] == templatesOption) {
698 dumpTemplates = true;
699 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000700 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700701 if (i + 1 < n) {
702 String8 monitorTags = String8(args[i + 1]);
703 if (monitorTags == "off") {
704 mTagMonitor.disableMonitoring();
705 } else {
706 mTagMonitor.parseTagsToMonitor(monitorTags);
707 }
708 } else {
709 mTagMonitor.disableMonitoring();
710 }
711 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 }
713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 const char *status =
717 mStatus == STATUS_ERROR ? "ERROR" :
718 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
720 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800721 mStatus == STATUS_ACTIVE ? "ACTIVE" :
722 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700725 if (mStatus == STATUS_ERROR) {
726 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
727 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800729 const char *mode =
730 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
731 mOperatingMode == static_cast<int>(
732 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
733 "CUSTOM";
734 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800735
736 if (mInputStream != NULL) {
737 write(fd, lines.string(), lines.size());
738 mInputStream->dump(fd, args);
739 } else {
740 lines.appendFormat(" No input stream.\n");
741 write(fd, lines.string(), lines.size());
742 }
743 for (size_t i = 0; i < mOutputStreams.size(); i++) {
744 mOutputStreams[i]->dump(fd,args);
745 }
746
Zhijun He431503c2016-03-07 17:30:16 -0800747 if (mBufferManager != NULL) {
748 lines = String8(" Camera3 Buffer Manager:\n");
749 write(fd, lines.string(), lines.size());
750 mBufferManager->dump(fd, args);
751 }
Zhijun He125684a2015-12-26 15:07:30 -0800752
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" In-flight requests:\n");
754 if (mInFlightMap.size() == 0) {
755 lines.append(" None\n");
756 } else {
757 for (size_t i = 0; i < mInFlightMap.size(); i++) {
758 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700759 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700760 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800761 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700762 r.numBuffersLeft);
763 }
764 }
765 write(fd, lines.string(), lines.size());
766
Shuzhen Wang686f6442017-06-20 16:16:04 -0700767 if (mRequestThread != NULL) {
768 mRequestThread->dumpCaptureRequestLatency(fd,
769 " ProcessCaptureRequest latency histogram:");
770 }
771
Igor Murashkin1e479c02013-09-06 16:55:14 -0700772 {
773 lines = String8(" Last request sent:\n");
774 write(fd, lines.string(), lines.size());
775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700777 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
778 }
779
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800780 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800781 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800782 "TEMPLATE_PREVIEW",
783 "TEMPLATE_STILL_CAPTURE",
784 "TEMPLATE_VIDEO_RECORD",
785 "TEMPLATE_VIDEO_SNAPSHOT",
786 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800787 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800788 };
789
790 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 camera_metadata_t *templateRequest = nullptr;
792 mInterface->constructDefaultRequestSettings(
793 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800795 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800796 lines.append(" Not supported\n");
797 write(fd, lines.string(), lines.size());
798 } else {
799 write(fd, lines.string(), lines.size());
800 dump_indented_camera_metadata(templateRequest,
801 fd, /*verbosity*/2, /*indentation*/8);
802 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800803 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 }
805 }
806
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700807 mTagMonitor.dumpMonitoredMetadata(fd);
808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800809 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800810 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800811 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800812 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700815 if (gotLock) mLock.unlock();
816 if (gotInterfaceLock) mInterfaceLock.unlock();
817
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800818 return OK;
819}
820
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700821const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800822 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
824 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700825 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800826 mStatus == STATUS_ERROR ?
827 "when in error state" : "before init");
828 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700829 if (physicalId.isEmpty()) {
830 return mDeviceInfo;
831 } else {
832 std::string id(physicalId.c_str());
833 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
834 return mPhysicalDeviceInfoMap.at(id);
835 } else {
836 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
837 return mDeviceInfo;
838 }
839 }
840}
841
842const CameraMetadata& Camera3Device::info() const {
843 String8 emptyId;
844 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845}
846
Jianing Wei90e59c92014-03-12 18:29:36 -0700847status_t Camera3Device::checkStatusOkToCaptureLocked() {
848 switch (mStatus) {
849 case STATUS_ERROR:
850 CLOGE("Device has encountered a serious error");
851 return INVALID_OPERATION;
852 case STATUS_UNINITIALIZED:
853 CLOGE("Device not initialized");
854 return INVALID_OPERATION;
855 case STATUS_UNCONFIGURED:
856 case STATUS_CONFIGURED:
857 case STATUS_ACTIVE:
858 // OK
859 break;
860 default:
861 SET_ERR_L("Unexpected status: %d", mStatus);
862 return INVALID_OPERATION;
863 }
864 return OK;
865}
866
867status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 const std::list<const SurfaceMap> &surfaceMaps,
870 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700871 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700872 if (requestList == NULL) {
873 CLOGE("requestList cannot be NULL.");
874 return BAD_VALUE;
875 }
876
Jianing Weicb0652e2014-03-12 18:29:36 -0700877 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
880 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
881 ++metadataIt, ++surfaceMapIt) {
882 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 if (newRequest == 0) {
884 CLOGE("Can't create capture request");
885 return BAD_VALUE;
886 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700887
Shuzhen Wang9d066012016-09-30 11:30:20 -0700888 newRequest->mRepeating = repeating;
889
Jianing Weicb0652e2014-03-12 18:29:36 -0700890 // Setup burst Id and request Id
891 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000892 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
893 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700894 CLOGE("RequestID entry exists; but must not be empty in metadata");
895 return BAD_VALUE;
896 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000897 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
898 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700899 } else {
900 CLOGE("RequestID does not exist in metadata");
901 return BAD_VALUE;
902 }
903
Jianing Wei90e59c92014-03-12 18:29:36 -0700904 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700905
906 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700907 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700908 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
909 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
910 return BAD_VALUE;
911 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700912
913 // Setup batch size if this is a high speed video recording request.
914 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
915 auto firstRequest = requestList->begin();
916 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
917 if (outputStream->isVideoStream()) {
918 (*firstRequest)->mBatchSize = requestList->size();
919 break;
920 }
921 }
922 }
923
Jianing Wei90e59c92014-03-12 18:29:36 -0700924 return OK;
925}
926
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800927status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800928 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800929
Emilian Peevaebbe412018-01-15 13:53:24 +0000930 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700931 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000932 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800934 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935}
936
Emilian Peevaebbe412018-01-15 13:53:24 +0000937void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700938 std::list<const SurfaceMap>& surfaceMaps,
939 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000940 PhysicalCameraSettingsList requestList;
941 requestList.push_back({std::string(getId().string()), request});
942 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700943
944 SurfaceMap surfaceMap;
945 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
946 // With no surface list passed in, stream and surface will have 1-to-1
947 // mapping. So the surface index is 0 for each stream in the surfaceMap.
948 for (size_t i = 0; i < streams.count; i++) {
949 surfaceMap[streams.data.i32[i]].push_back(0);
950 }
951 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800952}
953
Jianing Wei90e59c92014-03-12 18:29:36 -0700954status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000955 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700956 const std::list<const SurfaceMap> &surfaceMaps,
957 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700958 /*out*/
959 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 ATRACE_CALL();
961 Mutex::Autolock il(mInterfaceLock);
962 Mutex::Autolock l(mLock);
963
964 status_t res = checkStatusOkToCaptureLocked();
965 if (res != OK) {
966 // error logged by previous call
967 return res;
968 }
969
970 RequestList requestList;
971
Shuzhen Wang0129d522016-10-30 22:43:41 -0700972 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
973 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700974 if (res != OK) {
975 // error logged by previous call
976 return res;
977 }
978
979 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700980 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700981 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700982 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700983 }
984
985 if (res == OK) {
986 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
987 if (res != OK) {
988 SET_ERR_L("Can't transition to active in %f seconds!",
989 kActiveTimeout/1e9);
990 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800991 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700992 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 } else {
994 CLOGE("Cannot queue request. Impossible.");
995 return BAD_VALUE;
996 }
997
998 return res;
999}
1000
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001001hardware::Return<void> Camera3Device::requestStreamBuffers(
1002 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1003 requestStreamBuffers_cb _hidl_cb) {
1004 using hardware::camera::device::V3_5::BufferRequestStatus;
1005 using hardware::camera::device::V3_5::StreamBufferRet;
1006 using hardware::camera::device::V3_5::StreamBufferRequestError;
1007
1008 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
1009
1010 hardware::hidl_vec<StreamBufferRet> bufRets;
1011 if (!mUseHalBufManager) {
1012 ALOGE("%s: Camera %s does not support HAL buffer management",
1013 __FUNCTION__, mId.string());
1014 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1015 return hardware::Void();
1016 }
1017
1018 SortedVector<int32_t> streamIds;
1019 ssize_t sz = streamIds.setCapacity(bufReqs.size());
1020 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1021 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1022 __FUNCTION__, bufReqs.size());
1023 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1024 return hardware::Void();
1025 }
1026
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001027 if (bufReqs.size() > mOutputStreams.size()) {
1028 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1029 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1030 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1031 return hardware::Void();
1032 }
1033
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001034 // Check for repeated streamId
1035 for (const auto& bufReq : bufReqs) {
1036 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1037 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1038 __FUNCTION__, bufReq.streamId);
1039 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1040 return hardware::Void();
1041 }
1042 streamIds.add(bufReq.streamId);
1043 }
1044
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001045 if (!mRequestBufferSM.startRequestBuffer()) {
1046 ALOGE("%s: request buffer disallowed while camera service is configuring",
1047 __FUNCTION__);
1048 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001049 return hardware::Void();
1050 }
1051
1052 bufRets.resize(bufReqs.size());
1053
1054 bool allReqsSucceeds = true;
1055 bool oneReqSucceeds = false;
1056 for (size_t i = 0; i < bufReqs.size(); i++) {
1057 const auto& bufReq = bufReqs[i];
1058 auto& bufRet = bufRets[i];
1059 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001060 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1061 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001062 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1063 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1064 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001065 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001066 return hardware::Void();
1067 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001068
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001069 if (outputStream->isAbandoned()) {
1070 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1071 allReqsSucceeds = false;
1072 continue;
1073 }
1074
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001075 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001076 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001077 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001078 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1079 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1080 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001081 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001082 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1083 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1084 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001085 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1086 allReqsSucceeds = false;
1087 continue;
1088 }
1089
1090 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1091 bool currentReqSucceeds = true;
1092 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1093 size_t numAllocatedBuffers = 0;
1094 size_t numPushedInflightBuffers = 0;
1095 for (size_t b = 0; b < numBuffersRequested; b++) {
1096 camera3_stream_buffer_t& sb = streamBuffers[b];
1097 // Since this method can run concurrently with request thread
1098 // We need to update the wait duration everytime we call getbuffer
1099 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1100 status_t res = outputStream->getBuffer(&sb, waitDuration);
1101 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001102 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001103 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1104 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001105 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001106 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001107 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1108 __FUNCTION__, streamId, strerror(-res), res);
1109 if (res == TIMED_OUT || res == NO_MEMORY) {
1110 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1111 } else {
1112 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1113 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001114 }
1115 currentReqSucceeds = false;
1116 break;
1117 }
1118 numAllocatedBuffers++;
1119
1120 buffer_handle_t *buffer = sb.buffer;
1121 auto pair = mInterface->getBufferId(*buffer, streamId);
1122 bool isNewBuffer = pair.first;
1123 uint64_t bufferId = pair.second;
1124 StreamBuffer& hBuf = tmpRetBuffers[b];
1125
1126 hBuf.streamId = streamId;
1127 hBuf.bufferId = bufferId;
1128 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1129 hBuf.status = BufferStatus::OK;
1130 hBuf.releaseFence = nullptr;
1131
1132 native_handle_t *acquireFence = nullptr;
1133 if (sb.acquire_fence != -1) {
1134 acquireFence = native_handle_create(1,0);
1135 acquireFence->data[0] = sb.acquire_fence;
1136 }
1137 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1138 hBuf.releaseFence = nullptr;
1139
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001140 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001141 if (res != OK) {
1142 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1143 __FUNCTION__, streamId, strerror(-res), res);
1144 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1145 currentReqSucceeds = false;
1146 break;
1147 }
1148 numPushedInflightBuffers++;
1149 }
1150 if (currentReqSucceeds) {
1151 bufRet.val.buffers(std::move(tmpRetBuffers));
1152 oneReqSucceeds = true;
1153 } else {
1154 allReqsSucceeds = false;
1155 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1156 StreamBuffer& hBuf = tmpRetBuffers[b];
1157 buffer_handle_t* buffer;
1158 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1159 if (res != OK) {
1160 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1161 __FUNCTION__, streamId, strerror(-res), res);
1162 }
1163 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001164 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1165 camera3_stream_buffer_t& sb = streamBuffers[b];
1166 sb.acquire_fence = -1;
1167 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1168 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001169 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1170 }
1171 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001172
1173 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1174 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1175 BufferRequestStatus::FAILED_UNKNOWN,
1176 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001177 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001178 return hardware::Void();
1179}
1180
1181hardware::Return<void> Camera3Device::returnStreamBuffers(
1182 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1183 if (!mUseHalBufManager) {
1184 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1185 __FUNCTION__, mId.string());
1186 return hardware::Void();
1187 }
1188
1189 for (const auto& buf : buffers) {
1190 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1191 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1192 continue;
1193 }
1194
1195 buffer_handle_t* buffer;
1196 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1197
1198 if (res != OK) {
1199 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1200 __FUNCTION__, buf.bufferId, buf.streamId);
1201 continue;
1202 }
1203
1204 camera3_stream_buffer_t streamBuffer;
1205 streamBuffer.buffer = buffer;
1206 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1207 streamBuffer.acquire_fence = -1;
1208 streamBuffer.release_fence = -1;
1209
1210 if (buf.releaseFence == nullptr) {
1211 streamBuffer.release_fence = -1;
1212 } else if (buf.releaseFence->numFds == 1) {
1213 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1214 } else {
1215 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1216 __FUNCTION__, buf.releaseFence->numFds);
1217 continue;
1218 }
1219
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001220 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1221 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001222 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1223 continue;
1224 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001225 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001226 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1227 }
1228 return hardware::Void();
1229}
1230
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001231hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001232 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001233 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001234 // Ideally we should grab mLock, but that can lead to deadlock, and
1235 // it's not super important to get up to date value of mStatus for this
1236 // warning print, hence skipping the lock here
1237 if (mStatus == STATUS_ERROR) {
1238 // Per API contract, HAL should act as closed after device error
1239 // But mStatus can be set to error by framework as well, so just log
1240 // a warning here.
1241 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001242 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001243
1244 if (mProcessCaptureResultLock.tryLock() != OK) {
1245 // This should never happen; it indicates a wrong client implementation
1246 // that doesn't follow the contract. But, we can be tolerant here.
1247 ALOGE("%s: callback overlapped! waiting 1s...",
1248 __FUNCTION__);
1249 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1250 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1251 __FUNCTION__);
1252 // really don't know what to do, so bail out.
1253 return hardware::Void();
1254 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001255 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001256 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001257 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001258 }
1259 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001260 return hardware::Void();
1261}
1262
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001263// Only one processCaptureResult should be called at a time, so
1264// the locks won't block. The locks are present here simply to enforce this.
1265hardware::Return<void> Camera3Device::processCaptureResult(
1266 const hardware::hidl_vec<
1267 hardware::camera::device::V3_2::CaptureResult>& results) {
1268 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1269
1270 // Ideally we should grab mLock, but that can lead to deadlock, and
1271 // it's not super important to get up to date value of mStatus for this
1272 // warning print, hence skipping the lock here
1273 if (mStatus == STATUS_ERROR) {
1274 // Per API contract, HAL should act as closed after device error
1275 // But mStatus can be set to error by framework as well, so just log
1276 // a warning here.
1277 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1278 }
1279
1280 if (mProcessCaptureResultLock.tryLock() != OK) {
1281 // This should never happen; it indicates a wrong client implementation
1282 // that doesn't follow the contract. But, we can be tolerant here.
1283 ALOGE("%s: callback overlapped! waiting 1s...",
1284 __FUNCTION__);
1285 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1286 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1287 __FUNCTION__);
1288 // really don't know what to do, so bail out.
1289 return hardware::Void();
1290 }
1291 }
1292 for (const auto& result : results) {
1293 processOneCaptureResultLocked(result, noPhysMetadata);
1294 }
1295 mProcessCaptureResultLock.unlock();
1296 return hardware::Void();
1297}
1298
1299status_t Camera3Device::readOneCameraMetadataLocked(
1300 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1301 const hardware::camera::device::V3_2::CameraMetadata& result) {
1302 if (fmqResultSize > 0) {
1303 resultMetadata.resize(fmqResultSize);
1304 if (mResultMetadataQueue == nullptr) {
1305 return NO_MEMORY; // logged in initialize()
1306 }
1307 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1308 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1309 __FUNCTION__, fmqResultSize);
1310 return INVALID_OPERATION;
1311 }
1312 } else {
1313 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1314 result.size());
1315 }
1316
1317 if (resultMetadata.size() != 0) {
1318 status_t res;
1319 const camera_metadata_t* metadata =
1320 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1321 size_t expected_metadata_size = resultMetadata.size();
1322 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1323 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1324 __FUNCTION__, strerror(-res), res);
1325 return INVALID_OPERATION;
1326 }
1327 }
1328
1329 return OK;
1330}
1331
Yifan Honga640c5a2017-04-12 16:30:31 -07001332void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001333 const hardware::camera::device::V3_2::CaptureResult& result,
1334 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001335 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001336 camera3_capture_result r;
1337 status_t res;
1338 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001339
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001340 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001341 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001342 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1343 if (res != OK) {
1344 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1345 __FUNCTION__, result.frameNumber);
1346 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001347 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001348 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001349
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001350 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001351 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001352 std::vector<const char*> physCamIds(physResultCount);
1353 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1354 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1355 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001356 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1357 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1358 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001359 if (res != OK) {
1360 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1361 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001362 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001363 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001364 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001365 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001366 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1367 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001369 r.num_physcam_metadata = physResultCount;
1370 r.physcam_ids = physCamIds.data();
1371 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001372
1373 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1374 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1375 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1376 auto& bDst = outputBuffers[i];
1377 const StreamBuffer &bSrc = result.outputBuffers[i];
1378
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001379 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1380 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001381 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1382 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001383 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001384 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001385 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001386
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001387 bool noBufferReturned = false;
1388 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001389 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001390 // This is suspicious most of the time but can be correct during flush where HAL
1391 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001392 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001393 if (bSrc.status == BufferStatus::OK) {
1394 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1395 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1396 // Still proceeds so other buffers can be returned
1397 }
1398 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001399 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001400 if (noBufferReturned) {
1401 res = OK;
1402 } else {
1403 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1404 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001405 } else {
1406 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1407 }
1408
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 if (res != OK) {
1410 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1411 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001412 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001413 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001414
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001415 bDst.buffer = buffer;
1416 bDst.status = mapHidlBufferStatus(bSrc.status);
1417 bDst.acquire_fence = -1;
1418 if (bSrc.releaseFence == nullptr) {
1419 bDst.release_fence = -1;
1420 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001421 if (noBufferReturned) {
1422 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1423 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001424 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1425 } else {
1426 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1427 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001428 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001429 }
1430 }
1431 r.num_output_buffers = outputBuffers.size();
1432 r.output_buffers = outputBuffers.data();
1433
1434 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001435 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001436 r.input_buffer = nullptr;
1437 } else {
1438 if (mInputStream->getId() != result.inputBuffer.streamId) {
1439 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1440 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001441 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001442 }
1443 inputBuffer.stream = mInputStream->asHalStream();
1444 buffer_handle_t *buffer;
1445 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1446 &buffer);
1447 if (res != OK) {
1448 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1449 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001450 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001451 }
1452 inputBuffer.buffer = buffer;
1453 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1454 inputBuffer.acquire_fence = -1;
1455 if (result.inputBuffer.releaseFence == nullptr) {
1456 inputBuffer.release_fence = -1;
1457 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1458 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1459 } else {
1460 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1461 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001462 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001463 }
1464 r.input_buffer = &inputBuffer;
1465 }
1466
1467 r.partial_result = result.partialResult;
1468
1469 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001470}
1471
1472hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001473 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001474 // Ideally we should grab mLock, but that can lead to deadlock, and
1475 // it's not super important to get up to date value of mStatus for this
1476 // warning print, hence skipping the lock here
1477 if (mStatus == STATUS_ERROR) {
1478 // Per API contract, HAL should act as closed after device error
1479 // But mStatus can be set to error by framework as well, so just log
1480 // a warning here.
1481 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001482 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001483
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001484 for (const auto& msg : msgs) {
1485 notify(msg);
1486 }
1487 return hardware::Void();
1488}
1489
1490void Camera3Device::notify(
1491 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1492
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001493 camera3_notify_msg m;
1494 switch (msg.type) {
1495 case MsgType::ERROR:
1496 m.type = CAMERA3_MSG_ERROR;
1497 m.message.error.frame_number = msg.msg.error.frameNumber;
1498 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001499 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1500 if (stream == nullptr) {
1501 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1502 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001503 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001504 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001505 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001506 } else {
1507 m.message.error.error_stream = nullptr;
1508 }
1509 switch (msg.msg.error.errorCode) {
1510 case ErrorCode::ERROR_DEVICE:
1511 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1512 break;
1513 case ErrorCode::ERROR_REQUEST:
1514 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1515 break;
1516 case ErrorCode::ERROR_RESULT:
1517 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1518 break;
1519 case ErrorCode::ERROR_BUFFER:
1520 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1521 break;
1522 }
1523 break;
1524 case MsgType::SHUTTER:
1525 m.type = CAMERA3_MSG_SHUTTER;
1526 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1527 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1528 break;
1529 }
1530 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001531}
1532
Emilian Peevaebbe412018-01-15 13:53:24 +00001533status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001534 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001535 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001536 ATRACE_CALL();
1537
Emilian Peevaebbe412018-01-15 13:53:24 +00001538 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001539}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540
Jianing Weicb0652e2014-03-12 18:29:36 -07001541status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1542 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001543 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544
Emilian Peevaebbe412018-01-15 13:53:24 +00001545 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001546 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001547 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001548
Emilian Peevaebbe412018-01-15 13:53:24 +00001549 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001550 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551}
1552
Emilian Peevaebbe412018-01-15 13:53:24 +00001553status_t Camera3Device::setStreamingRequestList(
1554 const List<const PhysicalCameraSettingsList> &requestsList,
1555 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001556 ATRACE_CALL();
1557
Emilian Peevaebbe412018-01-15 13:53:24 +00001558 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001559}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560
1561sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001562 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 status_t res;
1564
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001566 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1567 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001568 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1569 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001570 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001572 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001574 } else if (mStatus == STATUS_UNCONFIGURED) {
1575 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 CLOGE("No streams configured");
1577 return NULL;
1578 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 }
1580
Shuzhen Wang0129d522016-10-30 22:43:41 -07001581 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001582 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001583}
1584
Jianing Weicb0652e2014-03-12 18:29:36 -07001585status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590 switch (mStatus) {
1591 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001592 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 return INVALID_OPERATION;
1594 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001595 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 case STATUS_UNCONFIGURED:
1598 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 case STATUS_ACTIVE:
1600 // OK
1601 break;
1602 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001603 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 return INVALID_OPERATION;
1605 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001606 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001607
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001608 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001609}
1610
1611status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1612 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001615 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616}
1617
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001618status_t Camera3Device::createInputStream(
1619 uint32_t width, uint32_t height, int format, int *id) {
1620 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001622 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001623 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001624 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1625 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626
1627 status_t res;
1628 bool wasActive = false;
1629
1630 switch (mStatus) {
1631 case STATUS_ERROR:
1632 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1633 return INVALID_OPERATION;
1634 case STATUS_UNINITIALIZED:
1635 ALOGE("%s: Device not initialized", __FUNCTION__);
1636 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 case STATUS_UNCONFIGURED:
1638 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001639 // OK
1640 break;
1641 case STATUS_ACTIVE:
1642 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001643 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001644 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001646 return res;
1647 }
1648 wasActive = true;
1649 break;
1650 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001652 return INVALID_OPERATION;
1653 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001654 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001655
1656 if (mInputStream != 0) {
1657 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1658 return INVALID_OPERATION;
1659 }
1660
1661 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1662 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001664
1665 mInputStream = newStream;
1666
1667 *id = mNextStreamId++;
1668
1669 // Continue captures if active at start
1670 if (wasActive) {
1671 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001672 // Reuse current operating mode and session parameters for new stream config
1673 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001674 if (res != OK) {
1675 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1676 __FUNCTION__, mNextStreamId, strerror(-res), res);
1677 return res;
1678 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001680 }
1681
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001682 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001683 return OK;
1684}
1685
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001686status_t Camera3Device::StreamSet::add(
1687 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1688 if (stream == nullptr) {
1689 ALOGE("%s: cannot add null stream", __FUNCTION__);
1690 return BAD_VALUE;
1691 }
1692 std::lock_guard<std::mutex> lock(mLock);
1693 return mData.add(streamId, stream);
1694}
1695
1696ssize_t Camera3Device::StreamSet::remove(int streamId) {
1697 std::lock_guard<std::mutex> lock(mLock);
1698 return mData.removeItem(streamId);
1699}
1700
1701sp<camera3::Camera3OutputStreamInterface>
1702Camera3Device::StreamSet::get(int streamId) {
1703 std::lock_guard<std::mutex> lock(mLock);
1704 ssize_t idx = mData.indexOfKey(streamId);
1705 if (idx == NAME_NOT_FOUND) {
1706 return nullptr;
1707 }
1708 return mData.editValueAt(idx);
1709}
1710
1711sp<camera3::Camera3OutputStreamInterface>
1712Camera3Device::StreamSet::operator[] (size_t index) {
1713 std::lock_guard<std::mutex> lock(mLock);
1714 return mData.editValueAt(index);
1715}
1716
1717size_t Camera3Device::StreamSet::size() const {
1718 std::lock_guard<std::mutex> lock(mLock);
1719 return mData.size();
1720}
1721
1722void Camera3Device::StreamSet::clear() {
1723 std::lock_guard<std::mutex> lock(mLock);
1724 return mData.clear();
1725}
1726
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001727std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1728 std::lock_guard<std::mutex> lock(mLock);
1729 std::vector<int> streamIds(mData.size());
1730 for (size_t i = 0; i < mData.size(); i++) {
1731 streamIds[i] = mData.keyAt(i);
1732 }
1733 return streamIds;
1734}
1735
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001736status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001737 uint32_t width, uint32_t height, int format,
1738 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001739 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001740 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001741 ATRACE_CALL();
1742
1743 if (consumer == nullptr) {
1744 ALOGE("%s: consumer must not be null", __FUNCTION__);
1745 return BAD_VALUE;
1746 }
1747
1748 std::vector<sp<Surface>> consumers;
1749 consumers.push_back(consumer);
1750
1751 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001752 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1753 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001754}
1755
1756status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1757 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1758 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001759 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001760 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001762
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001763 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001764 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001766 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001767 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1768 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1769 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771 status_t res;
1772 bool wasActive = false;
1773
1774 switch (mStatus) {
1775 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001776 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 return INVALID_OPERATION;
1778 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001779 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001780 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001781 case STATUS_UNCONFIGURED:
1782 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001783 // OK
1784 break;
1785 case STATUS_ACTIVE:
1786 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001787 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001788 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001790 return res;
1791 }
1792 wasActive = true;
1793 break;
1794 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001795 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001796 return INVALID_OPERATION;
1797 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001799
1800 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001801
Shuzhen Wang0129d522016-10-30 22:43:41 -07001802 if (consumers.size() == 0 && !hasDeferredConsumer) {
1803 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1804 return BAD_VALUE;
1805 }
Zhijun He5d677d12016-05-29 16:52:39 -07001806
Shuzhen Wang0129d522016-10-30 22:43:41 -07001807 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001808 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1809 return BAD_VALUE;
1810 }
1811
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001812 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001813 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001814 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001815 blobBufferSize = getPointCloudBufferSize();
1816 if (blobBufferSize <= 0) {
1817 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1818 return BAD_VALUE;
1819 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001820 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1821 blobBufferSize = width * height;
1822 } else {
1823 blobBufferSize = getJpegBufferSize(width, height);
1824 if (blobBufferSize <= 0) {
1825 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1826 return BAD_VALUE;
1827 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001828 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001829 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001830 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001831 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001832 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1833 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1834 if (rawOpaqueBufferSize <= 0) {
1835 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1836 return BAD_VALUE;
1837 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001838 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001839 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001840 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001841 } else if (isShared) {
1842 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1843 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001844 mTimestampOffset, physicalCameraId, streamSetId,
1845 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001846 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001847 newStream = new Camera3OutputStream(mNextStreamId,
1848 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001849 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001850 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001851 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001852 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001853 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 }
Emilian Peev40ead602017-09-26 15:46:36 +01001855
1856 size_t consumerCount = consumers.size();
1857 for (size_t i = 0; i < consumerCount; i++) {
1858 int id = newStream->getSurfaceId(consumers[i]);
1859 if (id < 0) {
1860 SET_ERR_L("Invalid surface id");
1861 return BAD_VALUE;
1862 }
1863 if (surfaceIds != nullptr) {
1864 surfaceIds->push_back(id);
1865 }
1866 }
1867
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001868 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001869
Emilian Peev08dd2452017-04-06 16:55:14 +01001870 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001871
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872 res = mOutputStreams.add(mNextStreamId, newStream);
1873 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001874 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001875 return res;
1876 }
1877
1878 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001879 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001880
1881 // Continue captures if active at start
1882 if (wasActive) {
1883 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001884 // Reuse current operating mode and session parameters for new stream config
1885 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001886 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001887 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1888 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889 return res;
1890 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001892 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001893 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001894 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895}
1896
Emilian Peev710c1422017-08-30 11:19:38 +01001897status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001898 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001899 if (nullptr == streamInfo) {
1900 return BAD_VALUE;
1901 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001902 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001903 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001904
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 switch (mStatus) {
1906 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001907 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001908 return INVALID_OPERATION;
1909 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001910 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001911 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001912 case STATUS_UNCONFIGURED:
1913 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001914 case STATUS_ACTIVE:
1915 // OK
1916 break;
1917 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001918 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919 return INVALID_OPERATION;
1920 }
1921
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001922 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1923 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001924 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001925 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001926 }
1927
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001928 streamInfo->width = stream->getWidth();
1929 streamInfo->height = stream->getHeight();
1930 streamInfo->format = stream->getFormat();
1931 streamInfo->dataSpace = stream->getDataSpace();
1932 streamInfo->formatOverridden = stream->isFormatOverridden();
1933 streamInfo->originalFormat = stream->getOriginalFormat();
1934 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1935 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001936 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001937}
1938
1939status_t Camera3Device::setStreamTransform(int id,
1940 int transform) {
1941 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001942 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001943 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001944
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001945 switch (mStatus) {
1946 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001947 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001948 return INVALID_OPERATION;
1949 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001950 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001951 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001952 case STATUS_UNCONFIGURED:
1953 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001954 case STATUS_ACTIVE:
1955 // OK
1956 break;
1957 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001958 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001959 return INVALID_OPERATION;
1960 }
1961
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001962 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1963 if (stream == nullptr) {
1964 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001965 return BAD_VALUE;
1966 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001967 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968}
1969
1970status_t Camera3Device::deleteStream(int id) {
1971 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001972 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001973 Mutex::Autolock l(mLock);
1974 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001975
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001976 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001977
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001978 // CameraDevice semantics require device to already be idle before
1979 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001980 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001981 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001982 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001983 }
1984
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001985 if (mStatus == STATUS_ERROR) {
1986 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1987 __FUNCTION__, mId.string());
1988 return -EBUSY;
1989 }
1990
Igor Murashkin2fba5842013-04-22 14:03:54 -07001991 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001992 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 if (mInputStream != NULL && id == mInputStream->getId()) {
1994 deletedStream = mInputStream;
1995 mInputStream.clear();
1996 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001997 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001998 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001999 return BAD_VALUE;
2000 }
Zhijun He5f446352014-01-22 09:49:33 -08002001 }
2002
2003 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002004 if (stream != nullptr) {
2005 deletedStream = stream;
2006 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002007 }
2008
2009 // Free up the stream endpoint so that it can be used by some other stream
2010 res = deletedStream->disconnect();
2011 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002012 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002013 // fall through since we want to still list the stream as deleted.
2014 }
2015 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002016 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002017
2018 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002019}
2020
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002021status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002022 ATRACE_CALL();
2023 ALOGV("%s: E", __FUNCTION__);
2024
2025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002027
Emilian Peev811d2952018-05-25 11:08:40 +01002028 // In case the client doesn't include any session parameter, try a
2029 // speculative configuration using the values from the last cached
2030 // default request.
2031 if (sessionParams.isEmpty() &&
2032 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2033 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2034 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2035 mLastTemplateId);
2036 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2037 operatingMode);
2038 }
2039
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002040 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2041}
2042
2043status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2044 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002045 //Filter out any incoming session parameters
2046 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002047 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2048 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002049 CameraMetadata filteredParams(availableSessionKeys.count);
2050 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2051 filteredParams.getAndLock());
2052 set_camera_metadata_vendor_id(meta, mVendorTagId);
2053 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002054 if (availableSessionKeys.count > 0) {
2055 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2056 camera_metadata_ro_entry entry = params.find(
2057 availableSessionKeys.data.i32[i]);
2058 if (entry.count > 0) {
2059 filteredParams.update(entry);
2060 }
2061 }
2062 }
2063
2064 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002065}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002067status_t Camera3Device::getInputBufferProducer(
2068 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002069 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002070 Mutex::Autolock il(mInterfaceLock);
2071 Mutex::Autolock l(mLock);
2072
2073 if (producer == NULL) {
2074 return BAD_VALUE;
2075 } else if (mInputStream == NULL) {
2076 return INVALID_OPERATION;
2077 }
2078
2079 return mInputStream->getInputBufferProducer(producer);
2080}
2081
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002082status_t Camera3Device::createDefaultRequest(int templateId,
2083 CameraMetadata *request) {
2084 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002085 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002086
2087 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2088 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002089 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002090 return BAD_VALUE;
2091 }
2092
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002093 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002095 {
2096 Mutex::Autolock l(mLock);
2097 switch (mStatus) {
2098 case STATUS_ERROR:
2099 CLOGE("Device has encountered a serious error");
2100 return INVALID_OPERATION;
2101 case STATUS_UNINITIALIZED:
2102 CLOGE("Device is not initialized!");
2103 return INVALID_OPERATION;
2104 case STATUS_UNCONFIGURED:
2105 case STATUS_CONFIGURED:
2106 case STATUS_ACTIVE:
2107 // OK
2108 break;
2109 default:
2110 SET_ERR_L("Unexpected status: %d", mStatus);
2111 return INVALID_OPERATION;
2112 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002113
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002114 if (!mRequestTemplateCache[templateId].isEmpty()) {
2115 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002116 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002117 return OK;
2118 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002119 }
2120
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002121 camera_metadata_t *rawRequest;
2122 status_t res = mInterface->constructDefaultRequestSettings(
2123 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002124
2125 {
2126 Mutex::Autolock l(mLock);
2127 if (res == BAD_VALUE) {
2128 ALOGI("%s: template %d is not supported on this camera device",
2129 __FUNCTION__, templateId);
2130 return res;
2131 } else if (res != OK) {
2132 CLOGE("Unable to construct request template %d: %s (%d)",
2133 templateId, strerror(-res), res);
2134 return res;
2135 }
2136
2137 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2138 mRequestTemplateCache[templateId].acquire(rawRequest);
2139
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002140 // Override the template request with zoomRatioMapper
2141 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
2142 &mRequestTemplateCache[templateId]);
2143 if (res != OK) {
2144 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
2145 templateId, strerror(-res), res);
2146 return res;
2147 }
2148
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002149 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002150 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002151 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002152 return OK;
2153}
2154
2155status_t Camera3Device::waitUntilDrained() {
2156 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002157 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002158 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002159 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002160
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002161 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002162}
2163
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002164status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 switch (mStatus) {
2166 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002167 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002168 ALOGV("%s: Already idle", __FUNCTION__);
2169 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002170 case STATUS_CONFIGURED:
2171 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002172 case STATUS_ERROR:
2173 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175 break;
2176 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002177 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002178 return INVALID_OPERATION;
2179 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002180 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2181 maxExpectedDuration);
2182 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002183 if (res != OK) {
2184 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2185 res);
2186 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002187 return res;
2188}
2189
Ruben Brunk183f0562015-08-12 12:55:02 -07002190
2191void Camera3Device::internalUpdateStatusLocked(Status status) {
2192 mStatus = status;
2193 mRecentStatusUpdates.add(mStatus);
2194 mStatusChanged.broadcast();
2195}
2196
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002197void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdhary37eca242019-11-18 08:55:56 -08002198 // We must not hold mInterfaceLock here since this function is called from
2199 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2200 // deadlocks (http://b/143513518)
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002201 Mutex::Autolock l(mLock);
2202
2203 mPauseStateNotify = enable;
2204}
2205
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002206// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002207status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002208 if (mRequestThread.get() != nullptr) {
2209 mRequestThread->setPaused(true);
2210 } else {
2211 return NO_INIT;
2212 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002213
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002214 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2215 maxExpectedDuration);
2216 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 if (res != OK) {
2218 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002219 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220 }
2221
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002222 return res;
2223}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225// Resume after internalPauseAndWaitLocked
2226status_t Camera3Device::internalResumeLocked() {
2227 status_t res;
2228
2229 mRequestThread->setPaused(false);
2230
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002231 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2232 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2234 if (res != OK) {
2235 SET_ERR_L("Can't transition to active in %f seconds!",
2236 kActiveTimeout/1e9);
2237 }
2238 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002240}
2241
Ruben Brunk183f0562015-08-12 12:55:02 -07002242status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002243 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002244
2245 size_t startIndex = 0;
2246 if (mStatusWaiters == 0) {
2247 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2248 // this status list
2249 mRecentStatusUpdates.clear();
2250 } else {
2251 // If other threads are waiting on updates to this status list, set the position of the
2252 // first element that this list will check rather than clearing the list.
2253 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002254 }
2255
Ruben Brunk183f0562015-08-12 12:55:02 -07002256 mStatusWaiters++;
2257
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002258 if (!active && mUseHalBufManager) {
2259 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002260 if (mStatus == STATUS_ACTIVE) {
2261 mRequestThread->signalPipelineDrain(streamIds);
2262 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002263 mRequestBufferSM.onWaitUntilIdle();
2264 }
2265
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002266 bool stateSeen = false;
2267 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002268 if (active == (mStatus == STATUS_ACTIVE)) {
2269 // Desired state is current
2270 break;
2271 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002272
2273 res = mStatusChanged.waitRelative(mLock, timeout);
2274 if (res != OK) break;
2275
Ruben Brunk183f0562015-08-12 12:55:02 -07002276 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2277 // transitions.
2278 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2279 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2280 __FUNCTION__);
2281
2282 // Encountered desired state since we began waiting
2283 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002284 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2285 stateSeen = true;
2286 break;
2287 }
2288 }
2289 } while (!stateSeen);
2290
Ruben Brunk183f0562015-08-12 12:55:02 -07002291 mStatusWaiters--;
2292
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002293 return res;
2294}
2295
2296
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002297status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002298 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002299 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002300
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002301 if (listener != NULL && mListener != NULL) {
2302 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2303 }
2304 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002305 mRequestThread->setNotificationListener(listener);
2306 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002307
2308 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309}
2310
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002311bool Camera3Device::willNotify3A() {
2312 return false;
2313}
2314
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002315status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002316 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002317 status_t res;
2318 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002319
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002320 while (mResultQueue.empty()) {
2321 res = mResultSignal.waitRelative(mOutputLock, timeout);
2322 if (res == TIMED_OUT) {
2323 return res;
2324 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002325 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2326 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002327 return res;
2328 }
2329 }
2330 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002331}
2332
Jianing Weicb0652e2014-03-12 18:29:36 -07002333status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002334 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002335 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002336
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002337 if (mResultQueue.empty()) {
2338 return NOT_ENOUGH_DATA;
2339 }
2340
Jianing Weicb0652e2014-03-12 18:29:36 -07002341 if (frame == NULL) {
2342 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2343 return BAD_VALUE;
2344 }
2345
2346 CaptureResult &result = *(mResultQueue.begin());
2347 frame->mResultExtras = result.mResultExtras;
2348 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002349 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002350 mResultQueue.erase(mResultQueue.begin());
2351
2352 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002353}
2354
2355status_t Camera3Device::triggerAutofocus(uint32_t id) {
2356 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002357 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002358
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002359 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2360 // Mix-in this trigger into the next request and only the next request.
2361 RequestTrigger trigger[] = {
2362 {
2363 ANDROID_CONTROL_AF_TRIGGER,
2364 ANDROID_CONTROL_AF_TRIGGER_START
2365 },
2366 {
2367 ANDROID_CONTROL_AF_TRIGGER_ID,
2368 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002369 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002370 };
2371
2372 return mRequestThread->queueTrigger(trigger,
2373 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002374}
2375
2376status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2377 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002378 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002379
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002380 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2381 // Mix-in this trigger into the next request and only the next request.
2382 RequestTrigger trigger[] = {
2383 {
2384 ANDROID_CONTROL_AF_TRIGGER,
2385 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2386 },
2387 {
2388 ANDROID_CONTROL_AF_TRIGGER_ID,
2389 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002390 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002391 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002392
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002393 return mRequestThread->queueTrigger(trigger,
2394 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002395}
2396
2397status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2398 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002399 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002400
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002401 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2402 // Mix-in this trigger into the next request and only the next request.
2403 RequestTrigger trigger[] = {
2404 {
2405 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2406 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2407 },
2408 {
2409 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2410 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002411 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002412 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002413
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002414 return mRequestThread->queueTrigger(trigger,
2415 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002416}
2417
Jianing Weicb0652e2014-03-12 18:29:36 -07002418status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002419 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002420 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002421 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002422
Zhijun He7ef20392014-04-21 16:04:17 -07002423 {
2424 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002425
2426 // b/116514106 "disconnect()" can get called twice for the same device. The
2427 // camera device will not be initialized during the second run.
2428 if (mStatus == STATUS_UNINITIALIZED) {
2429 return OK;
2430 }
2431
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002432 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002433 }
2434
Emilian Peev08dd2452017-04-06 16:55:14 +01002435 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002436}
2437
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002438status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002439 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2440}
2441
2442status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002443 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002444 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002445 Mutex::Autolock il(mInterfaceLock);
2446 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002447
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002448 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2449 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002450 CLOGE("Stream %d does not exist", streamId);
2451 return BAD_VALUE;
2452 }
2453
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002454 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002455 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002456 return BAD_VALUE;
2457 }
2458
2459 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002460 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002461 return BAD_VALUE;
2462 }
2463
Ruben Brunkc78ac262015-08-13 17:58:46 -07002464 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002465}
2466
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002467status_t Camera3Device::tearDown(int streamId) {
2468 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002469 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002470 Mutex::Autolock il(mInterfaceLock);
2471 Mutex::Autolock l(mLock);
2472
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002473 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2474 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002475 CLOGE("Stream %d does not exist", streamId);
2476 return BAD_VALUE;
2477 }
2478
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002479 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2480 CLOGE("Stream %d is a target of a in-progress request", streamId);
2481 return BAD_VALUE;
2482 }
2483
2484 return stream->tearDown();
2485}
2486
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002487status_t Camera3Device::addBufferListenerForStream(int streamId,
2488 wp<Camera3StreamBufferListener> listener) {
2489 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002490 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002491 Mutex::Autolock il(mInterfaceLock);
2492 Mutex::Autolock l(mLock);
2493
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002494 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2495 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002496 CLOGE("Stream %d does not exist", streamId);
2497 return BAD_VALUE;
2498 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002499 stream->addBufferListener(listener);
2500
2501 return OK;
2502}
2503
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002504/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002505 * Methods called by subclasses
2506 */
2507
2508void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002509 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002510 {
2511 // Need mLock to safely update state and synchronize to current
2512 // state of methods in flight.
2513 Mutex::Autolock l(mLock);
2514 // We can get various system-idle notices from the status tracker
2515 // while starting up. Only care about them if we've actually sent
2516 // in some requests recently.
2517 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2518 return;
2519 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002520 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2521 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002522 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002523
2524 // Skip notifying listener if we're doing some user-transparent
2525 // state changes
2526 if (mPauseStateNotify) return;
2527 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002528
2529 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002530 {
2531 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002532 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002533 }
2534 if (idle && listener != NULL) {
2535 listener->notifyIdle();
2536 }
2537}
2538
Shuzhen Wang758c2152017-01-10 18:26:18 -08002539status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002540 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002541 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002542 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2543 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002544
2545 if (surfaceIds == nullptr) {
2546 return BAD_VALUE;
2547 }
2548
Zhijun He5d677d12016-05-29 16:52:39 -07002549 Mutex::Autolock il(mInterfaceLock);
2550 Mutex::Autolock l(mLock);
2551
Shuzhen Wang758c2152017-01-10 18:26:18 -08002552 if (consumers.size() == 0) {
2553 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002554 return BAD_VALUE;
2555 }
2556
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002557 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2558 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002559 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002560 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002561 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002562
2563 // isConsumerConfigurationDeferred will be off after setConsumers
2564 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002565 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002566 if (res != OK) {
2567 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2568 return res;
2569 }
2570
Emilian Peev40ead602017-09-26 15:46:36 +01002571 for (auto &consumer : consumers) {
2572 int id = stream->getSurfaceId(consumer);
2573 if (id < 0) {
2574 CLOGE("Invalid surface id!");
2575 return BAD_VALUE;
2576 }
2577 surfaceIds->push_back(id);
2578 }
2579
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002580 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002581 if (!stream->isConfiguring()) {
2582 CLOGE("Stream %d was already fully configured.", streamId);
2583 return INVALID_OPERATION;
2584 }
Zhijun He5d677d12016-05-29 16:52:39 -07002585
Shuzhen Wang0129d522016-10-30 22:43:41 -07002586 res = stream->finishConfiguration();
2587 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002588 // If finishConfiguration fails due to abandoned surface, do not set
2589 // device to error state.
2590 bool isSurfaceAbandoned =
2591 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2592 if (!isSurfaceAbandoned) {
2593 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2594 stream->getId(), strerror(-res), res);
2595 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002596 return res;
2597 }
Zhijun He5d677d12016-05-29 16:52:39 -07002598 }
2599
2600 return OK;
2601}
2602
Emilian Peev40ead602017-09-26 15:46:36 +01002603status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2604 const std::vector<OutputStreamInfo> &outputInfo,
2605 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2606 Mutex::Autolock il(mInterfaceLock);
2607 Mutex::Autolock l(mLock);
2608
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002609 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2610 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002611 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002612 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002613 }
2614
2615 for (const auto &it : removedSurfaceIds) {
2616 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2617 CLOGE("Shared surface still part of a pending request!");
2618 return -EBUSY;
2619 }
2620 }
2621
Emilian Peev40ead602017-09-26 15:46:36 +01002622 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2623 if (res != OK) {
2624 CLOGE("Stream %d failed to update stream (error %d %s) ",
2625 streamId, res, strerror(-res));
2626 if (res == UNKNOWN_ERROR) {
2627 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2628 __FUNCTION__);
2629 }
2630 return res;
2631 }
2632
2633 return res;
2634}
2635
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002636status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2637 Mutex::Autolock il(mInterfaceLock);
2638 Mutex::Autolock l(mLock);
2639
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002640 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2641 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002642 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2643 return BAD_VALUE;
2644 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002645 return stream->dropBuffers(dropping);
2646}
2647
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002648/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649 * Camera3Device private methods
2650 */
2651
2652sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002653 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655
2656 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002657 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658
2659 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002660 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 if (inputStreams.count > 0) {
2662 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002663 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002664 CLOGE("Request references unknown input stream %d",
2665 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002666 return NULL;
2667 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002668
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002669 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002670 SET_ERR_L("%s: input stream %d is not configured!",
2671 __FUNCTION__, mInputStream->getId());
2672 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002673 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002674 // Check if stream prepare is blocking requests.
2675 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002676 CLOGE("Request references an input stream that's being prepared!");
2677 return NULL;
2678 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679
2680 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002681 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 }
2683
2684 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002685 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002687 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688 return NULL;
2689 }
2690
2691 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002692 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2693 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002694 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002695 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696 return NULL;
2697 }
Zhijun He5d677d12016-05-29 16:52:39 -07002698 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002699 auto iter = surfaceMap.find(streams.data.i32[i]);
2700 if (iter != surfaceMap.end()) {
2701 const std::vector<size_t>& surfaces = iter->second;
2702 for (const auto& surface : surfaces) {
2703 if (stream->isConsumerConfigurationDeferred(surface)) {
2704 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2705 "due to deferred consumer", stream->getId(), surface);
2706 return NULL;
2707 }
2708 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002709 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002710 }
2711
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002712 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002713 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2714 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002715 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002716 // Check if stream prepare is blocking requests.
2717 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002718 CLOGE("Request references an output stream that's being prepared!");
2719 return NULL;
2720 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002721
2722 newRequest->mOutputStreams.push(stream);
2723 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002724 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002725 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002726
2727 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002728}
2729
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002730bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2731 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2732 Size size = mSupportedOpaqueInputSizes[i];
2733 if (size.width == width && size.height == height) {
2734 return true;
2735 }
2736 }
2737
2738 return false;
2739}
2740
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002741void Camera3Device::cancelStreamsConfigurationLocked() {
2742 int res = OK;
2743 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2744 res = mInputStream->cancelConfiguration();
2745 if (res != OK) {
2746 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2747 mInputStream->getId(), strerror(-res), res);
2748 }
2749 }
2750
2751 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002752 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 if (outputStream->isConfiguring()) {
2754 res = outputStream->cancelConfiguration();
2755 if (res != OK) {
2756 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2757 outputStream->getId(), strerror(-res), res);
2758 }
2759 }
2760 }
2761
2762 // Return state to that at start of call, so that future configures
2763 // properly clean things up
2764 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2765 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002766
2767 res = mPreparerThread->resume();
2768 if (res != OK) {
2769 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2770 }
2771}
2772
2773bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2774 ATRACE_CALL();
2775 bool ret = false;
2776
Jayant Chowdhary37eca242019-11-18 08:55:56 -08002777 // We must not hold mInterfaceLock here since this function is called from
2778 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2779 // deadlocks (http://b/143513518)
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002780 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2781
2782 Mutex::Autolock l(mLock);
2783 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2784 if (rc == NO_ERROR) {
2785 mNeedConfig = true;
2786 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2787 if (rc == NO_ERROR) {
2788 ret = true;
2789 mPauseStateNotify = false;
2790 //Moving to active state while holding 'mLock' is important.
2791 //There could be pending calls to 'create-/deleteStream' which
2792 //will trigger another stream configuration while the already
2793 //present streams end up with outstanding buffers that will
2794 //not get drained.
2795 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002796 } else if (rc == DEAD_OBJECT) {
2797 // DEAD_OBJECT can be returned if either the consumer surface is
2798 // abandoned, or the HAL has died.
2799 // - If the HAL has died, configureStreamsLocked call will set
2800 // device to error state,
2801 // - If surface is abandoned, we should not set device to error
2802 // state.
2803 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002804 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002805 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002806 }
2807 } else {
2808 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2809 }
2810
2811 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002812}
2813
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002814status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002815 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002816 ATRACE_CALL();
2817 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002818
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002819 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002820 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821 return INVALID_OPERATION;
2822 }
2823
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002824 if (operatingMode < 0) {
2825 CLOGE("Invalid operating mode: %d", operatingMode);
2826 return BAD_VALUE;
2827 }
2828
2829 bool isConstrainedHighSpeed =
2830 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2831 operatingMode;
2832
2833 if (mOperatingMode != operatingMode) {
2834 mNeedConfig = true;
2835 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2836 mOperatingMode = operatingMode;
2837 }
2838
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002839 // In case called from configureStreams, abort queued input buffers not belonging to
2840 // any pending requests.
2841 if (mInputStream != NULL && notifyRequestThread) {
2842 while (true) {
2843 camera3_stream_buffer_t inputBuffer;
2844 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2845 /*respectHalLimit*/ false);
2846 if (res != OK) {
2847 // Exhausted acquiring all input buffers.
2848 break;
2849 }
2850
2851 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2852 res = mInputStream->returnInputBuffer(inputBuffer);
2853 if (res != OK) {
2854 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2855 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2856 }
2857 }
2858 }
2859
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002860 if (!mNeedConfig) {
2861 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2862 return OK;
2863 }
2864
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002865 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2866 // adding a dummy stream instead.
2867 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2868 if (mOutputStreams.size() == 0) {
2869 addDummyStreamLocked();
2870 } else {
2871 tryRemoveDummyStreamLocked();
2872 }
2873
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002874 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002875 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002876
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002877 mPreparerThread->pause();
2878
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002879 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002880 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002881 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2882
2883 Vector<camera3_stream_t*> streams;
2884 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002885 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002886
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002887
2888 if (mInputStream != NULL) {
2889 camera3_stream_t *inputStream;
2890 inputStream = mInputStream->startConfiguration();
2891 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002892 CLOGE("Can't start input stream configuration");
2893 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002894 return INVALID_OPERATION;
2895 }
2896 streams.add(inputStream);
2897 }
2898
2899 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002900
2901 // Don't configure bidi streams twice, nor add them twice to the list
2902 if (mOutputStreams[i].get() ==
2903 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2904
2905 config.num_streams--;
2906 continue;
2907 }
2908
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002909 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002910 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002911 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002912 CLOGE("Can't start output stream configuration");
2913 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002914 return INVALID_OPERATION;
2915 }
2916 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002917
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002918 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002919 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2920 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002921 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2922 bufferSizes[k] = static_cast<uint32_t>(
2923 getJpegBufferSize(outputStream->width, outputStream->height));
2924 } else if (outputStream->data_space ==
2925 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2926 bufferSizes[k] = outputStream->width * outputStream->height;
2927 } else {
2928 ALOGW("%s: Blob dataSpace %d not supported",
2929 __FUNCTION__, outputStream->data_space);
2930 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002931 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002932 }
2933
2934 config.streams = streams.editArray();
2935
2936 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002937 // max_buffers, usage, and priv fields, as well as data_space and format
2938 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002939
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002940 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002941 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002942 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002943
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002944 if (res == BAD_VALUE) {
2945 // HAL rejected this set of streams as unsupported, clean up config
2946 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002947 CLOGE("Set of requested inputs/outputs not supported by HAL");
2948 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002949 return BAD_VALUE;
2950 } else if (res != OK) {
2951 // Some other kind of error from configure_streams - this is not
2952 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002953 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2954 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955 return res;
2956 }
2957
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002958 // Finish all stream configuration immediately.
2959 // TODO: Try to relax this later back to lazy completion, which should be
2960 // faster
2961
Igor Murashkin073f8572013-05-02 14:59:28 -07002962 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002963 bool streamReConfigured = false;
2964 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002965 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002966 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002967 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002968 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002969 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2970 return DEAD_OBJECT;
2971 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002972 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002973 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002974 if (streamReConfigured) {
2975 mInterface->onStreamReConfigured(mInputStream->getId());
2976 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002977 }
2978
2979 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002980 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002981 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002982 bool streamReConfigured = false;
2983 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002984 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002985 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002986 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002987 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002988 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2989 return DEAD_OBJECT;
2990 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002991 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002992 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002993 if (streamReConfigured) {
2994 mInterface->onStreamReConfigured(outputStream->getId());
2995 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002996 }
2997 }
2998
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002999 // Request thread needs to know to avoid using repeat-last-settings protocol
3000 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003001 if (notifyRequestThread) {
3002 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
3003 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003004
Zhijun He90f7c372016-08-16 16:19:43 -07003005 char value[PROPERTY_VALUE_MAX];
3006 property_get("camera.fifo.disable", value, "0");
3007 int32_t disableFifo = atoi(value);
3008 if (disableFifo != 1) {
3009 // Boost priority of request thread to SCHED_FIFO.
3010 pid_t requestThreadTid = mRequestThread->getTid();
3011 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08003012 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07003013 if (res != OK) {
3014 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
3015 strerror(-res), res);
3016 } else {
3017 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
3018 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07003019 }
3020
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003021 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003022 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
3023 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
3024 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
3025 sessionParams.unlock(newSessionParams);
3026 mSessionParams.unlock(currentSessionParams);
3027 if (updateSessionParams) {
3028 mSessionParams = sessionParams;
3029 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003030
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07003031 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003032
Ruben Brunk183f0562015-08-12 12:55:02 -07003033 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
3034 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003035
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003036 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003037
Zhijun He0a210512014-07-24 13:45:15 -07003038 // tear down the deleted streams after configure streams.
3039 mDeletedStreams.clear();
3040
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003041 auto rc = mPreparerThread->resume();
3042 if (rc != OK) {
3043 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
3044 return rc;
3045 }
3046
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003047 if (mDummyStreamId == NO_STREAM) {
3048 mRequestBufferSM.onStreamsConfigured();
3049 }
3050
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003051 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003052}
3053
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003054status_t Camera3Device::addDummyStreamLocked() {
3055 ATRACE_CALL();
3056 status_t res;
3057
3058 if (mDummyStreamId != NO_STREAM) {
3059 // Should never be adding a second dummy stream when one is already
3060 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003061 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3062 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003063 return INVALID_OPERATION;
3064 }
3065
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003066 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003067
3068 sp<Camera3OutputStreamInterface> dummyStream =
3069 new Camera3DummyStream(mNextStreamId);
3070
3071 res = mOutputStreams.add(mNextStreamId, dummyStream);
3072 if (res < 0) {
3073 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3074 return res;
3075 }
3076
3077 mDummyStreamId = mNextStreamId;
3078 mNextStreamId++;
3079
3080 return OK;
3081}
3082
3083status_t Camera3Device::tryRemoveDummyStreamLocked() {
3084 ATRACE_CALL();
3085 status_t res;
3086
3087 if (mDummyStreamId == NO_STREAM) return OK;
3088 if (mOutputStreams.size() == 1) return OK;
3089
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003090 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003091
3092 // Ok, have a dummy stream and there's at least one other output stream,
3093 // so remove the dummy
3094
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003095 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3096 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003097 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3098 return INVALID_OPERATION;
3099 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003100 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003101
3102 // Free up the stream endpoint so that it can be used by some other stream
3103 res = deletedStream->disconnect();
3104 if (res != OK) {
3105 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3106 // fall through since we want to still list the stream as deleted.
3107 }
3108 mDeletedStreams.add(deletedStream);
3109 mDummyStreamId = NO_STREAM;
3110
3111 return res;
3112}
3113
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003114void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003115 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003116 Mutex::Autolock l(mLock);
3117 va_list args;
3118 va_start(args, fmt);
3119
3120 setErrorStateLockedV(fmt, args);
3121
3122 va_end(args);
3123}
3124
3125void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003126 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003127 Mutex::Autolock l(mLock);
3128 setErrorStateLockedV(fmt, args);
3129}
3130
3131void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3132 va_list args;
3133 va_start(args, fmt);
3134
3135 setErrorStateLockedV(fmt, args);
3136
3137 va_end(args);
3138}
3139
3140void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003141 // Print out all error messages to log
3142 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003144
3145 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003146 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003147
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003148 mErrorCause = errorCause;
3149
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003150 if (mRequestThread != nullptr) {
3151 mRequestThread->setPaused(true);
3152 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003153 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003154
3155 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003156 sp<NotificationListener> listener = mListener.promote();
3157 if (listener != NULL) {
3158 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003159 CaptureResultExtras());
3160 }
3161
3162 // Save stack trace. View by dumping it later.
3163 CameraTraces::saveTrace();
3164 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003165}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003166
3167/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003168 * In-flight request management
3169 */
3170
Jianing Weicb0652e2014-03-12 18:29:36 -07003171status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003172 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003173 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003174 std::set<String8>& physicalCameraIds, bool isStillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003175 bool isZslCapture, const std::set<std::string>& cameraIdsWithZoom,
3176 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003177 ATRACE_CALL();
3178 Mutex::Autolock l(mInFlightLock);
3179
3180 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003181 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003182 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003183 cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003184 if (res < 0) return res;
3185
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003186 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003187 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3188 // avoid a deadlock during reprocess requests.
3189 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003190 if (mStatusTracker != nullptr) {
3191 mStatusTracker->markComponentActive(mInFlightStatusId);
3192 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003193 }
3194
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003195 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003196 return OK;
3197}
3198
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003199void Camera3Device::returnOutputBuffers(
3200 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003201 nsecs_t timestamp, bool timestampIncreasing,
3202 const SurfaceMap& outputSurfaces,
3203 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003204
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003205 for (size_t i = 0; i < numBuffers; i++)
3206 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003207 if (outputBuffers[i].buffer == nullptr) {
3208 if (!mUseHalBufManager) {
3209 // With HAL buffer management API, HAL sometimes will have to return buffers that
3210 // has not got a output buffer handle filled yet. This is though illegal if HAL
3211 // buffer management API is not being used.
3212 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3213 }
3214 continue;
3215 }
3216
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003217 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3218 int streamId = stream->getId();
3219 const auto& it = outputSurfaces.find(streamId);
3220 status_t res = OK;
3221 if (it != outputSurfaces.end()) {
3222 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003223 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3224 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003225 } else {
3226 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003227 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3228 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003229 }
3230
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003231 // Note: stream may be deallocated at this point, if this buffer was
3232 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003233 if (res == NO_INIT || res == DEAD_OBJECT) {
3234 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3235 } else if (res != OK) {
3236 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003237 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003238
3239 // Long processing consumers can cause returnBuffer timeout for shared stream
3240 // If that happens, cancel the buffer and send a buffer error to client
3241 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3242 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3243 // cancel the buffer
3244 camera3_stream_buffer_t sb = outputBuffers[i];
3245 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003246 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3247 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003248
3249 // notify client buffer error
3250 sp<NotificationListener> listener;
3251 {
3252 Mutex::Autolock l(mOutputLock);
3253 listener = mListener.promote();
3254 }
3255
3256 if (listener != nullptr) {
3257 CaptureResultExtras extras = inResultExtras;
3258 extras.errorStreamId = streamId;
3259 listener->notifyError(
3260 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3261 extras);
3262 }
3263 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003264 }
3265}
3266
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003267void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003268 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003269 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003270 mInFlightMap.removeItemsAt(idx, 1);
3271
3272 // Indicate idle inFlightMap to the status tracker
3273 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003274 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003275 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3276 // avoid a deadlock during reprocess requests.
3277 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003278 if (mStatusTracker != nullptr) {
3279 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3280 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003281 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003282 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003283}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003284
3285void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3286
3287 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3288 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3289
3290 nsecs_t sensorTimestamp = request.sensorTimestamp;
3291 nsecs_t shutterTimestamp = request.shutterTimestamp;
3292
3293 // Check if it's okay to remove the request from InFlightMap:
3294 // In the case of a successful request:
3295 // all input and output buffers, all result metadata, shutter callback
3296 // arrived.
3297 // In the case of a unsuccessful request:
3298 // all input and output buffers arrived.
3299 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003300 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003301 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003302 if (request.stillCapture) {
3303 ATRACE_ASYNC_END("still capture", frameNumber);
3304 }
3305
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003306 ATRACE_ASYNC_END("frame capture", frameNumber);
3307
Shuzhen Wang403044a2017-02-26 23:29:04 -08003308 // Sanity check - if sensor timestamp matches shutter timestamp in the
3309 // case of request having callback.
3310 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003311 sensorTimestamp != shutterTimestamp) {
3312 SET_ERR("sensor timestamp (%" PRId64
3313 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3314 sensorTimestamp, frameNumber, shutterTimestamp);
3315 }
3316
3317 // for an unsuccessful request, it may have pending output buffers to
3318 // return.
3319 assert(request.requestStatus != OK ||
3320 request.pendingOutputBuffers.size() == 0);
3321 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003322 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3323 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003324
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003325 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003326 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3327 }
3328
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003329 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3330 // something has likely gone wrong. This might still be legit only if application send in
3331 // a long burst of long exposure requests.
3332 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3333 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3334 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3335 mInFlightMap.size(), mExpectedInflightDuration);
3336 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3337 kInFlightWarnLimitHighSpeed) {
3338 CLOGW("In-flight list too large for high speed configuration: %zu,"
3339 "total inflight duration %" PRIu64,
3340 mInFlightMap.size(), mExpectedInflightDuration);
3341 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003342 }
3343}
3344
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003345void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003346 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003347 { // First return buffers cached in mInFlightMap
3348 Mutex::Autolock l(mInFlightLock);
3349 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3350 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3351 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003352 request.pendingOutputBuffers.size(), 0,
3353 /*timestampIncreasing*/true, request.outputSurfaces,
3354 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003355 }
3356 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003357 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003358 }
3359
3360 // Then return all inflight buffers not returned by HAL
3361 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3362 mInterface->getInflightBufferKeys(&inflightKeys);
3363
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003364 // Inflight buffers for HAL buffer manager
3365 std::vector<uint64_t> inflightRequestBufferKeys;
3366 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3367
3368 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3369 // frameNumber will be -1 for buffers from HAL buffer manager
3370 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3371 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3372
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003373 for (auto& pair : inflightKeys) {
3374 int32_t frameNumber = pair.first;
3375 int32_t streamId = pair.second;
3376 buffer_handle_t* buffer;
3377 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3378 if (res != OK) {
3379 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3380 __FUNCTION__, frameNumber, streamId);
3381 continue;
3382 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003383 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3384 }
3385
3386 for (auto& bufferId : inflightRequestBufferKeys) {
3387 int32_t streamId = -1;
3388 buffer_handle_t* buffer = nullptr;
3389 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3390 if (res != OK) {
3391 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3392 continue;
3393 }
3394 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3395 }
3396
3397 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3398 for (auto& tuple : inflightBuffers) {
3399 status_t res = OK;
3400 int32_t streamId = std::get<0>(tuple);
3401 int32_t frameNumber = std::get<1>(tuple);
3402 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003403
3404 camera3_stream_buffer_t streamBuffer;
3405 streamBuffer.buffer = buffer;
3406 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3407 streamBuffer.acquire_fence = -1;
3408 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003409
3410 // First check if the buffer belongs to deleted stream
3411 bool streamDeleted = false;
3412 for (auto& stream : mDeletedStreams) {
3413 if (streamId == stream->getId()) {
3414 streamDeleted = true;
3415 // Return buffer to deleted stream
3416 camera3_stream* halStream = stream->asHalStream();
3417 streamBuffer.stream = halStream;
3418 switch (halStream->stream_type) {
3419 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003420 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3421 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003422 if (res != OK) {
3423 ALOGE("%s: Can't return output buffer for frame %d to"
3424 " stream %d: %s (%d)", __FUNCTION__,
3425 frameNumber, streamId, strerror(-res), res);
3426 }
3427 break;
3428 case CAMERA3_STREAM_INPUT:
3429 res = stream->returnInputBuffer(streamBuffer);
3430 if (res != OK) {
3431 ALOGE("%s: Can't return input buffer for frame %d to"
3432 " stream %d: %s (%d)", __FUNCTION__,
3433 frameNumber, streamId, strerror(-res), res);
3434 }
3435 break;
3436 default: // Bi-direcitonal stream is deprecated
3437 ALOGE("%s: stream %d has unknown stream type %d",
3438 __FUNCTION__, streamId, halStream->stream_type);
3439 break;
3440 }
3441 break;
3442 }
3443 }
3444 if (streamDeleted) {
3445 continue;
3446 }
3447
3448 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003449 if (streamId == inputStreamId) {
3450 streamBuffer.stream = mInputStream->asHalStream();
3451 res = mInputStream->returnInputBuffer(streamBuffer);
3452 if (res != OK) {
3453 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003454 " stream %d: %s (%d)", __FUNCTION__,
3455 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003456 }
3457 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003458 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3459 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003460 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3461 continue;
3462 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003463 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003464 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3465 }
3466 }
3467}
3468
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003469void Camera3Device::insertResultLocked(CaptureResult *result,
3470 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003471 if (result == nullptr) return;
3472
Emilian Peev71c73a22017-03-21 16:35:51 +00003473 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3474 result->mMetadata.getAndLock());
3475 set_camera_metadata_vendor_id(meta, mVendorTagId);
3476 result->mMetadata.unlock(meta);
3477
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003478 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3479 (int32_t*)&frameNumber, 1) != OK) {
3480 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3481 return;
3482 }
3483
3484 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3485 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3486 return;
3487 }
3488
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003489 // Update vendor tag id for physical metadata
3490 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3491 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3492 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3493 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3494 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3495 }
3496
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003497 // Valid result, insert into queue
3498 List<CaptureResult>::iterator queuedResult =
3499 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3500 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3501 ", burstId = %" PRId32, __FUNCTION__,
3502 queuedResult->mResultExtras.requestId,
3503 queuedResult->mResultExtras.frameNumber,
3504 queuedResult->mResultExtras.burstId);
3505
3506 mResultSignal.signal();
3507}
3508
3509
3510void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003511 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003512 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003513 Mutex::Autolock l(mOutputLock);
3514
3515 CaptureResult captureResult;
3516 captureResult.mResultExtras = resultExtras;
3517 captureResult.mMetadata = partialResult;
3518
Shuzhen Wang268a1362018-10-16 16:32:59 -07003519 // Fix up result metadata for monochrome camera.
3520 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3521 if (res != OK) {
3522 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3523 return;
3524 }
3525
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003526 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003527}
3528
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003529
3530void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3531 CaptureResultExtras &resultExtras,
3532 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003533 uint32_t frameNumber,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003534 bool reprocess, bool zslStillCapture, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003535 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003536 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003537 if (pendingMetadata.isEmpty())
3538 return;
3539
3540 Mutex::Autolock l(mOutputLock);
3541
3542 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003543 if (reprocess) {
3544 if (frameNumber < mNextReprocessResultFrameNumber) {
3545 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003546 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003547 frameNumber, mNextReprocessResultFrameNumber);
3548 return;
3549 }
3550 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003551 } else if (zslStillCapture) {
3552 if (frameNumber < mNextZslStillResultFrameNumber) {
3553 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3554 "(got frame number %d, expecting %d)",
3555 frameNumber, mNextZslStillResultFrameNumber);
3556 return;
3557 }
3558 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003559 } else {
3560 if (frameNumber < mNextResultFrameNumber) {
3561 SET_ERR("Out-of-order capture result metadata submitted! "
3562 "(got frame number %d, expecting %d)",
3563 frameNumber, mNextResultFrameNumber);
3564 return;
3565 }
3566 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003567 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003568
3569 CaptureResult captureResult;
3570 captureResult.mResultExtras = resultExtras;
3571 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003572 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003573
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003574 // Append any previous partials to form a complete result
3575 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3576 captureResult.mMetadata.append(collectedPartialResult);
3577 }
3578
3579 captureResult.mMetadata.sort();
3580
3581 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003582 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3583 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003584 SET_ERR("No timestamp provided by HAL for frame %d!",
3585 frameNumber);
3586 return;
3587 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003588 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3589 camera_metadata_entry timestamp =
3590 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3591 if (timestamp.count == 0) {
3592 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3593 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3594 return;
3595 }
3596 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003597
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003598 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003599 status_t res =
3600 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003601 if (res != OK) {
3602 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003603 frameNumber, strerror(-res), res);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003604 return;
3605 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003606
3607 // Fix up result metadata to account for zoom ratio availabilities between
3608 // HAL and app.
3609 bool zoomRatioIs1 = cameraIdsWithZoom.find(mId.c_str()) == cameraIdsWithZoom.end();
3610 res = mZoomRatioMappers[mId.c_str()].updateCaptureResult(
3611 &captureResult.mMetadata, zoomRatioIs1);
3612 if (res != OK) {
3613 SET_ERR("Failed to update capture result zoom ratio metadata for frame %d: %s (%d)",
3614 frameNumber, strerror(-res), res);
3615 return;
3616 }
3617
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003618 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3619 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003620 if (mDistortionMappers.find(cameraId8.c_str()) != mDistortionMappers.end()) {
3621 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3622 &physicalMetadata.mPhysicalCameraMetadata);
3623 if (res != OK) {
3624 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3625 frameNumber, strerror(-res), res);
3626 return;
3627 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003628 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003629
3630 zoomRatioIs1 = cameraIdsWithZoom.find(cameraId8.c_str()) == cameraIdsWithZoom.end();
3631 res = mZoomRatioMappers[cameraId8.c_str()].updateCaptureResult(
3632 &physicalMetadata.mPhysicalCameraMetadata, zoomRatioIs1);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003633 if (res != OK) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003634 SET_ERR("Failed to update camera %s's physical zoom ratio metadata for "
3635 "frame %d: %s(%d)", cameraId8.c_str(), frameNumber, strerror(-res), res);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003636 return;
3637 }
3638 }
3639
Shuzhen Wang268a1362018-10-16 16:32:59 -07003640 // Fix up result metadata for monochrome camera.
3641 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3642 if (res != OK) {
3643 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3644 return;
3645 }
3646 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3647 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3648 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3649 physicalMetadata.mPhysicalCameraMetadata);
3650 if (res != OK) {
3651 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3652 return;
3653 }
3654 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003655
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003656 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3657 for (auto& m : physicalMetadatas) {
3658 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3659 CameraMetadata(m.mPhysicalCameraMetadata));
3660 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003661 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003662 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3663 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003664
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003665 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003666}
3667
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003668/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003669 * Camera HAL device callback methods
3670 */
3671
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003672void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003673 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003674
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003675 status_t res;
3676
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003677 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003678 if (result->result == NULL && result->num_output_buffers == 0 &&
3679 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003680 SET_ERR("No result data provided by HAL for frame %d",
3681 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003682 return;
3683 }
Zhijun He204e3292014-07-14 17:09:23 -07003684
Zhijun He204e3292014-07-14 17:09:23 -07003685 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003686 result->result != NULL &&
3687 result->partial_result != 1) {
3688 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3689 " if partial result is not supported",
3690 frameNumber, result->partial_result);
3691 return;
3692 }
3693
3694 bool isPartialResult = false;
3695 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003696 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003697
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003698 // Get shutter timestamp and resultExtras from list of in-flight requests,
3699 // where it was added by the shutter notification for this frame. If the
3700 // shutter timestamp isn't received yet, append the output buffers to the
3701 // in-flight request and they will be returned when the shutter timestamp
3702 // arrives. Update the in-flight status and remove the in-flight entry if
3703 // all result data and shutter timestamp have been received.
3704 nsecs_t shutterTimestamp = 0;
3705
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003706 {
3707 Mutex::Autolock l(mInFlightLock);
3708 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3709 if (idx == NAME_NOT_FOUND) {
3710 SET_ERR("Unknown frame number for capture result: %d",
3711 frameNumber);
3712 return;
3713 }
3714 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003715 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3716 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003717 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003718 __FUNCTION__, request.resultExtras.requestId,
3719 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003720 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003721 // Always update the partial count to the latest one if it's not 0
3722 // (buffers only). When framework aggregates adjacent partial results
3723 // into one, the latest partial count will be used.
3724 if (result->partial_result != 0)
3725 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003726
3727 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003728 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003729 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3730 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3731 " the range of [1, %d] when metadata is included in the result",
3732 frameNumber, result->partial_result, mNumPartialResults);
3733 return;
3734 }
3735 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003736 if (isPartialResult && result->num_physcam_metadata) {
3737 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3738 " physical camera result", frameNumber);
3739 return;
3740 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003741 if (isPartialResult) {
3742 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003743 }
3744
Shuzhen Wang4a472662017-02-26 23:29:04 -08003745 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003746 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003747 sendPartialCaptureResult(result->result, request.resultExtras,
3748 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003749 }
3750 }
3751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003752 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003753 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003754
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003755 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003756 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003757 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003758 SET_ERR("Expected physical Camera metadata count %d not equal to actual count %d",
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003759 request.physicalCameraIds.size(), result->num_physcam_metadata);
3760 return;
3761 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003762 if (request.haveResultMetadata) {
3763 SET_ERR("Called multiple times with metadata for frame %d",
3764 frameNumber);
3765 return;
3766 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003767 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3768 String8 physicalId(result->physcam_ids[i]);
3769 std::set<String8>::iterator cameraIdIter =
3770 request.physicalCameraIds.find(physicalId);
3771 if (cameraIdIter != request.physicalCameraIds.end()) {
3772 request.physicalCameraIds.erase(cameraIdIter);
3773 } else {
3774 SET_ERR("Total result for frame %d has already returned for camera %s",
3775 frameNumber, physicalId.c_str());
3776 return;
3777 }
3778 }
Zhijun He204e3292014-07-14 17:09:23 -07003779 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003780 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003781 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003782 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003783 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003784 request.haveResultMetadata = true;
3785 }
3786
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003787 uint32_t numBuffersReturned = result->num_output_buffers;
3788 if (result->input_buffer != NULL) {
3789 if (hasInputBufferInRequest) {
3790 numBuffersReturned += 1;
3791 } else {
3792 ALOGW("%s: Input buffer should be NULL if there is no input"
3793 " buffer sent in the request",
3794 __FUNCTION__);
3795 }
3796 }
3797 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003798 if (request.numBuffersLeft < 0) {
3799 SET_ERR("Too many buffers returned for frame %d",
3800 frameNumber);
3801 return;
3802 }
3803
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003804 camera_metadata_ro_entry_t entry;
3805 res = find_camera_metadata_ro_entry(result->result,
3806 ANDROID_SENSOR_TIMESTAMP, &entry);
3807 if (res == OK && entry.count == 1) {
3808 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003809 }
3810
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003811 // If shutter event isn't received yet, append the output buffers to
3812 // the in-flight request. Otherwise, return the output buffers to
3813 // streams.
3814 if (shutterTimestamp == 0) {
3815 request.pendingOutputBuffers.appendArray(result->output_buffers,
3816 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003817 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003818 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003819 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003820 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3821 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003822 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003823
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003824 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003825 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3826 CameraMetadata physicalMetadata;
3827 physicalMetadata.append(result->physcam_metadata[i]);
3828 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3829 physicalMetadata});
3830 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003831 if (shutterTimestamp == 0) {
3832 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003833 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003834 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003835 CameraMetadata metadata;
3836 metadata = result->result;
3837 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003838 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003839 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003840 request.cameraIdsWithZoom, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003841 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003842 }
3843
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003844 removeInFlightRequestIfReadyLocked(idx);
3845 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003846
Zhijun Hef0d962a2014-06-30 10:24:11 -07003847 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003848 if (hasInputBufferInRequest) {
3849 Camera3Stream *stream =
3850 Camera3Stream::cast(result->input_buffer->stream);
3851 res = stream->returnInputBuffer(*(result->input_buffer));
3852 // Note: stream may be deallocated at this point, if this buffer was the
3853 // last reference to it.
3854 if (res != OK) {
3855 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3856 " its stream:%s (%d)", __FUNCTION__,
3857 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003858 }
3859 } else {
3860 ALOGW("%s: Input buffer should be NULL if there is no input"
3861 " buffer sent in the request, skipping input buffer return.",
3862 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003863 }
3864 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003865}
3866
3867void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003868 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003869 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003870 {
3871 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003872 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003873 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003874
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003875 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003876 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003877 return;
3878 }
3879
3880 switch (msg->type) {
3881 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003882 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003883 break;
3884 }
3885 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003886 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003887 break;
3888 }
3889 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003890 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003891 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003892 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003893}
3894
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003895void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003896 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003897 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003898 // Map camera HAL error codes to ICameraDeviceCallback error codes
3899 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003900 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003901 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003902 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003903 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003904 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003905 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003906 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003907 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003908 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003909 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003910 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003911 };
3912
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003913 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003914 ((msg.error_code >= 0) &&
3915 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3916 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003917 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003918
3919 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003920 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003921 if (msg.error_stream != NULL) {
3922 Camera3Stream *stream =
3923 Camera3Stream::cast(msg.error_stream);
3924 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003925 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003926 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003927 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3928 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003929 streamId, msg.error_code);
3930
3931 CaptureResultExtras resultExtras;
3932 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003933 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003934 // SET_ERR calls notifyError
3935 SET_ERR("Camera HAL reported serious device error");
3936 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003937 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3938 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3939 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003940 {
3941 Mutex::Autolock l(mInFlightLock);
3942 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3943 if (idx >= 0) {
3944 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3945 r.requestStatus = msg.error_code;
3946 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003947 bool logicalDeviceResultError = false;
3948 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3949 errorCode) {
3950 if (physicalCameraId.size() > 0) {
3951 String8 cameraId(physicalCameraId);
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003952 auto iter = r.physicalCameraIds.find(cameraId);
3953 if (iter == r.physicalCameraIds.end()) {
Emilian Peevedec62d2019-03-19 17:59:24 -07003954 ALOGE("%s: Reported result failure for physical camera device: %s "
3955 " which is not part of the respective request!",
3956 __FUNCTION__, cameraId.string());
3957 break;
3958 }
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003959 r.physicalCameraIds.erase(iter);
Emilian Peevedec62d2019-03-19 17:59:24 -07003960 resultExtras.errorPhysicalCameraId = physicalCameraId;
3961 } else {
3962 logicalDeviceResultError = true;
3963 }
3964 }
3965
3966 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003967 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3968 errorCode) {
3969 r.skipResultMetadata = true;
3970 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003971 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003972 // In case of missing result check whether the buffers
3973 // returned. If they returned, then remove inflight
3974 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003975 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3976 // otherwise we are depending on HAL to send the buffers back after
3977 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003978 removeInFlightRequestIfReadyLocked(idx);
3979 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003980 } else {
3981 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003982 ALOGE("Camera %s: %s: cannot find in-flight request on "
3983 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003984 resultExtras.frameNumber);
3985 }
3986 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003987 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003988 if (listener != NULL) {
3989 listener->notifyError(errorCode, resultExtras);
3990 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003992 }
3993 break;
3994 default:
3995 // SET_ERR calls notifyError
3996 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3997 break;
3998 }
3999}
4000
4001void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004002 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004003 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004004 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004005
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004006 // Set timestamp for the request in the in-flight tracking
4007 // and get the request ID to send upstream
4008 {
4009 Mutex::Autolock l(mInFlightLock);
4010 idx = mInFlightMap.indexOfKey(msg.frame_number);
4011 if (idx >= 0) {
4012 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004013
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004014 // Verify ordering of shutter notifications
4015 {
4016 Mutex::Autolock l(mOutputLock);
4017 // TODO: need to track errors for tighter bounds on expected frame number.
4018 if (r.hasInputBuffer) {
4019 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004020 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004021 "notification for frame %d, got frame %d",
4022 mNextReprocessShutterFrameNumber, msg.frame_number);
4023 return;
4024 }
4025 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004026 } else if (r.zslCapture && r.stillCapture) {
4027 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
4028 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
4029 "notification for frame %d, got frame %d",
4030 mNextZslStillShutterFrameNumber, msg.frame_number);
4031 return;
4032 }
4033 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004034 } else {
4035 if (msg.frame_number < mNextShutterFrameNumber) {
4036 SET_ERR("Shutter notification out-of-order. Expected "
4037 "notification for frame %d, got frame %d",
4038 mNextShutterFrameNumber, msg.frame_number);
4039 return;
4040 }
4041 mNextShutterFrameNumber = msg.frame_number + 1;
4042 }
4043 }
4044
Shuzhen Wang4a472662017-02-26 23:29:04 -08004045 r.shutterTimestamp = msg.timestamp;
4046 if (r.hasCallback) {
4047 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004048 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004049 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08004050 // Call listener, if any
4051 if (listener != NULL) {
4052 listener->notifyShutter(r.resultExtras, msg.timestamp);
4053 }
4054 // send pending result and buffers
4055 sendCaptureResult(r.pendingMetadata, r.resultExtras,
4056 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004057 r.hasInputBuffer, r.zslCapture && r.stillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004058 r.cameraIdsWithZoom, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004059 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004060 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004061 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004062 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
4063 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004064 r.pendingOutputBuffers.clear();
4065
4066 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004067 }
4068 }
4069 if (idx < 0) {
4070 SET_ERR("Shutter notification for non-existent frame number %d",
4071 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004072 }
4073}
4074
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004075CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004076 ALOGV("%s", __FUNCTION__);
4077
Igor Murashkin1e479c02013-09-06 16:55:14 -07004078 CameraMetadata retVal;
4079
4080 if (mRequestThread != NULL) {
4081 retVal = mRequestThread->getLatestRequest();
4082 }
4083
Igor Murashkin1e479c02013-09-06 16:55:14 -07004084 return retVal;
4085}
4086
Jianing Weicb0652e2014-03-12 18:29:36 -07004087
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004088void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004089 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4090 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4091
4092 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4093 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004094}
4095
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004096/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004097 * HalInterface inner class methods
4098 */
4099
Yifan Hongf79b5542017-04-11 14:44:25 -07004100Camera3Device::HalInterface::HalInterface(
4101 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004102 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004103 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004104 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004105 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004106 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004107 mIsReconfigurationQuerySupported(true),
4108 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004109 // Check with hardware service manager if we can downcast these interfaces
4110 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004111 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
4112 if (castResult_3_6.isOk()) {
4113 mHidlSession_3_6 = castResult_3_6;
4114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004115 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4116 if (castResult_3_5.isOk()) {
4117 mHidlSession_3_5 = castResult_3_5;
4118 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004119 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4120 if (castResult_3_4.isOk()) {
4121 mHidlSession_3_4 = castResult_3_4;
4122 }
4123 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4124 if (castResult_3_3.isOk()) {
4125 mHidlSession_3_3 = castResult_3_3;
4126 }
4127}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004128
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004129Camera3Device::HalInterface::HalInterface() :
4130 mUseHalBufManager(false),
4131 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004132
4133Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004134 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004135 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004136 mUseHalBufManager(other.mUseHalBufManager),
4137 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004138
4139bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004140 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004141}
4142
4143void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004144 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00004145 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004146 mHidlSession_3_4.clear();
4147 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004148 mHidlSession.clear();
4149}
4150
4151status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4152 camera3_request_template_t templateId,
4153 /*out*/ camera_metadata_t **requestTemplate) {
4154 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4155 if (!valid()) return INVALID_OPERATION;
4156 status_t res = OK;
4157
Emilian Peev31abd0a2017-05-11 18:37:46 +01004158 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004159
4160 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004161 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004162 status = s;
4163 if (status == common::V1_0::Status::OK) {
4164 const camera_metadata *r =
4165 reinterpret_cast<const camera_metadata_t*>(request.data());
4166 size_t expectedSize = request.size();
4167 int ret = validate_camera_metadata_structure(r, &expectedSize);
4168 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4169 *requestTemplate = clone_camera_metadata(r);
4170 if (*requestTemplate == nullptr) {
4171 ALOGE("%s: Unable to clone camera metadata received from HAL",
4172 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004173 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004174 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004175 } else {
4176 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4177 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004178 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004179 }
4180 };
4181 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004182 RequestTemplate id;
4183 switch (templateId) {
4184 case CAMERA3_TEMPLATE_PREVIEW:
4185 id = RequestTemplate::PREVIEW;
4186 break;
4187 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4188 id = RequestTemplate::STILL_CAPTURE;
4189 break;
4190 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4191 id = RequestTemplate::VIDEO_RECORD;
4192 break;
4193 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4194 id = RequestTemplate::VIDEO_SNAPSHOT;
4195 break;
4196 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4197 id = RequestTemplate::ZERO_SHUTTER_LAG;
4198 break;
4199 case CAMERA3_TEMPLATE_MANUAL:
4200 id = RequestTemplate::MANUAL;
4201 break;
4202 default:
4203 // Unknown template ID, or this HAL is too old to support it
4204 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004205 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004206 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004207
Emilian Peev31abd0a2017-05-11 18:37:46 +01004208 if (!err.isOk()) {
4209 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4210 res = DEAD_OBJECT;
4211 } else {
4212 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004213 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004214
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004215 return res;
4216}
4217
Emilian Peev4ec17882019-01-24 17:16:58 -08004218bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4219 CameraMetadata& newSessionParams) {
4220 // We do reconfiguration by default;
4221 bool ret = true;
4222 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4223 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4224 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4225 oldSessionParams.getAndLock());
4226 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4227 newSessionParams.getAndLock());
4228 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4229 get_camera_metadata_size(oldSessioMeta));
4230 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4231 get_camera_metadata_size(newSessioMeta));
4232 hardware::camera::common::V1_0::Status callStatus;
4233 bool required;
4234 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4235 bool requiredFlag) {
4236 callStatus = s;
4237 required = requiredFlag;
4238 };
4239 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4240 oldSessionParams.unlock(oldSessioMeta);
4241 newSessionParams.unlock(newSessioMeta);
4242 if (err.isOk()) {
4243 switch (callStatus) {
4244 case hardware::camera::common::V1_0::Status::OK:
4245 ret = required;
4246 break;
4247 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4248 mIsReconfigurationQuerySupported = false;
4249 ret = true;
4250 break;
4251 default:
4252 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4253 ret = true;
4254 }
4255 } else {
4256 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4257 ret = true;
4258 }
4259 }
4260
4261 return ret;
4262}
4263
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004264status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004265 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004266 ATRACE_NAME("CameraHal::configureStreams");
4267 if (!valid()) return INVALID_OPERATION;
4268 status_t res = OK;
4269
Emilian Peev31abd0a2017-05-11 18:37:46 +01004270 // Convert stream config to HIDL
4271 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004272 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4273 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4274 requestedConfiguration3_2.streams.resize(config->num_streams);
4275 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004276 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004277 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4278 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004279 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004280
Emilian Peev31abd0a2017-05-11 18:37:46 +01004281 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4282 cam3stream->setBufferFreedListener(this);
4283 int streamId = cam3stream->getId();
4284 StreamType streamType;
4285 switch (src->stream_type) {
4286 case CAMERA3_STREAM_OUTPUT:
4287 streamType = StreamType::OUTPUT;
4288 break;
4289 case CAMERA3_STREAM_INPUT:
4290 streamType = StreamType::INPUT;
4291 break;
4292 default:
4293 ALOGE("%s: Stream %d: Unsupported stream type %d",
4294 __FUNCTION__, streamId, config->streams[i]->stream_type);
4295 return BAD_VALUE;
4296 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004297 dst3_2.id = streamId;
4298 dst3_2.streamType = streamType;
4299 dst3_2.width = src->width;
4300 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004301 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004302 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004303 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4304 // to HAL are original, not the overriden ones.
4305 if (mHidlSession_3_5 != nullptr) {
4306 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4307 cam3stream->getOriginalFormat() : src->format);
4308 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4309 cam3stream->getOriginalDataSpace() : src->data_space);
4310 } else {
4311 dst3_2.format = mapToPixelFormat(src->format);
4312 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4313 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004314 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004315 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004316 if (src->physical_camera_id != nullptr) {
4317 dst3_4.physicalCameraId = src->physical_camera_id;
4318 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004319
4320 activeStreams.insert(streamId);
4321 // Create Buffer ID map if necessary
4322 if (mBufferIdMaps.count(streamId) == 0) {
4323 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4324 }
4325 }
4326 // remove BufferIdMap for deleted streams
4327 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4328 int streamId = it->first;
4329 bool active = activeStreams.count(streamId) > 0;
4330 if (!active) {
4331 it = mBufferIdMaps.erase(it);
4332 } else {
4333 ++it;
4334 }
4335 }
4336
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004337 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004338 res = mapToStreamConfigurationMode(
4339 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004340 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004341 if (res != OK) {
4342 return res;
4343 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004344 requestedConfiguration3_2.operationMode = operationMode;
4345 requestedConfiguration3_4.operationMode = operationMode;
4346 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004347 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4348 get_camera_metadata_size(sessionParams));
4349
Emilian Peev31abd0a2017-05-11 18:37:46 +01004350 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004351 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004352 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004353 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004354
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004355 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004356 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4357 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004358 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004359 };
4360
4361 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4362 (hardware::Return<void>& err) -> status_t {
4363 if (!err.isOk()) {
4364 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4365 return DEAD_OBJECT;
4366 }
4367 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4368 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4369 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4370 }
4371 return OK;
4372 };
4373
Shuzhen Wang92653952019-05-07 15:11:43 -07004374 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004375 if (mHidlSession_3_5 != nullptr) {
4376 ALOGV("%s: v3.5 device found", __FUNCTION__);
4377 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4378 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4379 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4380 auto err = mHidlSession_3_5->configureStreams_3_5(
4381 requestedConfiguration3_5, configStream34Cb);
4382 res = postprocConfigStream34(err);
4383 if (res != OK) {
4384 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004385 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004386 } else if (mHidlSession_3_4 != nullptr) {
4387 // We do; use v3.4 for the call
4388 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004389 auto err = mHidlSession_3_4->configureStreams_3_4(
4390 requestedConfiguration3_4, configStream34Cb);
4391 res = postprocConfigStream34(err);
4392 if (res != OK) {
4393 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004394 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004395 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004396 // We do; use v3.3 for the call
4397 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004398 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004399 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004400 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004401 finalConfiguration = halConfiguration;
4402 status = s;
4403 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004404 if (!err.isOk()) {
4405 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4406 return DEAD_OBJECT;
4407 }
4408 } else {
4409 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4410 ALOGV("%s: v3.2 device found", __FUNCTION__);
4411 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004412 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004413 [&status, &finalConfiguration_3_2]
4414 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4415 finalConfiguration_3_2 = halConfiguration;
4416 status = s;
4417 });
4418 if (!err.isOk()) {
4419 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4420 return DEAD_OBJECT;
4421 }
4422 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4423 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4424 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4425 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004426 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004427 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004428 }
4429
4430 if (status != common::V1_0::Status::OK ) {
4431 return CameraProviderManager::mapToStatusT(status);
4432 }
4433
4434 // And convert output stream configuration from HIDL
4435
4436 for (size_t i = 0; i < config->num_streams; i++) {
4437 camera3_stream_t *dst = config->streams[i];
4438 int streamId = Camera3Stream::cast(dst)->getId();
4439
4440 // Start scan at i, with the assumption that the stream order matches
4441 size_t realIdx = i;
4442 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004443 size_t halStreamCount = finalConfiguration.streams.size();
4444 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004445 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004446 found = true;
4447 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004448 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004449 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004450 }
4451 if (!found) {
4452 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4453 __FUNCTION__, streamId);
4454 return INVALID_OPERATION;
4455 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004456 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004457
Emilian Peev710c1422017-08-30 11:19:38 +01004458 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004459 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4460 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4461
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004462 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004463 dstStream->setFormatOverride(false);
4464 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004465 if (dst->format != overrideFormat) {
4466 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4467 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004468 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004469 if (dst->data_space != overrideDataSpace) {
4470 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4471 streamId, dst->format);
4472 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004473 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004474 bool needFormatOverride =
4475 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4476 bool needDataspaceOverride =
4477 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004478 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004479 dstStream->setFormatOverride(needFormatOverride);
4480 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004481 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004482 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004483 }
4484
Emilian Peev31abd0a2017-05-11 18:37:46 +01004485 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004486 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004487 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004488 __FUNCTION__, streamId);
4489 return INVALID_OPERATION;
4490 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004491 dstStream->setUsage(
4492 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004493 } else {
4494 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004495 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004496 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4497 __FUNCTION__, streamId);
4498 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004499 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004500 dstStream->setUsage(
4501 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004502 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004503 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004504 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004505
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004506 return res;
4507}
4508
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004509status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004510 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004511 /*out*/std::vector<native_handle_t*>* handlesCreated,
4512 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004513 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004514 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4515 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4516 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004517 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004518 }
4519
4520 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004521
4522 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004523
4524 {
4525 std::lock_guard<std::mutex> lock(mInflightLock);
4526 if (request->input_buffer != nullptr) {
4527 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4528 buffer_handle_t buf = *(request->input_buffer->buffer);
4529 auto pair = getBufferId(buf, streamId);
4530 bool isNewBuffer = pair.first;
4531 uint64_t bufferId = pair.second;
4532 captureRequest->inputBuffer.streamId = streamId;
4533 captureRequest->inputBuffer.bufferId = bufferId;
4534 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4535 captureRequest->inputBuffer.status = BufferStatus::OK;
4536 native_handle_t *acquireFence = nullptr;
4537 if (request->input_buffer->acquire_fence != -1) {
4538 acquireFence = native_handle_create(1,0);
4539 acquireFence->data[0] = request->input_buffer->acquire_fence;
4540 handlesCreated->push_back(acquireFence);
4541 }
4542 captureRequest->inputBuffer.acquireFence = acquireFence;
4543 captureRequest->inputBuffer.releaseFence = nullptr;
4544
4545 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004546 request->input_buffer->buffer);
4547 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004548 } else {
4549 captureRequest->inputBuffer.streamId = -1;
4550 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4551 }
4552
4553 captureRequest->outputBuffers.resize(request->num_output_buffers);
4554 for (size_t i = 0; i < request->num_output_buffers; i++) {
4555 const camera3_stream_buffer_t *src = request->output_buffers + i;
4556 StreamBuffer &dst = captureRequest->outputBuffers[i];
4557 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004558 if (src->buffer != nullptr) {
4559 buffer_handle_t buf = *(src->buffer);
4560 auto pair = getBufferId(buf, streamId);
4561 bool isNewBuffer = pair.first;
4562 dst.bufferId = pair.second;
4563 dst.buffer = isNewBuffer ? buf : nullptr;
4564 native_handle_t *acquireFence = nullptr;
4565 if (src->acquire_fence != -1) {
4566 acquireFence = native_handle_create(1,0);
4567 acquireFence->data[0] = src->acquire_fence;
4568 handlesCreated->push_back(acquireFence);
4569 }
4570 dst.acquireFence = acquireFence;
4571 } else if (mUseHalBufManager) {
4572 // HAL buffer management path
4573 dst.bufferId = BUFFER_ID_NO_BUFFER;
4574 dst.buffer = nullptr;
4575 dst.acquireFence = nullptr;
4576 } else {
4577 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4578 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004579 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004580 dst.streamId = streamId;
4581 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004582 dst.releaseFence = nullptr;
4583
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004584 // Output buffers are empty when using HAL buffer manager
4585 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004586 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4587 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004588 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004589 }
4590 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004591 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004592}
4593
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004594void Camera3Device::HalInterface::cleanupNativeHandles(
4595 std::vector<native_handle_t*> *handles, bool closeFd) {
4596 if (handles == nullptr) {
4597 return;
4598 }
4599 if (closeFd) {
4600 for (auto& handle : *handles) {
4601 native_handle_close(handle);
4602 }
4603 }
4604 for (auto& handle : *handles) {
4605 native_handle_delete(handle);
4606 }
4607 handles->clear();
4608 return;
4609}
4610
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004611status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4612 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4613 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4614 if (!valid()) return INVALID_OPERATION;
4615
Emilian Peevaebbe412018-01-15 13:53:24 +00004616 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4617 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4618 if (castResult_3_4.isOk()) {
4619 hidlSession_3_4 = castResult_3_4;
4620 }
4621
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004622 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004623 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004624 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004625 if (hidlSession_3_4 != nullptr) {
4626 captureRequests_3_4.resize(batchSize);
4627 } else {
4628 captureRequests.resize(batchSize);
4629 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004630 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004631 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004632
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004633 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004634 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004635 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004636 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004637 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004638 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004639 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4640 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004641 }
4642 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004643 popInflightBuffers(inflightBuffers);
4644 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004645 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004646 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004647 }
4648
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004649 std::vector<device::V3_2::BufferCache> cachesToRemove;
4650 {
4651 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4652 for (auto& pair : mFreedBuffers) {
4653 // The stream might have been removed since onBufferFreed
4654 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4655 cachesToRemove.push_back({pair.first, pair.second});
4656 }
4657 }
4658 mFreedBuffers.clear();
4659 }
4660
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004661 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4662 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004663
4664 // Write metadata to FMQ.
4665 for (size_t i = 0; i < batchSize; i++) {
4666 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004667 device::V3_2::CaptureRequest* captureRequest;
4668 if (hidlSession_3_4 != nullptr) {
4669 captureRequest = &captureRequests_3_4[i].v3_2;
4670 } else {
4671 captureRequest = &captureRequests[i];
4672 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004673
4674 if (request->settings != nullptr) {
4675 size_t settingsSize = get_camera_metadata_size(request->settings);
4676 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4677 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4678 captureRequest->settings.resize(0);
4679 captureRequest->fmqSettingsSize = settingsSize;
4680 } else {
4681 if (mRequestMetadataQueue != nullptr) {
4682 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4683 }
4684 captureRequest->settings.setToExternal(
4685 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4686 get_camera_metadata_size(request->settings));
4687 captureRequest->fmqSettingsSize = 0u;
4688 }
4689 } else {
4690 // A null request settings maps to a size-0 CameraMetadata
4691 captureRequest->settings.resize(0);
4692 captureRequest->fmqSettingsSize = 0u;
4693 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004694
4695 if (hidlSession_3_4 != nullptr) {
4696 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4697 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004698 if (request->physcam_settings != nullptr) {
4699 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4700 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4701 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4702 settingsSize)) {
4703 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4704 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4705 settingsSize;
4706 } else {
4707 if (mRequestMetadataQueue != nullptr) {
4708 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4709 }
4710 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4711 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4712 request->physcam_settings[j])),
4713 get_camera_metadata_size(request->physcam_settings[j]));
4714 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004715 }
Emilian Peev00420d22018-02-05 21:33:13 +00004716 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004717 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004718 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004719 }
4720 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4721 request->physcam_id[j];
4722 }
4723 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004724 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004725
4726 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004727 auto resultCallback =
4728 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4729 status = s;
4730 *numRequestProcessed = n;
4731 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004732 if (hidlSession_3_4 != nullptr) {
4733 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004734 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004735 } else {
4736 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004737 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004738 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004739 if (!err.isOk()) {
4740 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004741 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004742 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004743
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004744 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4745 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4746 __FUNCTION__, *numRequestProcessed, batchSize);
4747 status = common::V1_0::Status::INTERNAL_ERROR;
4748 }
4749
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004750 res = CameraProviderManager::mapToStatusT(status);
4751 if (res == OK) {
4752 if (mHidlSession->isRemote()) {
4753 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4754 // sent to camera HAL processes)
4755 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4756 } else {
4757 // In passthrough mode the FDs are now owned by HAL
4758 cleanupNativeHandles(&handlesCreated);
4759 }
4760 } else {
4761 popInflightBuffers(inflightBuffers);
4762 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004763 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004764 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004765}
4766
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004767status_t Camera3Device::HalInterface::flush() {
4768 ATRACE_NAME("CameraHal::flush");
4769 if (!valid()) return INVALID_OPERATION;
4770 status_t res = OK;
4771
Emilian Peev31abd0a2017-05-11 18:37:46 +01004772 auto err = mHidlSession->flush();
4773 if (!err.isOk()) {
4774 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4775 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004776 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004777 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004778 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004779
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004780 return res;
4781}
4782
Emilian Peev31abd0a2017-05-11 18:37:46 +01004783status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004784 ATRACE_NAME("CameraHal::dump");
4785 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004786
Emilian Peev31abd0a2017-05-11 18:37:46 +01004787 // Handled by CameraProviderManager::dump
4788
4789 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004790}
4791
4792status_t Camera3Device::HalInterface::close() {
4793 ATRACE_NAME("CameraHal::close()");
4794 if (!valid()) return INVALID_OPERATION;
4795 status_t res = OK;
4796
Emilian Peev31abd0a2017-05-11 18:37:46 +01004797 auto err = mHidlSession->close();
4798 // Interface will be dead shortly anyway, so don't log errors
4799 if (!err.isOk()) {
4800 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004801 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004802
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004803 return res;
4804}
4805
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004806void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4807 ATRACE_NAME("CameraHal::signalPipelineDrain");
4808 if (!valid() || mHidlSession_3_5 == nullptr) {
4809 ALOGE("%s called on invalid camera!", __FUNCTION__);
4810 return;
4811 }
4812
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004813 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004814 if (!err.isOk()) {
4815 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4816 return;
4817 }
4818}
4819
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004820status_t Camera3Device::HalInterface::switchToOffline(
4821 const std::vector<int32_t>& streamsToKeep,
4822 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
4823 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
4824 ATRACE_NAME("CameraHal::switchToOffline");
4825 if (!valid() || mHidlSession_3_6 == nullptr) {
4826 ALOGE("%s called on invalid camera!", __FUNCTION__);
4827 return INVALID_OPERATION;
4828 }
4829
4830 if (offlineSessionInfo == nullptr || offlineSession == nullptr) {
4831 ALOGE("%s: offlineSessionInfo and offlineSession must not be null!", __FUNCTION__);
4832 return INVALID_OPERATION;
4833 }
4834
4835 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4836
4837 auto resultCallback =
4838 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4839 status = s;
4840 *offlineSessionInfo = info;
4841 *offlineSession = session;
4842 };
4843 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4844
4845 if (!err.isOk()) {
4846 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4847 return DEAD_OBJECT;
4848 }
4849 return CameraProviderManager::mapToStatusT(status);
4850}
4851
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004852void Camera3Device::HalInterface::getInflightBufferKeys(
4853 std::vector<std::pair<int32_t, int32_t>>* out) {
4854 std::lock_guard<std::mutex> lock(mInflightLock);
4855 out->clear();
4856 out->reserve(mInflightBufferMap.size());
4857 for (auto& pair : mInflightBufferMap) {
4858 uint64_t key = pair.first;
4859 int32_t streamId = key & 0xFFFFFFFF;
4860 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4861 out->push_back(std::make_pair(frameNumber, streamId));
4862 }
4863 return;
4864}
4865
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004866void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4867 std::vector<uint64_t>* out) {
4868 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4869 out->clear();
4870 out->reserve(mRequestedBuffers.size());
4871 for (auto& pair : mRequestedBuffers) {
4872 out->push_back(pair.first);
4873 }
4874 return;
4875}
4876
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004877status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004878 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004879 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004880 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004881 return OK;
4882}
4883
4884status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004885 int32_t frameNumber, int32_t streamId,
4886 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004887 std::lock_guard<std::mutex> lock(mInflightLock);
4888
4889 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4890 auto it = mInflightBufferMap.find(key);
4891 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004892 if (buffer != nullptr) {
4893 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004894 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004895 mInflightBufferMap.erase(it);
4896 return OK;
4897}
4898
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004899void Camera3Device::HalInterface::popInflightBuffers(
4900 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4901 for (const auto& pair : buffers) {
4902 int32_t frameNumber = pair.first;
4903 int32_t streamId = pair.second;
4904 popInflightBuffer(frameNumber, streamId, nullptr);
4905 }
4906}
4907
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004908status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004909 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004910 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004911 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004912 if (!pair.second) {
4913 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4914 __FUNCTION__, bufferId);
4915 return BAD_VALUE;
4916 }
4917 return OK;
4918}
4919
4920// Find and pop a buffer_handle_t based on bufferId
4921status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004922 uint64_t bufferId,
4923 /*out*/ buffer_handle_t** buffer,
4924 /*optional out*/ int32_t* streamId) {
4925 if (buffer == nullptr) {
4926 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4927 return BAD_VALUE;
4928 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004929 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4930 auto it = mRequestedBuffers.find(bufferId);
4931 if (it == mRequestedBuffers.end()) {
4932 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4933 __FUNCTION__, bufferId);
4934 return BAD_VALUE;
4935 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004936 *buffer = it->second.second;
4937 if (streamId != nullptr) {
4938 *streamId = it->second.first;
4939 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004940 mRequestedBuffers.erase(it);
4941 return OK;
4942}
4943
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004944std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4945 const buffer_handle_t& buf, int streamId) {
4946 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4947
4948 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4949 auto it = bIdMap.find(buf);
4950 if (it == bIdMap.end()) {
4951 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004952 ALOGV("stream %d now have %zu buffer caches, buf %p",
4953 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004954 return std::make_pair(true, mNextBufferId - 1);
4955 } else {
4956 return std::make_pair(false, it->second);
4957 }
4958}
4959
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004960void Camera3Device::HalInterface::onBufferFreed(
4961 int streamId, const native_handle_t* handle) {
4962 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4963 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4964 auto mapIt = mBufferIdMaps.find(streamId);
4965 if (mapIt == mBufferIdMaps.end()) {
4966 // streamId might be from a deleted stream here
4967 ALOGI("%s: stream %d has been removed",
4968 __FUNCTION__, streamId);
4969 return;
4970 }
4971 BufferIdMap& bIdMap = mapIt->second;
4972 auto it = bIdMap.find(handle);
4973 if (it == bIdMap.end()) {
4974 ALOGW("%s: cannot find buffer %p in stream %d",
4975 __FUNCTION__, handle, streamId);
4976 return;
4977 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004978 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004979 bIdMap.erase(it);
4980 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4981 __FUNCTION__, streamId, bIdMap.size(), handle);
4982 }
4983 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4984}
4985
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004986void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4987 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4988 auto mapIt = mBufferIdMaps.find(streamId);
4989 if (mapIt == mBufferIdMaps.end()) {
4990 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4991 return;
4992 }
4993
4994 BufferIdMap& bIdMap = mapIt->second;
4995 for (const auto& it : bIdMap) {
4996 uint64_t bufferId = it.second;
4997 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4998 }
4999 bIdMap.clear();
5000}
5001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005002/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005003 * RequestThread inner class methods
5004 */
5005
5006Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005007 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005008 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
5009 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005010 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005011 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005012 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005013 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005014 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005015 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005016 mReconfigured(false),
5017 mDoPause(false),
5018 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005019 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005020 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07005021 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005022 mCurrentAfTriggerId(0),
5023 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005024 mRepeatingLastFrameNumber(
5025 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07005026 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005027 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005028 mRequestLatency(kRequestLatencyBinSize),
5029 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005030 mLatestSessionParams(sessionParamKeys.size()),
5031 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005032 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005033}
5034
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005035Camera3Device::RequestThread::~RequestThread() {}
5036
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005037void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005038 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005039 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005040 Mutex::Autolock l(mRequestLock);
5041 mListener = listener;
5042}
5043
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005044void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
5045 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005046 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005047 Mutex::Autolock l(mRequestLock);
5048 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005049 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005050 // Prepare video stream for high speed recording.
5051 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005052 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005053}
5054
Jianing Wei90e59c92014-03-12 18:29:36 -07005055status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005056 List<sp<CaptureRequest> > &requests,
5057 /*out*/
5058 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005059 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07005060 Mutex::Autolock l(mRequestLock);
5061 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
5062 ++it) {
5063 mRequestQueue.push_back(*it);
5064 }
5065
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005066 if (lastFrameNumber != NULL) {
5067 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
5068 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
5069 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
5070 *lastFrameNumber);
5071 }
Jianing Weicb0652e2014-03-12 18:29:36 -07005072
Jianing Wei90e59c92014-03-12 18:29:36 -07005073 unpauseForNewRequests();
5074
5075 return OK;
5076}
5077
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005078
5079status_t Camera3Device::RequestThread::queueTrigger(
5080 RequestTrigger trigger[],
5081 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005082 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005083 Mutex::Autolock l(mTriggerMutex);
5084 status_t ret;
5085
5086 for (size_t i = 0; i < count; ++i) {
5087 ret = queueTriggerLocked(trigger[i]);
5088
5089 if (ret != OK) {
5090 return ret;
5091 }
5092 }
5093
5094 return OK;
5095}
5096
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005097const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
5098 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005099 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005100 if (d != nullptr) return d->mId;
5101 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005102}
5103
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005104status_t Camera3Device::RequestThread::queueTriggerLocked(
5105 RequestTrigger trigger) {
5106
5107 uint32_t tag = trigger.metadataTag;
5108 ssize_t index = mTriggerMap.indexOfKey(tag);
5109
5110 switch (trigger.getTagType()) {
5111 case TYPE_BYTE:
5112 // fall-through
5113 case TYPE_INT32:
5114 break;
5115 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005116 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5117 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005118 return INVALID_OPERATION;
5119 }
5120
5121 /**
5122 * Collect only the latest trigger, since we only have 1 field
5123 * in the request settings per trigger tag, and can't send more than 1
5124 * trigger per request.
5125 */
5126 if (index != NAME_NOT_FOUND) {
5127 mTriggerMap.editValueAt(index) = trigger;
5128 } else {
5129 mTriggerMap.add(tag, trigger);
5130 }
5131
5132 return OK;
5133}
5134
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005135status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005136 const RequestList &requests,
5137 /*out*/
5138 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005139 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005140 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005141 if (lastFrameNumber != NULL) {
5142 *lastFrameNumber = mRepeatingLastFrameNumber;
5143 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005144 mRepeatingRequests.clear();
5145 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5146 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005147
5148 unpauseForNewRequests();
5149
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005150 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005151 return OK;
5152}
5153
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005154bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005155 if (mRepeatingRequests.empty()) {
5156 return false;
5157 }
5158 int32_t requestId = requestIn->mResultExtras.requestId;
5159 const RequestList &repeatRequests = mRepeatingRequests;
5160 // All repeating requests are guaranteed to have same id so only check first quest
5161 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5162 return (firstRequest->mResultExtras.requestId == requestId);
5163}
5164
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005165status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005166 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005167 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005168 return clearRepeatingRequestsLocked(lastFrameNumber);
5169
5170}
5171
5172status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005173 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005174 if (lastFrameNumber != NULL) {
5175 *lastFrameNumber = mRepeatingLastFrameNumber;
5176 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005177 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005178 return OK;
5179}
5180
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005181status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005182 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005183 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005184 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005185 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005186
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005187 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005188
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005189 // Send errors for all requests pending in the request queue, including
5190 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005191 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005192 if (listener != NULL) {
5193 for (RequestList::iterator it = mRequestQueue.begin();
5194 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005195 // Abort the input buffers for reprocess requests.
5196 if ((*it)->mInputStream != NULL) {
5197 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005198 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5199 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005200 if (res != OK) {
5201 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5202 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5203 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07005204 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005205 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5206 if (res != OK) {
5207 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5208 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5209 }
5210 }
5211 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005212 // Set the frame number this request would have had, if it
5213 // had been submitted; this frame number will not be reused.
5214 // The requestId and burstId fields were set when the request was
5215 // submitted originally (in convertMetadataListToRequestListLocked)
5216 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005217 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005218 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005219 }
5220 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005221 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005222
5223 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005224 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005225 if (lastFrameNumber != NULL) {
5226 *lastFrameNumber = mRepeatingLastFrameNumber;
5227 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005228 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08005229 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005230 return OK;
5231}
5232
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005233status_t Camera3Device::RequestThread::flush() {
5234 ATRACE_CALL();
5235 Mutex::Autolock l(mFlushLock);
5236
Emilian Peev08dd2452017-04-06 16:55:14 +01005237 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005238}
5239
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005240void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005241 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005242 Mutex::Autolock l(mPauseLock);
5243 mDoPause = paused;
5244 mDoPauseSignal.signal();
5245}
5246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005247status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5248 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005249 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005250 Mutex::Autolock l(mLatestRequestMutex);
5251 status_t res;
5252 while (mLatestRequestId != requestId) {
5253 nsecs_t startTime = systemTime();
5254
5255 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5256 if (res != OK) return res;
5257
5258 timeout -= (systemTime() - startTime);
5259 }
5260
5261 return OK;
5262}
5263
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005264void Camera3Device::RequestThread::requestExit() {
5265 // Call parent to set up shutdown
5266 Thread::requestExit();
5267 // The exit from any possible waits
5268 mDoPauseSignal.signal();
5269 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005270
5271 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5272 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005273}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005274
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005275void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005276 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005277 bool surfaceAbandoned = false;
5278 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005279 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005280 {
5281 Mutex::Autolock l(mRequestLock);
5282 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5283 // repeating requests.
5284 for (const auto& request : mRepeatingRequests) {
5285 for (const auto& s : request->mOutputStreams) {
5286 if (s->isAbandoned()) {
5287 surfaceAbandoned = true;
5288 clearRepeatingRequestsLocked(&lastFrameNumber);
5289 break;
5290 }
5291 }
5292 if (surfaceAbandoned) {
5293 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005294 }
5295 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005296 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005297 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005298
5299 if (listener != NULL && surfaceAbandoned) {
5300 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005301 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005302}
5303
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005304bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005305 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005306 status_t res;
5307 size_t batchSize = mNextRequests.size();
5308 std::vector<camera3_capture_request_t*> requests(batchSize);
5309 uint32_t numRequestProcessed = 0;
5310 for (size_t i = 0; i < batchSize; i++) {
5311 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005312 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005313 }
5314
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005315 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5316
5317 bool triggerRemoveFailed = false;
5318 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5319 for (size_t i = 0; i < numRequestProcessed; i++) {
5320 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5321 nextRequest.submitted = true;
5322
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005323 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005324
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005325 if (!triggerRemoveFailed) {
5326 // Remove any previously queued triggers (after unlock)
5327 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5328 if (removeTriggerRes != OK) {
5329 triggerRemoveFailed = true;
5330 triggerFailedRequest = nextRequest;
5331 }
5332 }
5333 }
5334
5335 if (triggerRemoveFailed) {
5336 SET_ERR("RequestThread: Unable to remove triggers "
5337 "(capture request %d, HAL device: %s (%d)",
5338 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5339 cleanUpFailedRequests(/*sendRequestError*/ false);
5340 return false;
5341 }
5342
5343 if (res != OK) {
5344 // Should only get a failure here for malformed requests or device-level
5345 // errors, so consider all errors fatal. Bad metadata failures should
5346 // come through notify.
5347 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5348 mNextRequests[numRequestProcessed].halRequest.frame_number,
5349 strerror(-res), res);
5350 cleanUpFailedRequests(/*sendRequestError*/ false);
5351 return false;
5352 }
5353 return true;
5354}
5355
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005356nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5357 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5358 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5359 find_camera_metadata_ro_entry(request,
5360 ANDROID_CONTROL_AE_MODE,
5361 &e);
5362 if (e.count == 0) return maxExpectedDuration;
5363
5364 switch (e.data.u8[0]) {
5365 case ANDROID_CONTROL_AE_MODE_OFF:
5366 find_camera_metadata_ro_entry(request,
5367 ANDROID_SENSOR_EXPOSURE_TIME,
5368 &e);
5369 if (e.count > 0) {
5370 maxExpectedDuration = e.data.i64[0];
5371 }
5372 find_camera_metadata_ro_entry(request,
5373 ANDROID_SENSOR_FRAME_DURATION,
5374 &e);
5375 if (e.count > 0) {
5376 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5377 }
5378 break;
5379 default:
5380 find_camera_metadata_ro_entry(request,
5381 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5382 &e);
5383 if (e.count > 1) {
5384 maxExpectedDuration = 1e9 / e.data.u8[0];
5385 }
5386 break;
5387 }
5388
5389 return maxExpectedDuration;
5390}
5391
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005392bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5393 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5394 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5395 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5396 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5397 return true;
5398 }
5399
5400 return false;
5401}
5402
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005403void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5404 // Update the latest request sent to HAL
5405 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5406 Mutex::Autolock al(mLatestRequestMutex);
5407
5408 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5409 mLatestRequest.acquire(cloned);
5410
5411 mLatestPhysicalRequest.clear();
5412 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5413 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5414 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5415 CameraMetadata(cloned));
5416 }
5417
5418 sp<Camera3Device> parent = mParent.promote();
5419 if (parent != NULL) {
5420 parent->monitorMetadata(TagMonitor::REQUEST,
5421 nextRequest.halRequest.frame_number,
5422 0, mLatestRequest, mLatestPhysicalRequest);
5423 }
5424 }
5425
5426 if (nextRequest.halRequest.settings != NULL) {
5427 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5428 nextRequest.halRequest.settings);
5429 }
5430
5431 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5432}
5433
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005434bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5435 ATRACE_CALL();
5436 bool updatesDetected = false;
5437
Emilian Peev4ec17882019-01-24 17:16:58 -08005438 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005439 for (auto tag : mSessionParamKeys) {
5440 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005441 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005442
5443 if (entry.count > 0) {
5444 bool isDifferent = false;
5445 if (lastEntry.count > 0) {
5446 // Have a last value, compare to see if changed
5447 if (lastEntry.type == entry.type &&
5448 lastEntry.count == entry.count) {
5449 // Same type and count, compare values
5450 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5451 size_t entryBytes = bytesPerValue * lastEntry.count;
5452 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5453 if (cmp != 0) {
5454 isDifferent = true;
5455 }
5456 } else {
5457 // Count or type has changed
5458 isDifferent = true;
5459 }
5460 } else {
5461 // No last entry, so always consider to be different
5462 isDifferent = true;
5463 }
5464
5465 if (isDifferent) {
5466 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005467 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5468 updatesDetected = true;
5469 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005470 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005471 }
5472 } else if (lastEntry.count > 0) {
5473 // Value has been removed
5474 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005475 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005476 updatesDetected = true;
5477 }
5478 }
5479
Emilian Peev4ec17882019-01-24 17:16:58 -08005480 bool reconfigureRequired;
5481 if (updatesDetected) {
5482 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5483 updatedParams);
5484 mLatestSessionParams = updatedParams;
5485 } else {
5486 reconfigureRequired = false;
5487 }
5488
5489 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005490}
5491
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005492bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005493 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005494 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08005495 // Any function called from threadLoop() must not hold mInterfaceLock since
5496 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
5497 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005498
5499 // Handle paused state.
5500 if (waitIfPaused()) {
5501 return true;
5502 }
5503
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005504 // Wait for the next batch of requests.
5505 waitForNextRequestBatch();
5506 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005507 return true;
5508 }
5509
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005510 // Get the latest request ID, if any
5511 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005512 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005513 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005514 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005515 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005516 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005517 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5518 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005519 }
5520
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005521 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5522 // or a single request from streaming or burst. In either case the first element
5523 // should contain the latest camera settings that we need to check for any session
5524 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005525 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005526 res = OK;
5527
5528 //Input stream buffers are already acquired at this point so an input stream
5529 //will not be able to move to idle state unless we force it.
5530 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5531 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5532 if (res != OK) {
5533 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5534 cleanUpFailedRequests(/*sendRequestError*/ false);
5535 return false;
5536 }
5537 }
5538
5539 if (res == OK) {
5540 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5541 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005542 sp<Camera3Device> parent = mParent.promote();
5543 if (parent != nullptr) {
5544 parent->pauseStateNotify(true);
5545 }
5546
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005547 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5548
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005549 if (parent != nullptr) {
5550 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5551 }
5552
5553 statusTracker->markComponentActive(mStatusId);
5554 setPaused(false);
5555 }
5556
5557 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5558 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5559 if (res != OK) {
5560 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5561 cleanUpFailedRequests(/*sendRequestError*/ false);
5562 return false;
5563 }
5564 }
5565 }
5566 }
5567
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005568 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005569 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005570 if (res == TIMED_OUT) {
5571 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005572 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005573 // Check if any stream is abandoned.
5574 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005575 return true;
5576 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005577 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005578 return false;
5579 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005580
Zhijun Hecc27e112013-10-03 16:12:43 -07005581 // Inform waitUntilRequestProcessed thread of a new request ID
5582 {
5583 Mutex::Autolock al(mLatestRequestMutex);
5584
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005585 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005586 mLatestRequestSignal.signal();
5587 }
5588
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005589 // Submit a batch of requests to HAL.
5590 // Use flush lock only when submitting multilple requests in a batch.
5591 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5592 // which may take a long time to finish so synchronizing flush() and
5593 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5594 // For now, only synchronize for high speed recording and we should figure something out for
5595 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005596 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005597
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005598 if (useFlushLock) {
5599 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005600 }
5601
Zhijun Hef0645c12016-08-02 00:58:11 -07005602 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005603 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005604
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005605 sp<Camera3Device> parent = mParent.promote();
5606 if (parent != nullptr) {
5607 parent->mRequestBufferSM.onSubmittingRequest();
5608 }
5609
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005610 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005611 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005612 submitRequestSuccess = sendRequestsBatch();
5613
Shuzhen Wang686f6442017-06-20 16:16:04 -07005614 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5615 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005616
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005617 if (useFlushLock) {
5618 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005619 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005620
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005621 // Unset as current request
5622 {
5623 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005624 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005625 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005626 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005627
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005628 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005629}
5630
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005631status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005632 ATRACE_CALL();
5633
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005634 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005635 for (size_t i = 0; i < mNextRequests.size(); i++) {
5636 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005637 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5638 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5639 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5640
5641 // Prepare a request to HAL
5642 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5643
5644 // Insert any queued triggers (before metadata is locked)
5645 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005646 if (res < 0) {
5647 SET_ERR("RequestThread: Unable to insert triggers "
5648 "(capture request %d, HAL device: %s (%d)",
5649 halRequest->frame_number, strerror(-res), res);
5650 return INVALID_OPERATION;
5651 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005652
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005653 int triggerCount = res;
5654 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5655 mPrevTriggers = triggerCount;
5656
5657 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005658 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5659 // Request settings are all the same within one batch, so only treat the first
5660 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005661 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005662 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005663 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005664 /**
5665 * HAL workaround:
5666 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5667 */
5668 res = addDummyTriggerIds(captureRequest);
5669 if (res != OK) {
5670 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5671 "(capture request %d, HAL device: %s (%d)",
5672 halRequest->frame_number, strerror(-res), res);
5673 return INVALID_OPERATION;
5674 }
5675
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005676 {
5677 // Correct metadata regions for distortion correction if enabled
5678 sp<Camera3Device> parent = mParent.promote();
5679 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005680 List<PhysicalCameraSettings>::iterator it;
5681 for (it = captureRequest->mSettingsList.begin();
5682 it != captureRequest->mSettingsList.end(); it++) {
5683 if (parent->mDistortionMappers.find(it->cameraId) ==
5684 parent->mDistortionMappers.end()) {
5685 continue;
5686 }
5687 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5688 &(it->metadata));
5689 if (res != OK) {
5690 SET_ERR("RequestThread: Unable to correct capture requests "
5691 "for lens distortion for request %d: %s (%d)",
5692 halRequest->frame_number, strerror(-res), res);
5693 return INVALID_OPERATION;
5694 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005695 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005696
5697 for (it = captureRequest->mSettingsList.begin();
5698 it != captureRequest->mSettingsList.end(); it++) {
5699 if (parent->mZoomRatioMappers.find(it->cameraId) ==
5700 parent->mZoomRatioMappers.end()) {
5701 continue;
5702 }
5703
5704 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
5705 if (e.count > 0 && e.data.f[0] != 1.0f) {
5706 cameraIdsWithZoom.insert(it->cameraId);
5707 }
5708
5709 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
5710 &(it->metadata));
5711 if (res != OK) {
5712 SET_ERR("RequestThread: Unable to correct capture requests "
5713 "for zoom ratio for request %d: %s (%d)",
5714 halRequest->frame_number, strerror(-res), res);
5715 return INVALID_OPERATION;
5716 }
5717 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005718 }
5719 }
5720
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005721 /**
5722 * The request should be presorted so accesses in HAL
5723 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5724 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005725 captureRequest->mSettingsList.begin()->metadata.sort();
5726 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005727 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005728 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005729 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5730
5731 IF_ALOGV() {
5732 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5733 find_camera_metadata_ro_entry(
5734 halRequest->settings,
5735 ANDROID_CONTROL_AF_TRIGGER,
5736 &e
5737 );
5738 if (e.count > 0) {
5739 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5740 __FUNCTION__,
5741 halRequest->frame_number,
5742 e.data.u8[0]);
5743 }
5744 }
5745 } else {
5746 // leave request.settings NULL to indicate 'reuse latest given'
5747 ALOGVV("%s: Request settings are REUSED",
5748 __FUNCTION__);
5749 }
5750
Emilian Peevaebbe412018-01-15 13:53:24 +00005751 if (captureRequest->mSettingsList.size() > 1) {
5752 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5753 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005754 if (newRequest) {
5755 halRequest->physcam_settings =
5756 new const camera_metadata* [halRequest->num_physcam_settings];
5757 } else {
5758 halRequest->physcam_settings = nullptr;
5759 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005760 auto it = ++captureRequest->mSettingsList.begin();
5761 size_t i = 0;
5762 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5763 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005764 if (newRequest) {
5765 it->metadata.sort();
5766 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5767 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005768 }
5769 }
5770
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005771 uint32_t totalNumBuffers = 0;
5772
5773 // Fill in buffers
5774 if (captureRequest->mInputStream != NULL) {
5775 halRequest->input_buffer = &captureRequest->mInputBuffer;
5776 totalNumBuffers += 1;
5777 } else {
5778 halRequest->input_buffer = NULL;
5779 }
5780
5781 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5782 captureRequest->mOutputStreams.size());
5783 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005784 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005785
5786 sp<Camera3Device> parent = mParent.promote();
5787 if (parent == NULL) {
5788 // Should not happen, and nowhere to send errors to, so just log it
5789 CLOGE("RequestThread: Parent is gone");
5790 return INVALID_OPERATION;
5791 }
5792 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5793
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005794 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005795 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005796 sp<Camera3OutputStreamInterface> outputStream =
5797 captureRequest->mOutputStreams.editItemAt(j);
5798 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005799
5800 // Prepare video buffers for high speed recording on the first video request.
5801 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5802 // Only try to prepare video stream on the first video request.
5803 mPrepareVideoStream = false;
5804
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005805 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5806 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005807 while (res == NOT_ENOUGH_DATA) {
5808 res = outputStream->prepareNextBuffer();
5809 }
5810 if (res != OK) {
5811 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5812 __FUNCTION__, strerror(-res), res);
5813 outputStream->cancelPrepare();
5814 }
5815 }
5816
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005817 std::vector<size_t> uniqueSurfaceIds;
5818 res = outputStream->getUniqueSurfaceIds(
5819 captureRequest->mOutputSurfaces[streamId],
5820 &uniqueSurfaceIds);
5821 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5822 if (res != OK && res != INVALID_OPERATION) {
5823 ALOGE("%s: failed to query stream %d unique surface IDs",
5824 __FUNCTION__, streamId);
5825 return res;
5826 }
5827 if (res == OK) {
5828 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5829 }
5830
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005831 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005832 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005833 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005834 return TIMED_OUT;
5835 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005836 // HAL will request buffer through requestStreamBuffer API
5837 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5838 buffer.stream = outputStream->asHalStream();
5839 buffer.buffer = nullptr;
5840 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5841 buffer.acquire_fence = -1;
5842 buffer.release_fence = -1;
5843 } else {
5844 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5845 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005846 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005847 if (res != OK) {
5848 // Can't get output buffer from gralloc queue - this could be due to
5849 // abandoned queue or other consumer misbehavior, so not a fatal
5850 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005851 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005852 " %s (%d)", strerror(-res), res);
5853
5854 return TIMED_OUT;
5855 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005856 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005857
5858 {
5859 sp<Camera3Device> parent = mParent.promote();
5860 if (parent != nullptr) {
5861 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5862 for (const auto& settings : captureRequest->mSettingsList) {
5863 if ((streamCameraId.isEmpty() &&
5864 parent->getId() == settings.cameraId.c_str()) ||
5865 streamCameraId == settings.cameraId.c_str()) {
5866 outputStream->fireBufferRequestForFrameNumber(
5867 captureRequest->mResultExtras.frameNumber,
5868 settings.metadata);
5869 }
5870 }
5871 }
5872 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005873
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005874 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5875
5876 if (!physicalCameraId.isEmpty()) {
5877 // Physical stream isn't supported for input request.
5878 if (halRequest->input_buffer) {
5879 CLOGE("Physical stream is not supported for input request");
5880 return INVALID_OPERATION;
5881 }
5882 requestedPhysicalCameras.insert(physicalCameraId);
5883 }
5884 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005885 }
5886 totalNumBuffers += halRequest->num_output_buffers;
5887
5888 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005889 // If this request list is for constrained high speed recording (not
5890 // preview), and the current request is not the last one in the batch,
5891 // do not send callback to the app.
5892 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005893 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005894 hasCallback = false;
5895 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005896 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005897 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005898 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5899 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5900 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5901 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5902 isStillCapture = true;
5903 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5904 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005905
5906 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5907 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5908 isZslCapture = true;
5909 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005910 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005911 res = parent->registerInFlight(halRequest->frame_number,
5912 totalNumBuffers, captureRequest->mResultExtras,
5913 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005914 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005915 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005916 requestedPhysicalCameras, isStillCapture, isZslCapture, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005917 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5918 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005919 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5920 ", burstId = %" PRId32 ".",
5921 __FUNCTION__,
5922 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5923 captureRequest->mResultExtras.burstId);
5924 if (res != OK) {
5925 SET_ERR("RequestThread: Unable to register new in-flight request:"
5926 " %s (%d)", strerror(-res), res);
5927 return INVALID_OPERATION;
5928 }
5929 }
5930
5931 return OK;
5932}
5933
Igor Murashkin1e479c02013-09-06 16:55:14 -07005934CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005935 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005936 Mutex::Autolock al(mLatestRequestMutex);
5937
5938 ALOGV("RequestThread::%s", __FUNCTION__);
5939
5940 return mLatestRequest;
5941}
5942
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005943bool Camera3Device::RequestThread::isStreamPending(
5944 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005945 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005946 Mutex::Autolock l(mRequestLock);
5947
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005948 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005949 if (!nextRequest.submitted) {
5950 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5951 if (stream == s) return true;
5952 }
5953 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005954 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005955 }
5956
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005957 for (const auto& request : mRequestQueue) {
5958 for (const auto& s : request->mOutputStreams) {
5959 if (stream == s) return true;
5960 }
5961 if (stream == request->mInputStream) return true;
5962 }
5963
5964 for (const auto& request : mRepeatingRequests) {
5965 for (const auto& s : request->mOutputStreams) {
5966 if (stream == s) return true;
5967 }
5968 if (stream == request->mInputStream) return true;
5969 }
5970
5971 return false;
5972}
Jianing Weicb0652e2014-03-12 18:29:36 -07005973
Emilian Peev40ead602017-09-26 15:46:36 +01005974bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5975 ATRACE_CALL();
5976 Mutex::Autolock l(mRequestLock);
5977
5978 for (const auto& nextRequest : mNextRequests) {
5979 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5980 if (s.first == streamId) {
5981 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5982 if (it != s.second.end()) {
5983 return true;
5984 }
5985 }
5986 }
5987 }
5988
5989 for (const auto& request : mRequestQueue) {
5990 for (const auto& s : request->mOutputSurfaces) {
5991 if (s.first == streamId) {
5992 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5993 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005994 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005995 }
5996 }
5997 }
5998 }
5999
6000 for (const auto& request : mRepeatingRequests) {
6001 for (const auto& s : request->mOutputSurfaces) {
6002 if (s.first == streamId) {
6003 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
6004 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07006005 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01006006 }
6007 }
6008 }
6009 }
6010
6011 return false;
6012}
6013
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006014void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
6015 if (!mUseHalBufManager) {
6016 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
6017 return;
6018 }
6019
6020 Mutex::Autolock pl(mPauseLock);
6021 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006022 mInterface->signalPipelineDrain(streamIds);
6023 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006024 }
6025 // If request thread is still busy, wait until paused then notify HAL
6026 mNotifyPipelineDrain = true;
6027 mStreamIdsToBeDrained = streamIds;
6028}
6029
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006030status_t Camera3Device::RequestThread::switchToOffline(
6031 const std::vector<int32_t>& streamsToKeep,
6032 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
6033 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
6034 Mutex::Autolock l(mRequestLock);
6035 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
6036
6037 // Theoretically we should also check for mRepeatingRequests.empty(), but the API interface
6038 // is serialized by mInterfaceLock so skip that check.
6039 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
6040 while (!queueEmpty) {
6041 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
6042 if (res == TIMED_OUT) {
6043 ALOGE("%s: request thread failed to submit a request within timeout!", __FUNCTION__);
6044 return res;
6045 } else if (res != OK) {
6046 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
6047 __FUNCTION__, strerror(-res), res);
6048 return res;
6049 }
6050 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
6051 }
6052 return mInterface->switchToOffline(
6053 streamsToKeep, offlineSessionInfo, offlineSession);
6054}
6055
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07006056nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006057 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07006058 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07006059 return mExpectedInflightDuration > kMinInflightDuration ?
6060 mExpectedInflightDuration : kMinInflightDuration;
6061}
6062
Emilian Peevaebbe412018-01-15 13:53:24 +00006063void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
6064 camera3_capture_request_t *halRequest) {
6065 if ((request == nullptr) || (halRequest == nullptr)) {
6066 ALOGE("%s: Invalid request!", __FUNCTION__);
6067 return;
6068 }
6069
6070 if (halRequest->num_physcam_settings > 0) {
6071 if (halRequest->physcam_id != nullptr) {
6072 delete [] halRequest->physcam_id;
6073 halRequest->physcam_id = nullptr;
6074 }
6075 if (halRequest->physcam_settings != nullptr) {
6076 auto it = ++(request->mSettingsList.begin());
6077 size_t i = 0;
6078 for (; it != request->mSettingsList.end(); it++, i++) {
6079 it->metadata.unlock(halRequest->physcam_settings[i]);
6080 }
6081 delete [] halRequest->physcam_settings;
6082 halRequest->physcam_settings = nullptr;
6083 }
6084 }
6085}
6086
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006087void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
6088 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006089 return;
6090 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006091
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006092 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006093 // Skip the ones that have been submitted successfully.
6094 if (nextRequest.submitted) {
6095 continue;
6096 }
6097
6098 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
6099 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
6100 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
6101
6102 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00006103 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006104 }
6105
Emilian Peevaebbe412018-01-15 13:53:24 +00006106 cleanupPhysicalSettings(captureRequest, halRequest);
6107
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006108 if (captureRequest->mInputStream != NULL) {
6109 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
6110 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
6111 }
6112
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08006113 // No output buffer can be returned when using HAL buffer manager
6114 if (!mUseHalBufManager) {
6115 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
6116 //Buffers that failed processing could still have
6117 //valid acquire fence.
6118 int acquireFence = (*outputBuffers)[i].acquire_fence;
6119 if (0 <= acquireFence) {
6120 close(acquireFence);
6121 outputBuffers->editItemAt(i).acquire_fence = -1;
6122 }
6123 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
6124 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
6125 /*timestampIncreasing*/true, std::vector<size_t> (),
6126 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01006127 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006128 }
6129
6130 if (sendRequestError) {
6131 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006132 sp<NotificationListener> listener = mListener.promote();
6133 if (listener != NULL) {
6134 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006135 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006136 captureRequest->mResultExtras);
6137 }
6138 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07006139
6140 // Remove yet-to-be submitted inflight request from inflightMap
6141 {
6142 sp<Camera3Device> parent = mParent.promote();
6143 if (parent != NULL) {
6144 Mutex::Autolock l(parent->mInFlightLock);
6145 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
6146 if (idx >= 0) {
6147 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
6148 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
6149 parent->removeInFlightMapEntryLocked(idx);
6150 }
6151 }
6152 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006153 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07006154
6155 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006156 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006157}
6158
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006159void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006160 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006161 // Optimized a bit for the simple steady-state case (single repeating
6162 // request), to avoid putting that request in the queue temporarily.
6163 Mutex::Autolock l(mRequestLock);
6164
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006165 assert(mNextRequests.empty());
6166
6167 NextRequest nextRequest;
6168 nextRequest.captureRequest = waitForNextRequestLocked();
6169 if (nextRequest.captureRequest == nullptr) {
6170 return;
6171 }
6172
6173 nextRequest.halRequest = camera3_capture_request_t();
6174 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006175 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006176
6177 // Wait for additional requests
6178 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6179
6180 for (size_t i = 1; i < batchSize; i++) {
6181 NextRequest additionalRequest;
6182 additionalRequest.captureRequest = waitForNextRequestLocked();
6183 if (additionalRequest.captureRequest == nullptr) {
6184 break;
6185 }
6186
6187 additionalRequest.halRequest = camera3_capture_request_t();
6188 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006189 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006190 }
6191
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006192 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006193 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006194 mNextRequests.size(), batchSize);
6195 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006196 }
6197
6198 return;
6199}
6200
6201sp<Camera3Device::CaptureRequest>
6202 Camera3Device::RequestThread::waitForNextRequestLocked() {
6203 status_t res;
6204 sp<CaptureRequest> nextRequest;
6205
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006206 while (mRequestQueue.empty()) {
6207 if (!mRepeatingRequests.empty()) {
6208 // Always atomically enqueue all requests in a repeating request
6209 // list. Guarantees a complete in-sequence set of captures to
6210 // application.
6211 const RequestList &requests = mRepeatingRequests;
6212 RequestList::const_iterator firstRequest =
6213 requests.begin();
6214 nextRequest = *firstRequest;
6215 mRequestQueue.insert(mRequestQueue.end(),
6216 ++firstRequest,
6217 requests.end());
6218 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006219
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006220 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006221
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006222 break;
6223 }
6224
6225 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6226
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006227 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6228 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006229 Mutex::Autolock pl(mPauseLock);
6230 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006231 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006232 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006233 if (mNotifyPipelineDrain) {
6234 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6235 mNotifyPipelineDrain = false;
6236 mStreamIdsToBeDrained.clear();
6237 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006238 // Let the tracker know
6239 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6240 if (statusTracker != 0) {
6241 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6242 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006243 sp<Camera3Device> parent = mParent.promote();
6244 if (parent != nullptr) {
6245 parent->mRequestBufferSM.onRequestThreadPaused();
6246 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006247 }
6248 // Stop waiting for now and let thread management happen
6249 return NULL;
6250 }
6251 }
6252
6253 if (nextRequest == NULL) {
6254 // Don't have a repeating request already in hand, so queue
6255 // must have an entry now.
6256 RequestList::iterator firstRequest =
6257 mRequestQueue.begin();
6258 nextRequest = *firstRequest;
6259 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006260 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6261 sp<NotificationListener> listener = mListener.promote();
6262 if (listener != NULL) {
6263 listener->notifyRequestQueueEmpty();
6264 }
6265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006266 }
6267
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006268 // In case we've been unpaused by setPaused clearing mDoPause, need to
6269 // update internal pause state (capture/setRepeatingRequest unpause
6270 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006271 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006272 if (mPaused) {
6273 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6274 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6275 if (statusTracker != 0) {
6276 statusTracker->markComponentActive(mStatusId);
6277 }
6278 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006279 mPaused = false;
6280
6281 // Check if we've reconfigured since last time, and reset the preview
6282 // request if so. Can't use 'NULL request == repeat' across configure calls.
6283 if (mReconfigured) {
6284 mPrevRequest.clear();
6285 mReconfigured = false;
6286 }
6287
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006288 if (nextRequest != NULL) {
6289 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006290 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6291 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006292
6293 // Since RequestThread::clear() removes buffers from the input stream,
6294 // get the right buffer here before unlocking mRequestLock
6295 if (nextRequest->mInputStream != NULL) {
6296 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6297 if (res != OK) {
6298 // Can't get input buffer from gralloc queue - this could be due to
6299 // disconnected queue or other producer misbehavior, so not a fatal
6300 // error
6301 ALOGE("%s: Can't get input buffer, skipping request:"
6302 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006303
6304 sp<NotificationListener> listener = mListener.promote();
6305 if (listener != NULL) {
6306 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006307 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006308 nextRequest->mResultExtras);
6309 }
6310 return NULL;
6311 }
6312 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006313 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006314
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006315 return nextRequest;
6316}
6317
6318bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006319 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006320 status_t res;
6321 Mutex::Autolock l(mPauseLock);
6322 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006323 if (mPaused == false) {
6324 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006325 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006326 if (mNotifyPipelineDrain) {
6327 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6328 mNotifyPipelineDrain = false;
6329 mStreamIdsToBeDrained.clear();
6330 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006331 // Let the tracker know
6332 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6333 if (statusTracker != 0) {
6334 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6335 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006336 sp<Camera3Device> parent = mParent.promote();
6337 if (parent != nullptr) {
6338 parent->mRequestBufferSM.onRequestThreadPaused();
6339 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006340 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006341
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006342 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006343 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006344 return true;
6345 }
6346 }
6347 // We don't set mPaused to false here, because waitForNextRequest needs
6348 // to further manage the paused state in case of starvation.
6349 return false;
6350}
6351
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006352void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006353 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006354 // With work to do, mark thread as unpaused.
6355 // If paused by request (setPaused), don't resume, to avoid
6356 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006357 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006358 Mutex::Autolock p(mPauseLock);
6359 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006360 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6361 if (mPaused) {
6362 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6363 if (statusTracker != 0) {
6364 statusTracker->markComponentActive(mStatusId);
6365 }
6366 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006367 mPaused = false;
6368 }
6369}
6370
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006371void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6372 sp<Camera3Device> parent = mParent.promote();
6373 if (parent != NULL) {
6374 va_list args;
6375 va_start(args, fmt);
6376
6377 parent->setErrorStateV(fmt, args);
6378
6379 va_end(args);
6380 }
6381}
6382
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006383status_t Camera3Device::RequestThread::insertTriggers(
6384 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006385 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006386 Mutex::Autolock al(mTriggerMutex);
6387
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006388 sp<Camera3Device> parent = mParent.promote();
6389 if (parent == NULL) {
6390 CLOGE("RequestThread: Parent is gone");
6391 return DEAD_OBJECT;
6392 }
6393
Emilian Peevaebbe412018-01-15 13:53:24 +00006394 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006395 size_t count = mTriggerMap.size();
6396
6397 for (size_t i = 0; i < count; ++i) {
6398 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006399 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006400
6401 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6402 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6403 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006404 if (isAeTrigger) {
6405 request->mResultExtras.precaptureTriggerId = triggerId;
6406 mCurrentPreCaptureTriggerId = triggerId;
6407 } else {
6408 request->mResultExtras.afTriggerId = triggerId;
6409 mCurrentAfTriggerId = triggerId;
6410 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006411 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006412 }
6413
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006414 camera_metadata_entry entry = metadata.find(tag);
6415
6416 if (entry.count > 0) {
6417 /**
6418 * Already has an entry for this trigger in the request.
6419 * Rewrite it with our requested trigger value.
6420 */
6421 RequestTrigger oldTrigger = trigger;
6422
6423 oldTrigger.entryValue = entry.data.u8[0];
6424
6425 mTriggerReplacedMap.add(tag, oldTrigger);
6426 } else {
6427 /**
6428 * More typical, no trigger entry, so we just add it
6429 */
6430 mTriggerRemovedMap.add(tag, trigger);
6431 }
6432
6433 status_t res;
6434
6435 switch (trigger.getTagType()) {
6436 case TYPE_BYTE: {
6437 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6438 res = metadata.update(tag,
6439 &entryValue,
6440 /*count*/1);
6441 break;
6442 }
6443 case TYPE_INT32:
6444 res = metadata.update(tag,
6445 &trigger.entryValue,
6446 /*count*/1);
6447 break;
6448 default:
6449 ALOGE("%s: Type not supported: 0x%x",
6450 __FUNCTION__,
6451 trigger.getTagType());
6452 return INVALID_OPERATION;
6453 }
6454
6455 if (res != OK) {
6456 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6457 ", value %d", __FUNCTION__, trigger.getTagName(),
6458 trigger.entryValue);
6459 return res;
6460 }
6461
6462 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6463 trigger.getTagName(),
6464 trigger.entryValue);
6465 }
6466
6467 mTriggerMap.clear();
6468
6469 return count;
6470}
6471
6472status_t Camera3Device::RequestThread::removeTriggers(
6473 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006474 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006475 Mutex::Autolock al(mTriggerMutex);
6476
Emilian Peevaebbe412018-01-15 13:53:24 +00006477 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006478
6479 /**
6480 * Replace all old entries with their old values.
6481 */
6482 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6483 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6484
6485 status_t res;
6486
6487 uint32_t tag = trigger.metadataTag;
6488 switch (trigger.getTagType()) {
6489 case TYPE_BYTE: {
6490 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6491 res = metadata.update(tag,
6492 &entryValue,
6493 /*count*/1);
6494 break;
6495 }
6496 case TYPE_INT32:
6497 res = metadata.update(tag,
6498 &trigger.entryValue,
6499 /*count*/1);
6500 break;
6501 default:
6502 ALOGE("%s: Type not supported: 0x%x",
6503 __FUNCTION__,
6504 trigger.getTagType());
6505 return INVALID_OPERATION;
6506 }
6507
6508 if (res != OK) {
6509 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6510 ", trigger value %d", __FUNCTION__,
6511 trigger.getTagName(), trigger.entryValue);
6512 return res;
6513 }
6514 }
6515 mTriggerReplacedMap.clear();
6516
6517 /**
6518 * Remove all new entries.
6519 */
6520 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6521 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6522 status_t res = metadata.erase(trigger.metadataTag);
6523
6524 if (res != OK) {
6525 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6526 ", trigger value %d", __FUNCTION__,
6527 trigger.getTagName(), trigger.entryValue);
6528 return res;
6529 }
6530 }
6531 mTriggerRemovedMap.clear();
6532
6533 return OK;
6534}
6535
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006536status_t Camera3Device::RequestThread::addDummyTriggerIds(
6537 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006538 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006539 static const int32_t dummyTriggerId = 1;
6540 status_t res;
6541
Emilian Peevaebbe412018-01-15 13:53:24 +00006542 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006543
6544 // If AF trigger is active, insert a dummy AF trigger ID if none already
6545 // exists
6546 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6547 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6548 if (afTrigger.count > 0 &&
6549 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6550 afId.count == 0) {
6551 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6552 if (res != OK) return res;
6553 }
6554
6555 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6556 // if none already exists
6557 camera_metadata_entry pcTrigger =
6558 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6559 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6560 if (pcTrigger.count > 0 &&
6561 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6562 pcId.count == 0) {
6563 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6564 &dummyTriggerId, 1);
6565 if (res != OK) return res;
6566 }
6567
6568 return OK;
6569}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006570
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006571/**
6572 * PreparerThread inner class methods
6573 */
6574
6575Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006576 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006577 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006578}
6579
6580Camera3Device::PreparerThread::~PreparerThread() {
6581 Thread::requestExitAndWait();
6582 if (mCurrentStream != nullptr) {
6583 mCurrentStream->cancelPrepare();
6584 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6585 mCurrentStream.clear();
6586 }
6587 clear();
6588}
6589
Ruben Brunkc78ac262015-08-13 17:58:46 -07006590status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006591 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006592 status_t res;
6593
6594 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006595 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006596
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006597 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006598 if (res == OK) {
6599 // No preparation needed, fire listener right off
6600 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006601 if (listener != NULL) {
6602 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006603 }
6604 return OK;
6605 } else if (res != NOT_ENOUGH_DATA) {
6606 return res;
6607 }
6608
6609 // Need to prepare, start up thread if necessary
6610 if (!mActive) {
6611 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6612 // isn't running
6613 Thread::requestExitAndWait();
6614 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6615 if (res != OK) {
6616 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006617 if (listener != NULL) {
6618 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006619 }
6620 return res;
6621 }
6622 mCancelNow = false;
6623 mActive = true;
6624 ALOGV("%s: Preparer stream started", __FUNCTION__);
6625 }
6626
6627 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006628 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006629 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6630
6631 return OK;
6632}
6633
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006634void Camera3Device::PreparerThread::pause() {
6635 ATRACE_CALL();
6636
6637 Mutex::Autolock l(mLock);
6638
6639 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6640 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6641 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6642 int currentMaxCount = mCurrentMaxCount;
6643 mPendingStreams.clear();
6644 mCancelNow = true;
6645 while (mActive) {
6646 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6647 if (res == TIMED_OUT) {
6648 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6649 return;
6650 } else if (res != OK) {
6651 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6652 return;
6653 }
6654 }
6655
6656 //Check whether the prepare thread was able to complete the current
6657 //stream. In case work is still pending emplace it along with the rest
6658 //of the streams in the pending list.
6659 if (currentStream != nullptr) {
6660 if (!mCurrentPrepareComplete) {
6661 pendingStreams.emplace(currentMaxCount, currentStream);
6662 }
6663 }
6664
6665 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6666 for (const auto& it : mPendingStreams) {
6667 it.second->cancelPrepare();
6668 }
6669}
6670
6671status_t Camera3Device::PreparerThread::resume() {
6672 ATRACE_CALL();
6673 status_t res;
6674
6675 Mutex::Autolock l(mLock);
6676 sp<NotificationListener> listener = mListener.promote();
6677
6678 if (mActive) {
6679 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6680 return NO_INIT;
6681 }
6682
6683 auto it = mPendingStreams.begin();
6684 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006685 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006686 if (res == OK) {
6687 if (listener != NULL) {
6688 listener->notifyPrepared(it->second->getId());
6689 }
6690 it = mPendingStreams.erase(it);
6691 } else if (res != NOT_ENOUGH_DATA) {
6692 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6693 res, strerror(-res));
6694 it = mPendingStreams.erase(it);
6695 } else {
6696 it++;
6697 }
6698 }
6699
6700 if (mPendingStreams.empty()) {
6701 return OK;
6702 }
6703
6704 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6705 if (res != OK) {
6706 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6707 __FUNCTION__, res, strerror(-res));
6708 return res;
6709 }
6710 mCancelNow = false;
6711 mActive = true;
6712 ALOGV("%s: Preparer stream started", __FUNCTION__);
6713
6714 return OK;
6715}
6716
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006717status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006718 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006719 Mutex::Autolock l(mLock);
6720
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006721 for (const auto& it : mPendingStreams) {
6722 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006723 }
6724 mPendingStreams.clear();
6725 mCancelNow = true;
6726
6727 return OK;
6728}
6729
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006730void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006731 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006732 Mutex::Autolock l(mLock);
6733 mListener = listener;
6734}
6735
6736bool Camera3Device::PreparerThread::threadLoop() {
6737 status_t res;
6738 {
6739 Mutex::Autolock l(mLock);
6740 if (mCurrentStream == nullptr) {
6741 // End thread if done with work
6742 if (mPendingStreams.empty()) {
6743 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6744 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6745 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6746 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006747 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006748 return false;
6749 }
6750
6751 // Get next stream to prepare
6752 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006753 mCurrentStream = it->second;
6754 mCurrentMaxCount = it->first;
6755 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006756 mPendingStreams.erase(it);
6757 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6758 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6759 } else if (mCancelNow) {
6760 mCurrentStream->cancelPrepare();
6761 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6762 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6763 mCurrentStream.clear();
6764 mCancelNow = false;
6765 return true;
6766 }
6767 }
6768
6769 res = mCurrentStream->prepareNextBuffer();
6770 if (res == NOT_ENOUGH_DATA) return true;
6771 if (res != OK) {
6772 // Something bad happened; try to recover by cancelling prepare and
6773 // signalling listener anyway
6774 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6775 mCurrentStream->getId(), res, strerror(-res));
6776 mCurrentStream->cancelPrepare();
6777 }
6778
6779 // This stream has finished, notify listener
6780 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006781 sp<NotificationListener> listener = mListener.promote();
6782 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006783 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6784 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006785 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006786 }
6787
6788 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6789 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006790 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006791
6792 return true;
6793}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006794
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006795status_t Camera3Device::RequestBufferStateMachine::initialize(
6796 sp<camera3::StatusTracker> statusTracker) {
6797 if (statusTracker == nullptr) {
6798 ALOGE("%s: statusTracker is null", __FUNCTION__);
6799 return BAD_VALUE;
6800 }
6801
6802 std::lock_guard<std::mutex> lock(mLock);
6803 mStatusTracker = statusTracker;
6804 mRequestBufferStatusId = statusTracker->addComponent();
6805 return OK;
6806}
6807
6808bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6809 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006810 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006811 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006812 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006813 return true;
6814 }
6815 return false;
6816}
6817
6818void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6819 std::lock_guard<std::mutex> lock(mLock);
6820 if (!mRequestBufferOngoing) {
6821 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6822 return;
6823 }
6824 mRequestBufferOngoing = false;
6825 if (mStatus == RB_STATUS_PENDING_STOP) {
6826 checkSwitchToStopLocked();
6827 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006828 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006829}
6830
6831void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6832 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006833 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006834 return;
6835}
6836
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006837void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006838 std::lock_guard<std::mutex> lock(mLock);
6839 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006840 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6841 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006842 mInflightMapEmpty = false;
6843 if (mStatus == RB_STATUS_STOPPED) {
6844 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006845 }
6846 return;
6847}
6848
6849void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6850 std::lock_guard<std::mutex> lock(mLock);
6851 mRequestThreadPaused = true;
6852 if (mStatus == RB_STATUS_PENDING_STOP) {
6853 checkSwitchToStopLocked();
6854 }
6855 return;
6856}
6857
6858void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6859 std::lock_guard<std::mutex> lock(mLock);
6860 mInflightMapEmpty = true;
6861 if (mStatus == RB_STATUS_PENDING_STOP) {
6862 checkSwitchToStopLocked();
6863 }
6864 return;
6865}
6866
6867void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6868 std::lock_guard<std::mutex> lock(mLock);
6869 if (!checkSwitchToStopLocked()) {
6870 mStatus = RB_STATUS_PENDING_STOP;
6871 }
6872 return;
6873}
6874
6875void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6876 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6877 if (statusTracker != nullptr) {
6878 if (active) {
6879 statusTracker->markComponentActive(mRequestBufferStatusId);
6880 } else {
6881 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6882 }
6883 }
6884}
6885
6886bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6887 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6888 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006889 return true;
6890 }
6891 return false;
6892}
6893
Shuzhen Wang268a1362018-10-16 16:32:59 -07006894status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6895 CameraMetadata& resultMetadata) {
6896 status_t res = OK;
6897 if (!mNeedFixupMonochromeTags) {
6898 return res;
6899 }
6900
6901 // Remove tags that are not applicable to monochrome camera.
6902 int32_t tagsToRemove[] = {
6903 ANDROID_SENSOR_GREEN_SPLIT,
6904 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6905 ANDROID_COLOR_CORRECTION_MODE,
6906 ANDROID_COLOR_CORRECTION_TRANSFORM,
6907 ANDROID_COLOR_CORRECTION_GAINS,
6908 };
6909 for (auto tag : tagsToRemove) {
6910 res = resultMetadata.erase(tag);
6911 if (res != OK) {
6912 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6913 return res;
6914 }
6915 }
6916
6917 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6918 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6919 for (size_t i = 1; i < blEntry.count; i++) {
6920 blEntry.data.f[i] = blEntry.data.f[0];
6921 }
6922
6923 // ANDROID_SENSOR_NOISE_PROFILE
6924 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6925 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6926 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6927 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6928 if (res != OK) {
6929 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6930 __FUNCTION__, strerror(-res), res);
6931 return res;
6932 }
6933 }
6934
6935 // ANDROID_STATISTICS_LENS_SHADING_MAP
6936 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6937 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6938 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6939 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6940 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6941 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6942 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6943 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6944 }
6945 }
6946
6947 // ANDROID_TONEMAP_CURVE_BLUE
6948 // ANDROID_TONEMAP_CURVE_GREEN
6949 // ANDROID_TONEMAP_CURVE_RED
6950 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6951 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6952 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6953 if (tcbEntry.count > 0
6954 && tcbEntry.count == tcgEntry.count
6955 && tcbEntry.count == tcrEntry.count) {
6956 for (size_t i = 0; i < tcbEntry.count; i++) {
6957 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6958 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6959 }
6960 }
6961
6962 return res;
6963}
6964
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006965status_t Camera3Device::switchToOffline(
6966 const std::vector<int32_t>& streamsToKeep,
6967 /*out*/ sp<CameraOfflineSessionBase>* session) {
6968 ATRACE_CALL();
6969 if (session == nullptr) {
6970 ALOGE("%s: session must not be null", __FUNCTION__);
6971 return BAD_VALUE;
6972 }
6973
6974 Mutex::Autolock il(mInterfaceLock);
6975 Mutex::Autolock l(mLock);
6976
6977 // 1. Stop repeating request, wait until request thread submitted all requests, then
6978 // call HAL switchToOffline
6979 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6980 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
6981
6982 mRequestThread->switchToOffline(streamsToKeep, &offlineSessionInfo, &offlineSession);
6983
6984
6985 // 2. Verify offlineSessionInfo
6986 // 3. create Camera3OfflineSession and transfer object ownership
6987 // (streams, inflight requests, buffer caches)
6988 *session = new Camera3OfflineSession(mId);
6989
6990 // 4. Delete unneeded streams
6991 // 5. Verify Camera3Device is in unconfigured state
6992 return OK;
6993}
6994
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006995}; // namespace android