blob: 738cf531e9988827743b4091300c0593572ef669 [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
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.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"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Jayant Chowdhary0bd38522021-11-05 17:49:27 -070068#include "../common/hidl/HidlProviderInfo.h"
69
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080070#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080071#include <tuple>
72
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080073using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074using namespace android::hardware::camera;
75using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080076using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080077
78namespace android {
79
Emilian Peev5104fe92021-10-21 14:27:09 -070080Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070082 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080083 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070084 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070085 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070086 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070087 mUsePartialResult(false),
88 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080089 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070091 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070093 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070094 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070095 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000096 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010097 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070098 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070099 mNeedFixupMonochromeTags(false),
100 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
106Camera3Device::~Camera3Device()
107{
108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700110 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111}
112
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800113const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800114 return mId;
115}
116
Emilian Peevbd8c5032018-02-14 23:05:40 +0000117status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118 ATRACE_CALL();
119 Mutex::Autolock il(mInterfaceLock);
120 Mutex::Autolock l(mLock);
121
122 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
123 if (mStatus != STATUS_UNINITIALIZED) {
124 CLOGE("Already initialized!");
125 return INVALID_OPERATION;
126 }
127 if (manager == nullptr) return INVALID_OPERATION;
128
129 sp<ICameraDeviceSession> session;
130 ATRACE_BEGIN("CameraHal::openSession");
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700131 status_t res = manager->openHidlSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 /*out*/ &session);
133 ATRACE_END();
134 if (res != OK) {
135 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
136 return res;
137 }
138
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700139 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700141 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800142 session->close();
143 return res;
144 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800145 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800146
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700147 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700148 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700149 if (isLogical) {
150 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700151 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700152 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700153 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700154 if (res != OK) {
155 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
156 physicalId.c_str(), strerror(-res), res);
157 session->close();
158 return res;
159 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700160
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800161 bool usePrecorrectArray =
162 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
163 if (usePrecorrectArray) {
164 res = mDistortionMappers[physicalId].setupStaticInfo(
165 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700166 if (res != OK) {
167 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
168 "correction", physicalId.c_str());
169 session->close();
170 return res;
171 }
172 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800173
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800174 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800175 &mPhysicalDeviceInfoMap[physicalId],
176 mSupportNativeZoomRatio, usePrecorrectArray);
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700177
178 if (SessionConfigurationUtils::isUltraHighResolutionSensor(
179 mPhysicalDeviceInfoMap[physicalId])) {
180 mUHRCropAndMeteringRegionMappers[physicalId] =
181 UHRCropAndMeteringRegionMapper(mPhysicalDeviceInfoMap[physicalId],
182 usePrecorrectArray);
183 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700184 }
185 }
186
Yifan Hongf79b5542017-04-11 14:44:25 -0700187 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700188 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
189 [&queue](const auto& descriptor) {
190 queue = std::make_shared<RequestMetadataQueue>(descriptor);
191 if (!queue->isValid() || queue->availableToWrite() <= 0) {
192 ALOGE("HAL returns empty request metadata fmq, not use it");
193 queue = nullptr;
194 // don't use the queue onwards.
195 }
196 });
197 if (!requestQueueRet.isOk()) {
198 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
199 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700200 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700201 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700202
203 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700204 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700205 [&resQueue](const auto& descriptor) {
206 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
207 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700208 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700209 resQueue = nullptr;
210 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700211 }
212 });
213 if (!resultQueueRet.isOk()) {
214 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
215 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700216 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700217 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700218 IF_ALOGV() {
219 session->interfaceChain([](
220 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
221 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800222 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700223 ALOGV(" %s", iface.c_str());
224 }
225 });
226 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700227
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800228 camera_metadata_entry bufMgrMode =
229 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
230 if (bufMgrMode.count > 0) {
231 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
232 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
233 }
234
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700235 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
236 for (size_t i = 0; i < capabilities.count; i++) {
237 uint8_t capability = capabilities.data.u8[i];
238 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
239 mSupportOfflineProcessing = true;
240 }
241 }
242
243 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000244 std::string providerType;
245 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000246 mTagMonitor.initialize(mVendorTagId);
247 if (!monitorTags.isEmpty()) {
248 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
249 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800250
Shuzhen Wang268a1362018-10-16 16:32:59 -0700251 // Metadata tags needs fixup for monochrome camera device version less
252 // than 3.5.
253 hardware::hidl_version maxVersion{0,0};
254 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
255 if (res != OK) {
256 ALOGE("%s: Error in getting camera device version id: %s (%d)",
257 __FUNCTION__, strerror(-res), res);
258 return res;
259 }
260 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
261 maxVersion.get_major(), maxVersion.get_minor());
262
263 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700264 for (size_t i = 0; i < capabilities.count; i++) {
265 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700266 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
267 isMonochrome = true;
268 }
269 }
270 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
271
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800272 return initializeCommonLocked();
273}
274
275status_t Camera3Device::initializeCommonLocked() {
276
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700277 /** Start up status tracker thread */
278 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800279 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700280 if (res != OK) {
281 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
282 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800283 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284 mStatusTracker.clear();
285 return res;
286 }
287
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700288 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700289 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700290
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700291 if (mUseHalBufManager) {
292 res = mRequestBufferSM.initialize(mStatusTracker);
293 if (res != OK) {
294 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
295 strerror(-res), res);
296 mInterface->close();
297 mStatusTracker.clear();
298 return res;
299 }
300 }
301
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800302 /** Create buffer manager */
303 mBufferManager = new Camera3BufferManager();
304
305 Vector<int32_t> sessionParamKeys;
306 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
307 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
308 if (sessionKeysEntry.count > 0) {
309 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
310 }
311
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700312 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
313 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
314 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
315 if (availableTestPatternModes.data.i32[i] ==
316 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
317 mSupportCameraMute = true;
318 mSupportTestPatternSolidColor = true;
319 break;
320 } else if (availableTestPatternModes.data.i32[i] ==
321 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
322 mSupportCameraMute = true;
323 mSupportTestPatternSolidColor = false;
324 }
325 }
326
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700327 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700328 mRequestThread = new RequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700329 this, mStatusTracker, mInterface, sessionParamKeys,
330 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800331 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800332 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700333 SET_ERR_L("Unable to start request queue thread: %s (%d)",
334 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800335 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800336 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800337 return res;
338 }
339
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700340 mPreparerThread = new PreparerThread();
341
Ruben Brunk183f0562015-08-12 12:55:02 -0700342 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400344 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700345 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800347 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800348
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800349 // Measure the clock domain offset between camera and video/hw_composer
350 camera_metadata_entry timestampSource =
351 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
352 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
353 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
354 mTimestampOffset = getMonoToBoottimeOffset();
355 }
356
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700357 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100358 camera_metadata_entry partialResultsCount =
359 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
360 if (partialResultsCount.count > 0) {
361 mNumPartialResults = partialResultsCount.data.i32[0];
362 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700363 }
364
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800365 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
366 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700367 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700368 if (res != OK) {
369 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
370 return res;
371 }
372 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800373
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800374 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800375 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800376
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700377 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
378 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
379 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
380 }
381
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800382 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
383 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
384 }
385
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800386 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
387
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800388 return OK;
389}
390
391status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700392 return disconnectImpl();
393}
394
395status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800396 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700397 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800398
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700399 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700400 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700401 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800402 Mutex::Autolock il(mInterfaceLock);
403 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
404 {
405 Mutex::Autolock l(mLock);
406 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 if (mStatus == STATUS_ACTIVE ||
409 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
410 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700413 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800414 } else {
415 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
416 if (res != OK) {
417 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
418 maxExpectedDuration);
419 // Continue to close device even in case of error
420 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700421 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700422 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800423
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800424 if (mStatus == STATUS_ERROR) {
425 CLOGE("Shutting down in an error state");
426 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700427
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800428 if (mStatusTracker != NULL) {
429 mStatusTracker->requestExit();
430 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 if (mRequestThread != NULL) {
433 mRequestThread->requestExit();
434 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700435
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800436 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
437 for (size_t i = 0; i < mOutputStreams.size(); i++) {
438 streams.push_back(mOutputStreams[i]);
439 }
440 if (mInputStream != nullptr) {
441 streams.push_back(mInputStream);
442 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700443 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700444 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800445 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
446 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700447 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
448 // HAL may be in a bad state, so waiting for request thread
449 // (which may be stuck in the HAL processCaptureRequest call)
450 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800451 // give up mInterfaceLock here and then lock it again. Could this lead
452 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700453 mRequestThread->join();
454 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700455 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800456 Mutex::Autolock il(mInterfaceLock);
457 if (mStatusTracker != NULL) {
458 mStatusTracker->join();
459 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800460
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800461 if (mInjectionMethods->isInjecting()) {
462 mInjectionMethods->stopInjection();
463 }
464
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800465 HalInterface* interface;
466 {
467 Mutex::Autolock l(mLock);
468 mRequestThread.clear();
469 Mutex::Autolock stLock(mTrackerLock);
470 mStatusTracker.clear();
471 interface = mInterface.get();
472 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700473
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800474 // Call close without internal mutex held, as the HAL close may need to
475 // wait on assorted callbacks,etc, to complete before it can return.
476 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700477
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800478 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800479
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800480 {
481 Mutex::Autolock l(mLock);
482 mInterface->clear();
483 mOutputStreams.clear();
484 mInputStream.clear();
485 mDeletedStreams.clear();
486 mBufferManager.clear();
487 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
488 }
489
490 for (auto& weakStream : streams) {
491 sp<Camera3StreamInterface> stream = weakStream.promote();
492 if (stream != nullptr) {
493 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
494 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
495 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700496 }
497 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700498 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700499 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800500}
501
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700502// For dumping/debugging only -
503// try to acquire a lock a few times, eventually give up to proceed with
504// debug/dump operations
505bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
506 bool gotLock = false;
507 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
508 if (lock.tryLock() == NO_ERROR) {
509 gotLock = true;
510 break;
511 } else {
512 usleep(kDumpSleepDuration);
513 }
514 }
515 return gotLock;
516}
517
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800518nsecs_t Camera3Device::getMonoToBoottimeOffset() {
519 // try three times to get the clock offset, choose the one
520 // with the minimum gap in measurements.
521 const int tries = 3;
522 nsecs_t bestGap, measured;
523 for (int i = 0; i < tries; ++i) {
524 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
526 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
527 const nsecs_t gap = tmono2 - tmono;
528 if (i == 0 || gap < bestGap) {
529 bestGap = gap;
530 measured = tbase - ((tmono + tmono2) >> 1);
531 }
532 }
533 return measured;
534}
535
Emilian Peev2295df72021-11-12 18:14:10 -0800536CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap
537Camera3Device::mapToHidlDynamicProfile(int dynamicRangeProfile) {
538 return static_cast<CameraMetadataEnumAndroidRequestAvailableDynamicRangeProfilesMap>(
539 dynamicRangeProfile);
540}
541
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800542hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
543 int frameworkFormat) {
544 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
545}
546
547DataspaceFlags Camera3Device::mapToHidlDataspace(
548 android_dataspace dataSpace) {
549 return dataSpace;
550}
551
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700552BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100553 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700554 return usage;
555}
556
Emilian Peevf4816702020-04-03 15:44:51 -0700557StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700559 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700561 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800562 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700563 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800564 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700565 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800566 return StreamRotation::ROTATION_270;
567 }
568 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
569 return StreamRotation::ROTATION_0;
570}
571
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800572status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700573 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800574 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700575 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800576 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700577 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800578 *mode = StreamConfigurationMode::NORMAL_MODE;
579 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700580 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
582 break;
583 default:
584 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
585 return BAD_VALUE;
586 }
587 } else {
588 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800589 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800590 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591}
592
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800593int Camera3Device::mapToFrameworkFormat(
594 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
595 return static_cast<uint32_t>(pixelFormat);
596}
597
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700598android_dataspace Camera3Device::mapToFrameworkDataspace(
599 DataspaceFlags dataSpace) {
600 return static_cast<android_dataspace>(dataSpace);
601}
602
Emilian Peev050f5dc2017-05-18 14:43:56 +0100603uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700604 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700605 return usage;
606}
607
Emilian Peev050f5dc2017-05-18 14:43:56 +0100608uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700609 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700610 return usage;
611}
612
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800613ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
614 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700615 // Get max jpeg size (area-wise) for default sensor pixel mode
616 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800617 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700618 /*isUltraHighResolutionSensor*/false);
619 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
620 // not ultra high res sensor
621 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800622 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700623 /*isUltraHighResolution*/true);
624 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
626 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700627 return BAD_VALUE;
628 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700629 bool useMaxSensorPixelModeThreshold = false;
630 if (uhrMaxJpegResolution.width != 0 &&
631 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
632 // Use the ultra high res max jpeg size and max jpeg buffer size
633 useMaxSensorPixelModeThreshold = true;
634 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700635
Zhijun Hef7da0962014-04-24 13:27:56 -0700636 // Get max jpeg buffer size
637 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800638 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700639 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
641 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 return BAD_VALUE;
643 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700644 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700645
646 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
647 if (useMaxSensorPixelModeThreshold) {
648 maxJpegBufferSize =
649 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
650 maxDefaultJpegResolution, maxJpegBufferSize);
651 chosenMaxJpegResolution = uhrMaxJpegResolution;
652 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800653 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700654
655 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700656 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700657 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800658 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
659 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700660 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800661 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
662 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700663 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700664 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700665 return jpegBufferSize;
666}
667
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800668ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700669 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800670 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700671 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
673 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700674 return BAD_VALUE;
675 }
676 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
677 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
678 return maxBytesForPointCloud;
679}
680
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800681ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
682 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800683 const int PER_CONFIGURATION_SIZE = 3;
684 const int WIDTH_OFFSET = 0;
685 const int HEIGHT_OFFSET = 1;
686 const int SIZE_OFFSET = 2;
687 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800688 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800689 camera3::SessionConfigurationUtils::getAppropriateModeTag(
690 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
691 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800692 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800693 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800694 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
695 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800696 return BAD_VALUE;
697 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700698
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800699 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
700 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
701 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
702 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
703 }
704 }
705
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800706 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
707 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800708 return BAD_VALUE;
709}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700710
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800711status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
712 ATRACE_CALL();
713 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700714
715 // Try to lock, but continue in case of failure (to avoid blocking in
716 // deadlocks)
717 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
718 bool gotLock = tryLockSpinRightRound(mLock);
719
720 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800721 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
722 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700723 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800724 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
725 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700726
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800727 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700728
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800729 String16 templatesOption("-t");
730 int n = args.size();
731 for (int i = 0; i < n; i++) {
732 if (args[i] == templatesOption) {
733 dumpTemplates = true;
734 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000735 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700736 if (i + 1 < n) {
737 String8 monitorTags = String8(args[i + 1]);
738 if (monitorTags == "off") {
739 mTagMonitor.disableMonitoring();
740 } else {
741 mTagMonitor.parseTagsToMonitor(monitorTags);
742 }
743 } else {
744 mTagMonitor.disableMonitoring();
745 }
746 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800747 }
748
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800750
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 const char *status =
752 mStatus == STATUS_ERROR ? "ERROR" :
753 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700754 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
755 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 mStatus == STATUS_ACTIVE ? "ACTIVE" :
757 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700758
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800759 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700760 if (mStatus == STATUS_ERROR) {
761 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
762 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800763 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800764 const char *mode =
765 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
766 mOperatingMode == static_cast<int>(
767 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
768 "CUSTOM";
769 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800770
771 if (mInputStream != NULL) {
772 write(fd, lines.string(), lines.size());
773 mInputStream->dump(fd, args);
774 } else {
775 lines.appendFormat(" No input stream.\n");
776 write(fd, lines.string(), lines.size());
777 }
778 for (size_t i = 0; i < mOutputStreams.size(); i++) {
779 mOutputStreams[i]->dump(fd,args);
780 }
781
Zhijun He431503c2016-03-07 17:30:16 -0800782 if (mBufferManager != NULL) {
783 lines = String8(" Camera3 Buffer Manager:\n");
784 write(fd, lines.string(), lines.size());
785 mBufferManager->dump(fd, args);
786 }
Zhijun He125684a2015-12-26 15:07:30 -0800787
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700788 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700789 if (mInFlightLock.try_lock()) {
790 if (mInFlightMap.size() == 0) {
791 lines.append(" None\n");
792 } else {
793 for (size_t i = 0; i < mInFlightMap.size(); i++) {
794 InFlightRequest r = mInFlightMap.valueAt(i);
795 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
796 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
797 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
798 r.numBuffersLeft);
799 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700800 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700801 mInFlightLock.unlock();
802 } else {
803 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700804 }
805 write(fd, lines.string(), lines.size());
806
Shuzhen Wang686f6442017-06-20 16:16:04 -0700807 if (mRequestThread != NULL) {
808 mRequestThread->dumpCaptureRequestLatency(fd,
809 " ProcessCaptureRequest latency histogram:");
810 }
811
Igor Murashkin1e479c02013-09-06 16:55:14 -0700812 {
813 lines = String8(" Last request sent:\n");
814 write(fd, lines.string(), lines.size());
815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700816 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700817 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
818 }
819
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800820 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700821 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800822 "TEMPLATE_PREVIEW",
823 "TEMPLATE_STILL_CAPTURE",
824 "TEMPLATE_VIDEO_RECORD",
825 "TEMPLATE_VIDEO_SNAPSHOT",
826 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800827 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800828 };
829
Emilian Peevf4816702020-04-03 15:44:51 -0700830 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800831 camera_metadata_t *templateRequest = nullptr;
832 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700833 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800834 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800836 lines.append(" Not supported\n");
837 write(fd, lines.string(), lines.size());
838 } else {
839 write(fd, lines.string(), lines.size());
840 dump_indented_camera_metadata(templateRequest,
841 fd, /*verbosity*/2, /*indentation*/8);
842 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800843 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800844 }
845 }
846
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700847 mTagMonitor.dumpMonitoredMetadata(fd);
848
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800849 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800850 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800852 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700855 if (gotLock) mLock.unlock();
856 if (gotInterfaceLock) mInterfaceLock.unlock();
857
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800858 return OK;
859}
860
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700861status_t Camera3Device::startWatchingTags(const String8 &tags) {
862 mTagMonitor.parseTagsToMonitor(tags);
863 return OK;
864}
865
866status_t Camera3Device::stopWatchingTags() {
867 mTagMonitor.disableMonitoring();
868 return OK;
869}
870
871status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
872 mTagMonitor.getLatestMonitoredTagEvents(out);
873 return OK;
874}
875
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800876const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
879 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700880 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 mStatus == STATUS_ERROR ?
882 "when in error state" : "before init");
883 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700884 if (physicalId.isEmpty()) {
885 return mDeviceInfo;
886 } else {
887 std::string id(physicalId.c_str());
888 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
889 return mPhysicalDeviceInfoMap.at(id);
890 } else {
891 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
892 return mDeviceInfo;
893 }
894 }
895}
896
897const CameraMetadata& Camera3Device::info() const {
898 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800899 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800900}
901
Jianing Wei90e59c92014-03-12 18:29:36 -0700902status_t Camera3Device::checkStatusOkToCaptureLocked() {
903 switch (mStatus) {
904 case STATUS_ERROR:
905 CLOGE("Device has encountered a serious error");
906 return INVALID_OPERATION;
907 case STATUS_UNINITIALIZED:
908 CLOGE("Device not initialized");
909 return INVALID_OPERATION;
910 case STATUS_UNCONFIGURED:
911 case STATUS_CONFIGURED:
912 case STATUS_ACTIVE:
913 // OK
914 break;
915 default:
916 SET_ERR_L("Unexpected status: %d", mStatus);
917 return INVALID_OPERATION;
918 }
919 return OK;
920}
921
922status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000923 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700924 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700925 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700926 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700927 if (requestList == NULL) {
928 CLOGE("requestList cannot be NULL.");
929 return BAD_VALUE;
930 }
931
Jianing Weicb0652e2014-03-12 18:29:36 -0700932 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000933 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700934 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
935 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
936 ++metadataIt, ++surfaceMapIt) {
937 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700938 if (newRequest == 0) {
939 CLOGE("Can't create capture request");
940 return BAD_VALUE;
941 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700942
Shuzhen Wang9d066012016-09-30 11:30:20 -0700943 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700944 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700945
Jianing Weicb0652e2014-03-12 18:29:36 -0700946 // Setup burst Id and request Id
947 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800948 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
949 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700950 CLOGE("RequestID does not exist in metadata");
951 return BAD_VALUE;
952 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800953 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700954
Jianing Wei90e59c92014-03-12 18:29:36 -0700955 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700956
957 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700958 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700959 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
960 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
961 return BAD_VALUE;
962 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700963
964 // Setup batch size if this is a high speed video recording request.
965 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
966 auto firstRequest = requestList->begin();
967 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
968 if (outputStream->isVideoStream()) {
969 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800970 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700971 break;
972 }
973 }
974 }
975
Jianing Wei90e59c92014-03-12 18:29:36 -0700976 return OK;
977}
978
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800979status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800980 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800981
Emilian Peevaebbe412018-01-15 13:53:24 +0000982 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000984 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700985
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800986 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700987}
988
Emilian Peevaebbe412018-01-15 13:53:24 +0000989void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700990 std::list<const SurfaceMap>& surfaceMaps,
991 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000992 PhysicalCameraSettingsList requestList;
993 requestList.push_back({std::string(getId().string()), request});
994 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700995
996 SurfaceMap surfaceMap;
997 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
998 // With no surface list passed in, stream and surface will have 1-to-1
999 // mapping. So the surface index is 0 for each stream in the surfaceMap.
1000 for (size_t i = 0; i < streams.count; i++) {
1001 surfaceMap[streams.data.i32[i]].push_back(0);
1002 }
1003 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001004}
1005
Jianing Wei90e59c92014-03-12 18:29:36 -07001006status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +00001007 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001008 const std::list<const SurfaceMap> &surfaceMaps,
1009 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001010 /*out*/
1011 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001012 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001013 nsecs_t requestTimeNs = systemTime();
1014
Jianing Wei90e59c92014-03-12 18:29:36 -07001015 Mutex::Autolock il(mInterfaceLock);
1016 Mutex::Autolock l(mLock);
1017
1018 status_t res = checkStatusOkToCaptureLocked();
1019 if (res != OK) {
1020 // error logged by previous call
1021 return res;
1022 }
1023
1024 RequestList requestList;
1025
Shuzhen Wang0129d522016-10-30 22:43:41 -07001026 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001027 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -07001028 if (res != OK) {
1029 // error logged by previous call
1030 return res;
1031 }
1032
1033 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001034 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001035 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001036 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001037 }
1038
1039 if (res == OK) {
1040 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1041 if (res != OK) {
1042 SET_ERR_L("Can't transition to active in %f seconds!",
1043 kActiveTimeout/1e9);
1044 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001045 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001046 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001047 } else {
1048 CLOGE("Cannot queue request. Impossible.");
1049 return BAD_VALUE;
1050 }
1051
1052 return res;
1053}
1054
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001055hardware::Return<void> Camera3Device::requestStreamBuffers(
1056 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1057 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001058 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001059 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001060 *this, *mInterface, *this};
1061 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001062 return hardware::Void();
1063}
1064
1065hardware::Return<void> Camera3Device::returnStreamBuffers(
1066 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001067 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001068 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001069 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001070 return hardware::Void();
1071}
1072
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001073hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001074 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001075 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001076 // Ideally we should grab mLock, but that can lead to deadlock, and
1077 // it's not super important to get up to date value of mStatus for this
1078 // warning print, hence skipping the lock here
1079 if (mStatus == STATUS_ERROR) {
1080 // Per API contract, HAL should act as closed after device error
1081 // But mStatus can be set to error by framework as well, so just log
1082 // a warning here.
1083 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001084 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001085
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001086 sp<NotificationListener> listener;
1087 {
1088 std::lock_guard<std::mutex> l(mOutputLock);
1089 listener = mListener.promote();
1090 }
1091
Yifan Honga640c5a2017-04-12 16:30:31 -07001092 if (mProcessCaptureResultLock.tryLock() != OK) {
1093 // This should never happen; it indicates a wrong client implementation
1094 // that doesn't follow the contract. But, we can be tolerant here.
1095 ALOGE("%s: callback overlapped! waiting 1s...",
1096 __FUNCTION__);
1097 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1098 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1099 __FUNCTION__);
1100 // really don't know what to do, so bail out.
1101 return hardware::Void();
1102 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001103 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001104 CaptureOutputStates states {
1105 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001106 mInFlightLock, mLastCompletedRegularFrameNumber,
1107 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1108 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001109 mNextShutterFrameNumber,
1110 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1111 mNextResultFrameNumber,
1112 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1113 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1114 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001115 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001116 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001117 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001118 };
1119
Yifan Honga640c5a2017-04-12 16:30:31 -07001120 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001121 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001122 }
1123 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001124 return hardware::Void();
1125}
1126
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001127// Only one processCaptureResult should be called at a time, so
1128// the locks won't block. The locks are present here simply to enforce this.
1129hardware::Return<void> Camera3Device::processCaptureResult(
1130 const hardware::hidl_vec<
1131 hardware::camera::device::V3_2::CaptureResult>& results) {
1132 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1133
1134 // Ideally we should grab mLock, but that can lead to deadlock, and
1135 // it's not super important to get up to date value of mStatus for this
1136 // warning print, hence skipping the lock here
1137 if (mStatus == STATUS_ERROR) {
1138 // Per API contract, HAL should act as closed after device error
1139 // But mStatus can be set to error by framework as well, so just log
1140 // a warning here.
1141 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1142 }
1143
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001144 sp<NotificationListener> listener;
1145 {
1146 std::lock_guard<std::mutex> l(mOutputLock);
1147 listener = mListener.promote();
1148 }
1149
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001150 if (mProcessCaptureResultLock.tryLock() != OK) {
1151 // This should never happen; it indicates a wrong client implementation
1152 // that doesn't follow the contract. But, we can be tolerant here.
1153 ALOGE("%s: callback overlapped! waiting 1s...",
1154 __FUNCTION__);
1155 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1156 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1157 __FUNCTION__);
1158 // really don't know what to do, so bail out.
1159 return hardware::Void();
1160 }
1161 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001162
1163 CaptureOutputStates states {
1164 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001165 mInFlightLock, mLastCompletedRegularFrameNumber,
1166 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1167 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001168 mNextShutterFrameNumber,
1169 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1170 mNextResultFrameNumber,
1171 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1172 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1173 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001174 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001175 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001176 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001177 };
1178
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001179 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001180 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001181 }
1182 mProcessCaptureResultLock.unlock();
1183 return hardware::Void();
1184}
1185
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001186hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001187 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Shuzhen Wang90708ea2021-11-04 11:40:49 -07001188 return notifyHelper<hardware::camera::device::V3_2::NotifyMsg>(msgs);
1189}
1190
1191hardware::Return<void> Camera3Device::notify_3_8(
1192 const hardware::hidl_vec<hardware::camera::device::V3_8::NotifyMsg>& msgs) {
1193 return notifyHelper<hardware::camera::device::V3_8::NotifyMsg>(msgs);
1194}
1195
1196template<typename NotifyMsgType>
1197hardware::Return<void> Camera3Device::notifyHelper(const hardware::hidl_vec<NotifyMsgType>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001198 // Ideally we should grab mLock, but that can lead to deadlock, and
1199 // it's not super important to get up to date value of mStatus for this
1200 // warning print, hence skipping the lock here
1201 if (mStatus == STATUS_ERROR) {
1202 // Per API contract, HAL should act as closed after device error
1203 // But mStatus can be set to error by framework as well, so just log
1204 // a warning here.
1205 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001206 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001207
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001208 sp<NotificationListener> listener;
1209 {
1210 std::lock_guard<std::mutex> l(mOutputLock);
1211 listener = mListener.promote();
1212 }
1213
1214 CaptureOutputStates states {
1215 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001216 mInFlightLock, mLastCompletedRegularFrameNumber,
1217 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1218 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001219 mNextShutterFrameNumber,
1220 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1221 mNextResultFrameNumber,
1222 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1223 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1224 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001225 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001226 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
Emilian Peev5104fe92021-10-21 14:27:09 -07001227 *mInterface, mLegacyClient
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001228 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001229 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001230 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001231 }
1232 return hardware::Void();
1233}
1234
Emilian Peevaebbe412018-01-15 13:53:24 +00001235status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001236 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001237 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001238 ATRACE_CALL();
1239
Emilian Peevaebbe412018-01-15 13:53:24 +00001240 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001241}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001242
Jianing Weicb0652e2014-03-12 18:29:36 -07001243status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1244 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001245 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246
Emilian Peevaebbe412018-01-15 13:53:24 +00001247 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001248 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001249 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001250
Emilian Peevaebbe412018-01-15 13:53:24 +00001251 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001252 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253}
1254
Emilian Peevaebbe412018-01-15 13:53:24 +00001255status_t Camera3Device::setStreamingRequestList(
1256 const List<const PhysicalCameraSettingsList> &requestsList,
1257 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001258 ATRACE_CALL();
1259
Emilian Peevaebbe412018-01-15 13:53:24 +00001260 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001261}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262
1263sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001264 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 status_t res;
1266
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001268 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1269 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001270 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001271 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001272 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001274 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001276 } else if (mStatus == STATUS_UNCONFIGURED) {
1277 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 CLOGE("No streams configured");
1279 return NULL;
1280 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 }
1282
Shuzhen Wang0129d522016-10-30 22:43:41 -07001283 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001285}
1286
Jianing Weicb0652e2014-03-12 18:29:36 -07001287status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001288 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001291
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 switch (mStatus) {
1293 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001294 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001295 return INVALID_OPERATION;
1296 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 case STATUS_UNCONFIGURED:
1300 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301 case STATUS_ACTIVE:
1302 // OK
1303 break;
1304 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001305 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001306 return INVALID_OPERATION;
1307 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001308 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001309
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001310 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001311}
1312
1313status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1314 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001316
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001317 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001318}
1319
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001321 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001322 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001323 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001324 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001325 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001326 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1327 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001328
1329 status_t res;
1330 bool wasActive = false;
1331
1332 switch (mStatus) {
1333 case STATUS_ERROR:
1334 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1335 return INVALID_OPERATION;
1336 case STATUS_UNINITIALIZED:
1337 ALOGE("%s: Device not initialized", __FUNCTION__);
1338 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001339 case STATUS_UNCONFIGURED:
1340 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001341 // OK
1342 break;
1343 case STATUS_ACTIVE:
1344 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001345 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001346 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001348 return res;
1349 }
1350 wasActive = true;
1351 break;
1352 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001353 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001354 return INVALID_OPERATION;
1355 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001356 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001357
1358 if (mInputStream != 0) {
1359 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1360 return INVALID_OPERATION;
1361 }
1362
1363 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1364 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001365 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001366
1367 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001368 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001369
1370 *id = mNextStreamId++;
1371
1372 // Continue captures if active at start
1373 if (wasActive) {
1374 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001375 // Reuse current operating mode and session parameters for new stream config
1376 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001377 if (res != OK) {
1378 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1379 __FUNCTION__, mNextStreamId, strerror(-res), res);
1380 return res;
1381 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001382 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001383 }
1384
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001385 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001386 return OK;
1387}
1388
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001389status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001390 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001391 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001392 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001393 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1394 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Emilian Peev2295df72021-11-12 18:14:10 -08001395 uint64_t consumerUsage, int dynamicRangeProfile) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001396 ATRACE_CALL();
1397
1398 if (consumer == nullptr) {
1399 ALOGE("%s: consumer must not be null", __FUNCTION__);
1400 return BAD_VALUE;
1401 }
1402
1403 std::vector<sp<Surface>> consumers;
1404 consumers.push_back(consumer);
1405
1406 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001407 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Emilian Peev2295df72021-11-12 18:14:10 -08001408 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001409}
1410
1411static bool isRawFormat(int format) {
1412 switch (format) {
1413 case HAL_PIXEL_FORMAT_RAW16:
1414 case HAL_PIXEL_FORMAT_RAW12:
1415 case HAL_PIXEL_FORMAT_RAW10:
1416 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1417 return true;
1418 default:
1419 return false;
1420 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001421}
1422
1423status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1424 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001425 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001426 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001427 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Emilian Peev2295df72021-11-12 18:14:10 -08001428 uint64_t consumerUsage, int dynamicRangeProfile) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001429 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001430
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001431 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001432 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001434 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001435 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1436 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1437 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001438
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 status_t res;
1440 bool wasActive = false;
1441
1442 switch (mStatus) {
1443 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001444 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 return INVALID_OPERATION;
1446 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001447 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 case STATUS_UNCONFIGURED:
1450 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 // OK
1452 break;
1453 case STATUS_ACTIVE:
1454 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001455 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 return res;
1459 }
1460 wasActive = true;
1461 break;
1462 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001463 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 return INVALID_OPERATION;
1465 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001466 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467
1468 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001469
Shuzhen Wang0129d522016-10-30 22:43:41 -07001470 if (consumers.size() == 0 && !hasDeferredConsumer) {
1471 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1472 return BAD_VALUE;
1473 }
Zhijun He5d677d12016-05-29 16:52:39 -07001474
Shuzhen Wang0129d522016-10-30 22:43:41 -07001475 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001476 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1477 return BAD_VALUE;
1478 }
1479
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001480 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1481 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1482 // be found in only one sensor pixel mode.
1483 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1484 return BAD_VALUE;
1485 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001487 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001488 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001489 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001490 if (blobBufferSize <= 0) {
1491 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1492 return BAD_VALUE;
1493 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001494 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1495 blobBufferSize = width * height;
1496 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001497 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001498 if (blobBufferSize <= 0) {
1499 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1500 return BAD_VALUE;
1501 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001502 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001503 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001504 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001505 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001506 isMultiResolution, dynamicRangeProfile);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001507 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001508 bool maxResolution =
1509 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1510 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001511 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1512 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001513 if (rawOpaqueBufferSize <= 0) {
1514 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1515 return BAD_VALUE;
1516 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001517 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001518 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001519 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001520 isMultiResolution, dynamicRangeProfile);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001521 } else if (isShared) {
1522 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1523 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001524 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001525 mUseHalBufManager, dynamicRangeProfile);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001526 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001527 newStream = new Camera3OutputStream(mNextStreamId,
1528 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001529 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001530 isMultiResolution, dynamicRangeProfile);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001532 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001533 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001534 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001535 isMultiResolution, dynamicRangeProfile);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 }
Emilian Peev40ead602017-09-26 15:46:36 +01001537
1538 size_t consumerCount = consumers.size();
1539 for (size_t i = 0; i < consumerCount; i++) {
1540 int id = newStream->getSurfaceId(consumers[i]);
1541 if (id < 0) {
1542 SET_ERR_L("Invalid surface id");
1543 return BAD_VALUE;
1544 }
1545 if (surfaceIds != nullptr) {
1546 surfaceIds->push_back(id);
1547 }
1548 }
1549
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551
Emilian Peev08dd2452017-04-06 16:55:14 +01001552 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001553
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001554 newStream->setImageDumpMask(mImageDumpMask);
1555
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 res = mOutputStreams.add(mNextStreamId, newStream);
1557 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return res;
1560 }
1561
Shuzhen Wang316781a2020-08-18 18:11:01 -07001562 mSessionStatsBuilder.addStream(mNextStreamId);
1563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001565 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566
1567 // Continue captures if active at start
1568 if (wasActive) {
1569 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001570 // Reuse current operating mode and session parameters for new stream config
1571 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1574 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return res;
1576 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001577 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001579 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001581}
1582
Emilian Peev710c1422017-08-30 11:19:38 +01001583status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001584 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001585 if (nullptr == streamInfo) {
1586 return BAD_VALUE;
1587 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 switch (mStatus) {
1592 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001593 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 return INVALID_OPERATION;
1595 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001596 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001598 case STATUS_UNCONFIGURED:
1599 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 case STATUS_ACTIVE:
1601 // OK
1602 break;
1603 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001604 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 return INVALID_OPERATION;
1606 }
1607
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001608 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1609 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001610 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001611 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 }
1613
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001614 streamInfo->width = stream->getWidth();
1615 streamInfo->height = stream->getHeight();
1616 streamInfo->format = stream->getFormat();
1617 streamInfo->dataSpace = stream->getDataSpace();
1618 streamInfo->formatOverridden = stream->isFormatOverridden();
1619 streamInfo->originalFormat = stream->getOriginalFormat();
1620 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1621 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001622 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001624}
1625
1626status_t Camera3Device::setStreamTransform(int id,
1627 int transform) {
1628 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 switch (mStatus) {
1633 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001634 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001635 return INVALID_OPERATION;
1636 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001637 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001638 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 case STATUS_UNCONFIGURED:
1640 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 case STATUS_ACTIVE:
1642 // OK
1643 break;
1644 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001645 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 return INVALID_OPERATION;
1647 }
1648
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001649 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1650 if (stream == nullptr) {
1651 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001652 return BAD_VALUE;
1653 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001654 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001655}
1656
1657status_t Camera3Device::deleteStream(int id) {
1658 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001659 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001660 Mutex::Autolock l(mLock);
1661 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001663 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001664
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001665 // CameraDevice semantics require device to already be idle before
1666 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001668 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001669 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001670 }
1671
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001672 if (mStatus == STATUS_ERROR) {
1673 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1674 __FUNCTION__, mId.string());
1675 return -EBUSY;
1676 }
1677
Igor Murashkin2fba5842013-04-22 14:03:54 -07001678 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001679 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001680 if (mInputStream != NULL && id == mInputStream->getId()) {
1681 deletedStream = mInputStream;
1682 mInputStream.clear();
1683 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001684 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001685 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001686 return BAD_VALUE;
1687 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001688 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001689 }
1690
1691 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001692 if (stream != nullptr) {
1693 deletedStream = stream;
1694 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001695 }
1696
1697 // Free up the stream endpoint so that it can be used by some other stream
1698 res = deletedStream->disconnect();
1699 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001700 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001701 // fall through since we want to still list the stream as deleted.
1702 }
1703 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001704 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001705
1706 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707}
1708
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001709status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001710 ATRACE_CALL();
1711 ALOGV("%s: E", __FUNCTION__);
1712
1713 Mutex::Autolock il(mInterfaceLock);
1714 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001715
Emilian Peev811d2952018-05-25 11:08:40 +01001716 // In case the client doesn't include any session parameter, try a
1717 // speculative configuration using the values from the last cached
1718 // default request.
1719 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001720 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001721 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1722 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1723 mLastTemplateId);
1724 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1725 operatingMode);
1726 }
1727
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001728 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1729}
1730
1731status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1732 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001733 //Filter out any incoming session parameters
1734 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001735 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1736 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001737 CameraMetadata filteredParams(availableSessionKeys.count);
1738 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1739 filteredParams.getAndLock());
1740 set_camera_metadata_vendor_id(meta, mVendorTagId);
1741 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001742 if (availableSessionKeys.count > 0) {
1743 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1744 camera_metadata_ro_entry entry = params.find(
1745 availableSessionKeys.data.i32[i]);
1746 if (entry.count > 0) {
1747 filteredParams.update(entry);
1748 }
1749 }
1750 }
1751
1752 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001753}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001754
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001755status_t Camera3Device::getInputBufferProducer(
1756 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001757 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001758 Mutex::Autolock il(mInterfaceLock);
1759 Mutex::Autolock l(mLock);
1760
1761 if (producer == NULL) {
1762 return BAD_VALUE;
1763 } else if (mInputStream == NULL) {
1764 return INVALID_OPERATION;
1765 }
1766
1767 return mInputStream->getInputBufferProducer(producer);
1768}
1769
Emilian Peevf4816702020-04-03 15:44:51 -07001770status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001771 CameraMetadata *request) {
1772 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001773 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001774
Emilian Peevf4816702020-04-03 15:44:51 -07001775 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001776 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001777 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001778 return BAD_VALUE;
1779 }
1780
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001781 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001782
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001783 {
1784 Mutex::Autolock l(mLock);
1785 switch (mStatus) {
1786 case STATUS_ERROR:
1787 CLOGE("Device has encountered a serious error");
1788 return INVALID_OPERATION;
1789 case STATUS_UNINITIALIZED:
1790 CLOGE("Device is not initialized!");
1791 return INVALID_OPERATION;
1792 case STATUS_UNCONFIGURED:
1793 case STATUS_CONFIGURED:
1794 case STATUS_ACTIVE:
1795 // OK
1796 break;
1797 default:
1798 SET_ERR_L("Unexpected status: %d", mStatus);
1799 return INVALID_OPERATION;
1800 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001801
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001802 if (!mRequestTemplateCache[templateId].isEmpty()) {
1803 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001804 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001805 return OK;
1806 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001807 }
1808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001809 camera_metadata_t *rawRequest;
1810 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001811 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001812
1813 {
1814 Mutex::Autolock l(mLock);
1815 if (res == BAD_VALUE) {
1816 ALOGI("%s: template %d is not supported on this camera device",
1817 __FUNCTION__, templateId);
1818 return res;
1819 } else if (res != OK) {
1820 CLOGE("Unable to construct request template %d: %s (%d)",
1821 templateId, strerror(-res), res);
1822 return res;
1823 }
1824
1825 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1826 mRequestTemplateCache[templateId].acquire(rawRequest);
1827
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001828 // Override the template request with zoomRatioMapper
1829 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1830 &mRequestTemplateCache[templateId]);
1831 if (res != OK) {
1832 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1833 templateId, strerror(-res), res);
1834 return res;
1835 }
1836
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001837 // Fill in JPEG_QUALITY if not available
1838 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1839 static const uint8_t kDefaultJpegQuality = 95;
1840 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1841 &kDefaultJpegQuality, 1);
1842 }
1843
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001844 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001845 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001846 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001847 return OK;
1848}
1849
1850status_t Camera3Device::waitUntilDrained() {
1851 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001853 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001855
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001856 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001857}
1858
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001859status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001860 switch (mStatus) {
1861 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001863 ALOGV("%s: Already idle", __FUNCTION__);
1864 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 case STATUS_CONFIGURED:
1866 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 case STATUS_ERROR:
1868 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 break;
1871 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001872 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 return INVALID_OPERATION;
1874 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001875 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1876 maxExpectedDuration);
1877 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001878 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001879 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001880 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1881 res);
1882 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001883 return res;
1884}
1885
Ruben Brunk183f0562015-08-12 12:55:02 -07001886void Camera3Device::internalUpdateStatusLocked(Status status) {
1887 mStatus = status;
1888 mRecentStatusUpdates.add(mStatus);
1889 mStatusChanged.broadcast();
1890}
1891
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001893status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001894 if (mRequestThread.get() != nullptr) {
1895 mRequestThread->setPaused(true);
1896 } else {
1897 return NO_INIT;
1898 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001900 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1901 maxExpectedDuration);
1902 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903 if (res != OK) {
1904 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001905 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001906 }
1907
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001908 return res;
1909}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001910
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001911// Resume after internalPauseAndWaitLocked
1912status_t Camera3Device::internalResumeLocked() {
1913 status_t res;
1914
1915 mRequestThread->setPaused(false);
1916
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001917 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1918 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001919 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1920 if (res != OK) {
1921 SET_ERR_L("Can't transition to active in %f seconds!",
1922 kActiveTimeout/1e9);
1923 }
1924 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001925 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926}
1927
Ruben Brunk183f0562015-08-12 12:55:02 -07001928status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001930
1931 size_t startIndex = 0;
1932 if (mStatusWaiters == 0) {
1933 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1934 // this status list
1935 mRecentStatusUpdates.clear();
1936 } else {
1937 // If other threads are waiting on updates to this status list, set the position of the
1938 // first element that this list will check rather than clearing the list.
1939 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001940 }
1941
Ruben Brunk183f0562015-08-12 12:55:02 -07001942 mStatusWaiters++;
1943
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001944 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001945 if (!active && mUseHalBufManager) {
1946 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001947 if (mStatus == STATUS_ACTIVE) {
1948 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001949 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001950 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001951 mRequestBufferSM.onWaitUntilIdle();
1952 }
1953
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001954 bool stateSeen = false;
1955 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001956 if (active == (mStatus == STATUS_ACTIVE)) {
1957 // Desired state is current
1958 break;
1959 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001960
1961 res = mStatusChanged.waitRelative(mLock, timeout);
1962 if (res != OK) break;
1963
Ruben Brunk183f0562015-08-12 12:55:02 -07001964 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1965 // transitions.
1966 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1967 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1968 __FUNCTION__);
1969
1970 // Encountered desired state since we began waiting
1971 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001972 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1973 stateSeen = true;
1974 break;
1975 }
1976 }
1977 } while (!stateSeen);
1978
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001979 if (signalPipelineDrain) {
1980 mRequestThread->resetPipelineDrain();
1981 }
1982
Ruben Brunk183f0562015-08-12 12:55:02 -07001983 mStatusWaiters--;
1984
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001985 return res;
1986}
1987
1988
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001989status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001991 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001993 if (listener != NULL && mListener != NULL) {
1994 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1995 }
1996 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001997 mRequestThread->setNotificationListener(listener);
1998 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001999
2000 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001}
2002
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002003bool Camera3Device::willNotify3A() {
2004 return false;
2005}
2006
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002008 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002009 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002010
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002011 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002012 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
2013 if (st == std::cv_status::timeout) {
2014 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002015 }
2016 }
2017 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002018}
2019
Jianing Weicb0652e2014-03-12 18:29:36 -07002020status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002021 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002022 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002023
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002024 if (mResultQueue.empty()) {
2025 return NOT_ENOUGH_DATA;
2026 }
2027
Jianing Weicb0652e2014-03-12 18:29:36 -07002028 if (frame == NULL) {
2029 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2030 return BAD_VALUE;
2031 }
2032
2033 CaptureResult &result = *(mResultQueue.begin());
2034 frame->mResultExtras = result.mResultExtras;
2035 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002036 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002037 mResultQueue.erase(mResultQueue.begin());
2038
2039 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002040}
2041
2042status_t Camera3Device::triggerAutofocus(uint32_t id) {
2043 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002044 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2047 // Mix-in this trigger into the next request and only the next request.
2048 RequestTrigger trigger[] = {
2049 {
2050 ANDROID_CONTROL_AF_TRIGGER,
2051 ANDROID_CONTROL_AF_TRIGGER_START
2052 },
2053 {
2054 ANDROID_CONTROL_AF_TRIGGER_ID,
2055 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002056 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002057 };
2058
2059 return mRequestThread->queueTrigger(trigger,
2060 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002061}
2062
2063status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2064 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002066
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002067 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2068 // Mix-in this trigger into the next request and only the next request.
2069 RequestTrigger trigger[] = {
2070 {
2071 ANDROID_CONTROL_AF_TRIGGER,
2072 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2073 },
2074 {
2075 ANDROID_CONTROL_AF_TRIGGER_ID,
2076 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002077 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002078 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002079
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002080 return mRequestThread->queueTrigger(trigger,
2081 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002082}
2083
2084status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2085 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002086 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002087
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002088 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2089 // Mix-in this trigger into the next request and only the next request.
2090 RequestTrigger trigger[] = {
2091 {
2092 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2093 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2094 },
2095 {
2096 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2097 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002098 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002099 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002100
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002101 return mRequestThread->queueTrigger(trigger,
2102 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002103}
2104
Jianing Weicb0652e2014-03-12 18:29:36 -07002105status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002107 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002108 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002109
Zhijun He7ef20392014-04-21 16:04:17 -07002110 {
2111 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002112
2113 // b/116514106 "disconnect()" can get called twice for the same device. The
2114 // camera device will not be initialized during the second run.
2115 if (mStatus == STATUS_UNINITIALIZED) {
2116 return OK;
2117 }
2118
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002119 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002120
2121 // Stop session and stream counter
2122 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002123 }
2124
Emilian Peev08dd2452017-04-06 16:55:14 +01002125 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002126}
2127
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002128status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002129 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2130}
2131
2132status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002133 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002134 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002135 Mutex::Autolock il(mInterfaceLock);
2136 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002137
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002138 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2139 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002140 CLOGE("Stream %d does not exist", streamId);
2141 return BAD_VALUE;
2142 }
2143
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002144 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002145 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002146 return BAD_VALUE;
2147 }
2148
2149 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002150 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002151 return BAD_VALUE;
2152 }
2153
Ruben Brunkc78ac262015-08-13 17:58:46 -07002154 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002155}
2156
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002157status_t Camera3Device::tearDown(int streamId) {
2158 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002159 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002160 Mutex::Autolock il(mInterfaceLock);
2161 Mutex::Autolock l(mLock);
2162
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002163 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2164 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002165 CLOGE("Stream %d does not exist", streamId);
2166 return BAD_VALUE;
2167 }
2168
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002169 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2170 CLOGE("Stream %d is a target of a in-progress request", streamId);
2171 return BAD_VALUE;
2172 }
2173
2174 return stream->tearDown();
2175}
2176
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002177status_t Camera3Device::addBufferListenerForStream(int streamId,
2178 wp<Camera3StreamBufferListener> listener) {
2179 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002180 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002181 Mutex::Autolock il(mInterfaceLock);
2182 Mutex::Autolock l(mLock);
2183
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002184 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2185 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002186 CLOGE("Stream %d does not exist", streamId);
2187 return BAD_VALUE;
2188 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002189 stream->addBufferListener(listener);
2190
2191 return OK;
2192}
2193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195 * Methods called by subclasses
2196 */
2197
2198void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002199 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002200 std::vector<int> streamIds;
2201 std::vector<hardware::CameraStreamStats> streamStats;
2202
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002203 {
2204 // Need mLock to safely update state and synchronize to current
2205 // state of methods in flight.
2206 Mutex::Autolock l(mLock);
2207 // We can get various system-idle notices from the status tracker
2208 // while starting up. Only care about them if we've actually sent
2209 // in some requests recently.
2210 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2211 return;
2212 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002213 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2214 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002215 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002216
2217 // Skip notifying listener if we're doing some user-transparent
2218 // state changes
2219 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002220
2221 // Populate stream statistics in case of Idle
2222 if (idle) {
2223 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2224 auto stream = mOutputStreams[i];
2225 if (stream.get() == nullptr) continue;
2226 streamIds.push_back(stream->getId());
2227 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2228 int64_t usage = 0LL;
2229 if (camera3Stream != nullptr) {
2230 usage = camera3Stream->getUsage();
2231 }
2232 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2233 stream->getFormat(), stream->getDataSpace(), usage,
2234 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08002235 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
2236 stream->getDynamicRangeProfile());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002237 }
2238 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002239 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002240
2241 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002242 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002243 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002244 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002246 status_t res = OK;
2247 if (listener != nullptr) {
2248 if (idle) {
2249 // Get session stats from the builder, and notify the listener.
2250 int64_t requestCount, resultErrorCount;
2251 bool deviceError;
2252 std::map<int, StreamStats> streamStatsMap;
2253 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2254 &deviceError, &streamStatsMap);
2255 for (size_t i = 0; i < streamIds.size(); i++) {
2256 int streamId = streamIds[i];
2257 auto stats = streamStatsMap.find(streamId);
2258 if (stats != streamStatsMap.end()) {
2259 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2260 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2261 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2262 streamStats[i].mHistogramType =
2263 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2264 streamStats[i].mHistogramBins.assign(
2265 stats->second.mCaptureLatencyBins.begin(),
2266 stats->second.mCaptureLatencyBins.end());
2267 streamStats[i].mHistogramCounts.assign(
2268 stats->second.mCaptureLatencyHistogram.begin(),
2269 stats->second.mCaptureLatencyHistogram.end());
2270 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002271 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002272 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2273 } else {
2274 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002275 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002276 }
2277 if (res != OK) {
2278 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2279 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002280 }
2281}
2282
Shuzhen Wang758c2152017-01-10 18:26:18 -08002283status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002284 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002285 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002286 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2287 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002288
2289 if (surfaceIds == nullptr) {
2290 return BAD_VALUE;
2291 }
2292
Zhijun He5d677d12016-05-29 16:52:39 -07002293 Mutex::Autolock il(mInterfaceLock);
2294 Mutex::Autolock l(mLock);
2295
Shuzhen Wang758c2152017-01-10 18:26:18 -08002296 if (consumers.size() == 0) {
2297 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002298 return BAD_VALUE;
2299 }
2300
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002301 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2302 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002303 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002304 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002305 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002306
2307 // isConsumerConfigurationDeferred will be off after setConsumers
2308 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002309 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002310 if (res != OK) {
2311 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2312 return res;
2313 }
2314
Emilian Peev40ead602017-09-26 15:46:36 +01002315 for (auto &consumer : consumers) {
2316 int id = stream->getSurfaceId(consumer);
2317 if (id < 0) {
2318 CLOGE("Invalid surface id!");
2319 return BAD_VALUE;
2320 }
2321 surfaceIds->push_back(id);
2322 }
2323
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002324 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002325 if (!stream->isConfiguring()) {
2326 CLOGE("Stream %d was already fully configured.", streamId);
2327 return INVALID_OPERATION;
2328 }
Zhijun He5d677d12016-05-29 16:52:39 -07002329
Shuzhen Wang0129d522016-10-30 22:43:41 -07002330 res = stream->finishConfiguration();
2331 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002332 // If finishConfiguration fails due to abandoned surface, do not set
2333 // device to error state.
2334 bool isSurfaceAbandoned =
2335 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2336 if (!isSurfaceAbandoned) {
2337 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2338 stream->getId(), strerror(-res), res);
2339 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002340 return res;
2341 }
Zhijun He5d677d12016-05-29 16:52:39 -07002342 }
2343
2344 return OK;
2345}
2346
Emilian Peev40ead602017-09-26 15:46:36 +01002347status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2348 const std::vector<OutputStreamInfo> &outputInfo,
2349 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2350 Mutex::Autolock il(mInterfaceLock);
2351 Mutex::Autolock l(mLock);
2352
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002353 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2354 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002355 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002356 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002357 }
2358
2359 for (const auto &it : removedSurfaceIds) {
2360 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2361 CLOGE("Shared surface still part of a pending request!");
2362 return -EBUSY;
2363 }
2364 }
2365
Emilian Peev40ead602017-09-26 15:46:36 +01002366 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2367 if (res != OK) {
2368 CLOGE("Stream %d failed to update stream (error %d %s) ",
2369 streamId, res, strerror(-res));
2370 if (res == UNKNOWN_ERROR) {
2371 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2372 __FUNCTION__);
2373 }
2374 return res;
2375 }
2376
2377 return res;
2378}
2379
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002380status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2381 Mutex::Autolock il(mInterfaceLock);
2382 Mutex::Autolock l(mLock);
2383
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002384 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2385 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002386 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2387 return BAD_VALUE;
2388 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002389
2390 if (dropping) {
2391 mSessionStatsBuilder.stopCounter(streamId);
2392 } else {
2393 mSessionStatsBuilder.startCounter(streamId);
2394 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002395 return stream->dropBuffers(dropping);
2396}
2397
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002398/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 * Camera3Device private methods
2400 */
2401
2402sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002403 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002404 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002405
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002406 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002407 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408
2409 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002410 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 if (inputStreams.count > 0) {
2412 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002413 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002414 CLOGE("Request references unknown input stream %d",
2415 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002416 return NULL;
2417 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002418
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002419 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002420 SET_ERR_L("%s: input stream %d is not configured!",
2421 __FUNCTION__, mInputStream->getId());
2422 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002424 // Check if stream prepare is blocking requests.
2425 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002426 CLOGE("Request references an input stream that's being prepared!");
2427 return NULL;
2428 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002429
2430 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002431 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002432 }
2433
2434 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002435 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002437 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002438 return NULL;
2439 }
2440
2441 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002442 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2443 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002444 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002445 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 return NULL;
2447 }
Zhijun He5d677d12016-05-29 16:52:39 -07002448 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002449 auto iter = surfaceMap.find(streams.data.i32[i]);
2450 if (iter != surfaceMap.end()) {
2451 const std::vector<size_t>& surfaces = iter->second;
2452 for (const auto& surface : surfaces) {
2453 if (stream->isConsumerConfigurationDeferred(surface)) {
2454 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2455 "due to deferred consumer", stream->getId(), surface);
2456 return NULL;
2457 }
2458 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002459 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002460 }
2461
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002462 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002463 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2464 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002465 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002466 // Check if stream prepare is blocking requests.
2467 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002468 CLOGE("Request references an output stream that's being prepared!");
2469 return NULL;
2470 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002471
2472 newRequest->mOutputStreams.push(stream);
2473 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002474 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002475 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002477 auto rotateAndCropEntry =
2478 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2479 if (rotateAndCropEntry.count > 0 &&
2480 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2481 newRequest->mRotateAndCropAuto = true;
2482 } else {
2483 newRequest->mRotateAndCropAuto = false;
2484 }
2485
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002486 auto zoomRatioEntry =
2487 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2488 if (zoomRatioEntry.count > 0 &&
2489 zoomRatioEntry.data.f[0] == 1.0f) {
2490 newRequest->mZoomRatioIs1x = true;
2491 } else {
2492 newRequest->mZoomRatioIs1x = false;
2493 }
2494
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002495 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002496 for (auto& settings : newRequest->mSettingsList) {
2497 auto testPatternModeEntry =
2498 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2499 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2500 testPatternModeEntry.data.i32[0] :
2501 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002502
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002503 auto testPatternDataEntry =
2504 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2505 if (testPatternDataEntry.count >= 4) {
2506 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2507 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2508 } else {
2509 settings.mOriginalTestPatternData[0] = 0;
2510 settings.mOriginalTestPatternData[1] = 0;
2511 settings.mOriginalTestPatternData[2] = 0;
2512 settings.mOriginalTestPatternData[3] = 0;
2513 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002514 }
2515 }
2516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002517 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002518}
2519
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002520void Camera3Device::cancelStreamsConfigurationLocked() {
2521 int res = OK;
2522 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2523 res = mInputStream->cancelConfiguration();
2524 if (res != OK) {
2525 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2526 mInputStream->getId(), strerror(-res), res);
2527 }
2528 }
2529
2530 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002531 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002532 if (outputStream->isConfiguring()) {
2533 res = outputStream->cancelConfiguration();
2534 if (res != OK) {
2535 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2536 outputStream->getId(), strerror(-res), res);
2537 }
2538 }
2539 }
2540
2541 // Return state to that at start of call, so that future configures
2542 // properly clean things up
2543 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2544 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002545
2546 res = mPreparerThread->resume();
2547 if (res != OK) {
2548 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2549 }
2550}
2551
Emilian Peev0d0191e2020-04-21 17:01:18 -07002552bool Camera3Device::checkAbandonedStreamsLocked() {
2553 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2554 return true;
2555 }
2556
2557 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2558 auto stream = mOutputStreams[i];
2559 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2560 return true;
2561 }
2562 }
2563
2564 return false;
2565}
2566
Emilian Peev3bead5f2020-05-28 17:29:08 -07002567bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002568 ATRACE_CALL();
2569 bool ret = false;
2570
Shuzhen Wang316781a2020-08-18 18:11:01 -07002571 nsecs_t startTime = systemTime();
2572
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002573 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002574 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2575
2576 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002577 if (checkAbandonedStreamsLocked()) {
2578 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2579 __FUNCTION__);
2580 return true;
2581 }
2582
Emilian Peev3bead5f2020-05-28 17:29:08 -07002583 status_t rc = NO_ERROR;
2584 bool markClientActive = false;
2585 if (mStatus == STATUS_ACTIVE) {
2586 markClientActive = true;
2587 mPauseStateNotify = true;
2588 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2589
2590 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2591 }
2592
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002593 if (rc == NO_ERROR) {
2594 mNeedConfig = true;
2595 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2596 if (rc == NO_ERROR) {
2597 ret = true;
2598 mPauseStateNotify = false;
2599 //Moving to active state while holding 'mLock' is important.
2600 //There could be pending calls to 'create-/deleteStream' which
2601 //will trigger another stream configuration while the already
2602 //present streams end up with outstanding buffers that will
2603 //not get drained.
2604 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002605 } else if (rc == DEAD_OBJECT) {
2606 // DEAD_OBJECT can be returned if either the consumer surface is
2607 // abandoned, or the HAL has died.
2608 // - If the HAL has died, configureStreamsLocked call will set
2609 // device to error state,
2610 // - If surface is abandoned, we should not set device to error
2611 // state.
2612 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002613 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002614 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002615 }
2616 } else {
2617 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2618 }
2619
Shuzhen Wang316781a2020-08-18 18:11:01 -07002620 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2621 ns2ms(systemTime() - startTime));
2622
Emilian Peev3bead5f2020-05-28 17:29:08 -07002623 if (markClientActive) {
2624 mStatusTracker->markComponentActive(clientStatusId);
2625 }
2626
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002627 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002628}
2629
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002630status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002631 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632 ATRACE_CALL();
2633 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002634
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002635 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002636 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 return INVALID_OPERATION;
2638 }
2639
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002640 if (operatingMode < 0) {
2641 CLOGE("Invalid operating mode: %d", operatingMode);
2642 return BAD_VALUE;
2643 }
2644
2645 bool isConstrainedHighSpeed =
2646 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2647 operatingMode;
2648
2649 if (mOperatingMode != operatingMode) {
2650 mNeedConfig = true;
2651 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2652 mOperatingMode = operatingMode;
2653 }
2654
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002655 // In case called from configureStreams, abort queued input buffers not belonging to
2656 // any pending requests.
2657 if (mInputStream != NULL && notifyRequestThread) {
2658 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002659 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002660 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002661 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002662 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002663 if (res != OK) {
2664 // Exhausted acquiring all input buffers.
2665 break;
2666 }
2667
Emilian Peevf4816702020-04-03 15:44:51 -07002668 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002669 res = mInputStream->returnInputBuffer(inputBuffer);
2670 if (res != OK) {
2671 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2672 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2673 }
2674 }
2675 }
2676
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002677 if (!mNeedConfig) {
2678 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2679 return OK;
2680 }
2681
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002682 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002683 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002684 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2685 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002686 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002687 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002688 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002689 }
2690
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002691 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002692 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002694 mPreparerThread->pause();
2695
Emilian Peevf4816702020-04-03 15:44:51 -07002696 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002697 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002699 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002700
Emilian Peevf4816702020-04-03 15:44:51 -07002701 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002702 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002703 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002704
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002705
2706 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002707 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002708 inputStream = mInputStream->startConfiguration();
2709 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002710 CLOGE("Can't start input stream configuration");
2711 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002712 return INVALID_OPERATION;
2713 }
2714 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002715
2716 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717 }
2718
Shuzhen Wang99080502021-03-07 21:08:20 -08002719 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002720 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002721 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002722
2723 // Don't configure bidi streams twice, nor add them twice to the list
2724 if (mOutputStreams[i].get() ==
2725 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2726
2727 config.num_streams--;
2728 continue;
2729 }
2730
Emilian Peevf4816702020-04-03 15:44:51 -07002731 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002732 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002733 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002734 CLOGE("Can't start output stream configuration");
2735 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002736 return INVALID_OPERATION;
2737 }
2738 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002739
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002740 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002741 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2742 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002743 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2744 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002745 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2746 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002747 } else if (outputStream->data_space ==
2748 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2749 bufferSizes[k] = outputStream->width * outputStream->height;
2750 } else {
2751 ALOGW("%s: Blob dataSpace %d not supported",
2752 __FUNCTION__, outputStream->data_space);
2753 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002754 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002755
2756 if (mOutputStreams[i]->isMultiResolution()) {
2757 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2758 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2759 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2760 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002761
2762 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2763 composerSurfacePresent = true;
2764 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002765 }
2766
2767 config.streams = streams.editArray();
2768
2769 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002770 // max_buffers, usage, and priv fields, as well as data_space and format
2771 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002772
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002773 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002774 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002775 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002776
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002777 if (res == BAD_VALUE) {
2778 // HAL rejected this set of streams as unsupported, clean up config
2779 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002780 CLOGE("Set of requested inputs/outputs not supported by HAL");
2781 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002782 return BAD_VALUE;
2783 } else if (res != OK) {
2784 // Some other kind of error from configure_streams - this is not
2785 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002786 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2787 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002788 return res;
2789 }
2790
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002791 // Finish all stream configuration immediately.
2792 // TODO: Try to relax this later back to lazy completion, which should be
2793 // faster
2794
Igor Murashkin073f8572013-05-02 14:59:28 -07002795 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002796 bool streamReConfigured = false;
2797 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002798 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002799 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002800 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002801 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002802 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2803 return DEAD_OBJECT;
2804 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002805 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002806 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002807 if (streamReConfigured) {
2808 mInterface->onStreamReConfigured(mInputStream->getId());
2809 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002810 }
2811
2812 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002813 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002814 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002815 bool streamReConfigured = false;
2816 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002817 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002818 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002819 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002820 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002821 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2822 return DEAD_OBJECT;
2823 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002824 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002825 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002826 if (streamReConfigured) {
2827 mInterface->onStreamReConfigured(outputStream->getId());
2828 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002829 }
2830 }
2831
Emilian Peeve23f1d92021-09-20 14:56:01 -07002832 mRequestThread->setComposerSurface(composerSurfacePresent);
2833
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002834 // Request thread needs to know to avoid using repeat-last-settings protocol
2835 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002836 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002837 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2838 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002839 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002840
Zhijun He90f7c372016-08-16 16:19:43 -07002841 char value[PROPERTY_VALUE_MAX];
2842 property_get("camera.fifo.disable", value, "0");
2843 int32_t disableFifo = atoi(value);
2844 if (disableFifo != 1) {
2845 // Boost priority of request thread to SCHED_FIFO.
2846 pid_t requestThreadTid = mRequestThread->getTid();
2847 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002848 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002849 if (res != OK) {
2850 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2851 strerror(-res), res);
2852 } else {
2853 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2854 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002855 }
2856
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002857 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002858 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2859 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2860 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2861 sessionParams.unlock(newSessionParams);
2862 mSessionParams.unlock(currentSessionParams);
2863 if (updateSessionParams) {
2864 mSessionParams = sessionParams;
2865 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002866
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002867 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002868
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002870 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002871
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002872 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002873
Zhijun He0a210512014-07-24 13:45:15 -07002874 // tear down the deleted streams after configure streams.
2875 mDeletedStreams.clear();
2876
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002877 auto rc = mPreparerThread->resume();
2878 if (rc != OK) {
2879 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2880 return rc;
2881 }
2882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002884 mRequestBufferSM.onStreamsConfigured();
2885 }
2886
Cliff Wu3b268182021-07-06 15:44:43 +08002887 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002888 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002889 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002890 // configure the injection streams.
2891 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002892 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002893 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2894 res = mInjectionMethods->injectCamera(config, bufferSizes);
2895 if (res != OK) {
2896 ALOGE("Can't finish inject camera process!");
2897 return res;
2898 }
Cliff Wu3b268182021-07-06 15:44:43 +08002899 } else {
2900 // First run configureStreamsLocked() and then call injectCamera() case:
2901 // If the stream configuration has been completed and camera deive is active, but the
2902 // injection camera has not been injected yet, we need to store the stream configuration of
2903 // the internal camera (because the stream configuration of the injection camera is based
2904 // on the internal camera). When injecting occurs later, this configuration can be used by
2905 // the injection camera.
2906 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2907 " injection camera has not been injected yet.", __FUNCTION__);
2908 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002909 }
2910
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002911 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002912}
2913
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002914status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002915 ATRACE_CALL();
2916 status_t res;
2917
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002918 if (mFakeStreamId != NO_STREAM) {
2919 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002920 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002921 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002923 return INVALID_OPERATION;
2924 }
2925
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002926 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002927
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002928 sp<Camera3OutputStreamInterface> fakeStream =
2929 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002930
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002931 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002932 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002933 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002934 return res;
2935 }
2936
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002937 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002938 mNextStreamId++;
2939
2940 return OK;
2941}
2942
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002943status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002944 ATRACE_CALL();
2945 status_t res;
2946
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002947 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002948 if (mOutputStreams.size() == 1) return OK;
2949
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002950 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002951
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002952 // Ok, have a fake stream and there's at least one other output stream,
2953 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002954
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002955 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002956 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002957 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002958 return INVALID_OPERATION;
2959 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002960 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002961
2962 // Free up the stream endpoint so that it can be used by some other stream
2963 res = deletedStream->disconnect();
2964 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002965 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002966 // fall through since we want to still list the stream as deleted.
2967 }
2968 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002969 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002970
2971 return res;
2972}
2973
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002974void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002975 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002976 Mutex::Autolock l(mLock);
2977 va_list args;
2978 va_start(args, fmt);
2979
2980 setErrorStateLockedV(fmt, args);
2981
2982 va_end(args);
2983}
2984
2985void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002986 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002987 Mutex::Autolock l(mLock);
2988 setErrorStateLockedV(fmt, args);
2989}
2990
2991void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2992 va_list args;
2993 va_start(args, fmt);
2994
2995 setErrorStateLockedV(fmt, args);
2996
2997 va_end(args);
2998}
2999
3000void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003001 // Print out all error messages to log
3002 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003003 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003004
3005 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003006 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003007
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003008 mErrorCause = errorCause;
3009
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003010 if (mRequestThread != nullptr) {
3011 mRequestThread->setPaused(true);
3012 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003013 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003014
3015 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003016 sp<NotificationListener> listener = mListener.promote();
3017 if (listener != NULL) {
3018 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003019 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07003020 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003021 }
3022
3023 // Save stack trace. View by dumping it later.
3024 CameraTraces::saveTrace();
3025 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003026}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003027
3028/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003029 * In-flight request management
3030 */
3031
Jianing Weicb0652e2014-03-12 18:29:36 -07003032status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003033 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003034 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08003035 const std::set<std::set<String8>>& physicalCameraIds,
3036 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
3037 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003038 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003039 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003040 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003041
3042 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003043 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003044 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003045 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003046 if (res < 0) return res;
3047
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003048 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003049 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3050 // avoid a deadlock during reprocess requests.
3051 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003052 if (mStatusTracker != nullptr) {
3053 mStatusTracker->markComponentActive(mInFlightStatusId);
3054 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003055 }
3056
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003057 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003058 return OK;
3059}
3060
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003061void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003062 // Indicate idle inFlightMap to the status tracker
3063 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003064 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003065 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3066 // avoid a deadlock during reprocess requests.
3067 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003068 if (mStatusTracker != nullptr) {
3069 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3070 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003071 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003072 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003073}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003074
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003075void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003076 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003077 // something has likely gone wrong. This might still be legit only if application send in
3078 // a long burst of long exposure requests.
3079 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3080 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3081 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3082 mInFlightMap.size(), mExpectedInflightDuration);
3083 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3084 kInFlightWarnLimitHighSpeed) {
3085 CLOGW("In-flight list too large for high speed configuration: %zu,"
3086 "total inflight duration %" PRIu64,
3087 mInFlightMap.size(), mExpectedInflightDuration);
3088 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003089 }
3090}
3091
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003092void Camera3Device::onInflightMapFlushedLocked() {
3093 mExpectedInflightDuration = 0;
3094}
3095
3096void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003097 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003098 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3099 mInFlightMap.removeItemsAt(idx, 1);
3100
3101 onInflightEntryRemovedLocked(duration);
3102}
3103
3104
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003105void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003106 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003107 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003108 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003109 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003110 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003111 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003112
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003113 FlushInflightReqStates states {
3114 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003115 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003116
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003117 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003118}
3119
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003120CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003121 ALOGV("%s", __FUNCTION__);
3122
Igor Murashkin1e479c02013-09-06 16:55:14 -07003123 CameraMetadata retVal;
3124
3125 if (mRequestThread != NULL) {
3126 retVal = mRequestThread->getLatestRequest();
3127 }
3128
Igor Murashkin1e479c02013-09-06 16:55:14 -07003129 return retVal;
3130}
3131
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003132void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003133 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003134 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003135 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
3136 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003137
3138 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003139 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003140}
3141
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003142/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 * HalInterface inner class methods
3144 */
3145
Yifan Hongf79b5542017-04-11 14:44:25 -07003146Camera3Device::HalInterface::HalInterface(
3147 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003148 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003149 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003150 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003151 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003152 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003153 mIsReconfigurationQuerySupported(true),
3154 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003155 // Check with hardware service manager if we can downcast these interfaces
3156 // Somewhat expensive, so cache the results at startup
Emilian Peev2295df72021-11-12 18:14:10 -08003157 auto castResult_3_8 = device::V3_8::ICameraDeviceSession::castFrom(mHidlSession);
3158 if (castResult_3_8.isOk()) {
3159 mHidlSession_3_8 = castResult_3_8;
3160 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003161 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3162 if (castResult_3_7.isOk()) {
3163 mHidlSession_3_7 = castResult_3_7;
3164 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003165 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3166 if (castResult_3_6.isOk()) {
3167 mHidlSession_3_6 = castResult_3_6;
3168 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003169 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3170 if (castResult_3_5.isOk()) {
3171 mHidlSession_3_5 = castResult_3_5;
3172 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003173 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3174 if (castResult_3_4.isOk()) {
3175 mHidlSession_3_4 = castResult_3_4;
3176 }
3177 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3178 if (castResult_3_3.isOk()) {
3179 mHidlSession_3_3 = castResult_3_3;
3180 }
3181}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003182
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003183Camera3Device::HalInterface::HalInterface() :
3184 mUseHalBufManager(false),
3185 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003186
3187Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003188 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003189 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003190 mUseHalBufManager(other.mUseHalBufManager),
3191 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003192
3193bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003194 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003195}
3196
3197void Camera3Device::HalInterface::clear() {
Emilian Peev2295df72021-11-12 18:14:10 -08003198 mHidlSession_3_8.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003199 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003200 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003201 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003202 mHidlSession_3_4.clear();
3203 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003204 mHidlSession.clear();
3205}
3206
3207status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003208 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003209 /*out*/ camera_metadata_t **requestTemplate) {
3210 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3211 if (!valid()) return INVALID_OPERATION;
3212 status_t res = OK;
3213
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003215
3216 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003217 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003218 status = s;
3219 if (status == common::V1_0::Status::OK) {
3220 const camera_metadata *r =
3221 reinterpret_cast<const camera_metadata_t*>(request.data());
3222 size_t expectedSize = request.size();
3223 int ret = validate_camera_metadata_structure(r, &expectedSize);
3224 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3225 *requestTemplate = clone_camera_metadata(r);
3226 if (*requestTemplate == nullptr) {
3227 ALOGE("%s: Unable to clone camera metadata received from HAL",
3228 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003229 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003230 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003231 } else {
3232 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3233 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003234 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003235 }
3236 };
3237 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003238 RequestTemplate id;
3239 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003240 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003241 id = RequestTemplate::PREVIEW;
3242 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003243 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003244 id = RequestTemplate::STILL_CAPTURE;
3245 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003246 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003247 id = RequestTemplate::VIDEO_RECORD;
3248 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003249 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003250 id = RequestTemplate::VIDEO_SNAPSHOT;
3251 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003252 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003253 id = RequestTemplate::ZERO_SHUTTER_LAG;
3254 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003255 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003256 id = RequestTemplate::MANUAL;
3257 break;
3258 default:
3259 // Unknown template ID, or this HAL is too old to support it
3260 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003261 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003262 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003263
Emilian Peev31abd0a2017-05-11 18:37:46 +01003264 if (!err.isOk()) {
3265 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3266 res = DEAD_OBJECT;
3267 } else {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003268 res = HidlProviderInfo::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003269 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003270
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003271 return res;
3272}
3273
Emilian Peev4ec17882019-01-24 17:16:58 -08003274bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3275 CameraMetadata& newSessionParams) {
3276 // We do reconfiguration by default;
3277 bool ret = true;
3278 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3279 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3280 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3281 oldSessionParams.getAndLock());
3282 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3283 newSessionParams.getAndLock());
3284 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3285 get_camera_metadata_size(oldSessioMeta));
3286 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3287 get_camera_metadata_size(newSessioMeta));
3288 hardware::camera::common::V1_0::Status callStatus;
3289 bool required;
3290 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3291 bool requiredFlag) {
3292 callStatus = s;
3293 required = requiredFlag;
3294 };
3295 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3296 oldSessionParams.unlock(oldSessioMeta);
3297 newSessionParams.unlock(newSessioMeta);
3298 if (err.isOk()) {
3299 switch (callStatus) {
3300 case hardware::camera::common::V1_0::Status::OK:
3301 ret = required;
3302 break;
3303 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3304 mIsReconfigurationQuerySupported = false;
3305 ret = true;
3306 break;
3307 default:
3308 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3309 ret = true;
3310 }
3311 } else {
3312 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3313 ret = true;
3314 }
3315 }
3316
3317 return ret;
3318}
3319
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003320status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003321 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003322 ATRACE_NAME("CameraHal::configureStreams");
3323 if (!valid()) return INVALID_OPERATION;
3324 status_t res = OK;
3325
Shuzhen Wang83bff122020-11-20 15:51:39 -08003326 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3327 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3328 return BAD_VALUE;
3329 }
3330
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 // Convert stream config to HIDL
3332 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003333 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3334 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003335 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Emilian Peev2295df72021-11-12 18:14:10 -08003336 device::V3_8::StreamConfiguration requestedConfiguration3_8;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003337 requestedConfiguration3_2.streams.resize(config->num_streams);
3338 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003339 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev2295df72021-11-12 18:14:10 -08003340 requestedConfiguration3_8.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003341 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003342 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3343 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003344 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peev2295df72021-11-12 18:14:10 -08003345 device::V3_8::Stream &dst3_8 = requestedConfiguration3_8.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003346 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003347
Emilian Peev31abd0a2017-05-11 18:37:46 +01003348 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3349 cam3stream->setBufferFreedListener(this);
3350 int streamId = cam3stream->getId();
3351 StreamType streamType;
3352 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003353 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003354 streamType = StreamType::OUTPUT;
3355 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003356 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003357 streamType = StreamType::INPUT;
3358 break;
3359 default:
3360 ALOGE("%s: Stream %d: Unsupported stream type %d",
3361 __FUNCTION__, streamId, config->streams[i]->stream_type);
3362 return BAD_VALUE;
3363 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003364 dst3_2.id = streamId;
3365 dst3_2.streamType = streamType;
3366 dst3_2.width = src->width;
3367 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003368 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003369 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003370 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003371 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003372 if (mHidlSession_3_5 != nullptr) {
3373 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3374 cam3stream->getOriginalFormat() : src->format);
3375 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3376 cam3stream->getOriginalDataSpace() : src->data_space);
3377 } else {
3378 dst3_2.format = mapToPixelFormat(src->format);
3379 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3380 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003381 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003382 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003383 if (src->physical_camera_id != nullptr) {
3384 dst3_4.physicalCameraId = src->physical_camera_id;
3385 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003386 dst3_7.v3_4 = dst3_4;
3387 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003388 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3389 size_t j = 0;
3390 for (int mode : src->sensor_pixel_modes_used) {
3391 dst3_7.sensorPixelModesUsed[j++] =
3392 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3393 }
Emilian Peev2295df72021-11-12 18:14:10 -08003394 if ((src->dynamic_range_profile !=
3395 ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD) &&
3396 (mHidlSession_3_8 == nullptr)) {
3397 ALOGE("%s: Camera device doesn't support non-standard dynamic range profiles: %d",
3398 __FUNCTION__, src->dynamic_range_profile);
3399 return BAD_VALUE;
3400 }
3401 dst3_8.v3_7 = dst3_7;
3402 dst3_8.dynamicRangeProfile = mapToHidlDynamicProfile(src->dynamic_range_profile);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003403 activeStreams.insert(streamId);
3404 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003405 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003406 }
3407 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003408 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003409
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003410 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003411 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003412 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003413 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003414 if (res != OK) {
3415 return res;
3416 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003417 requestedConfiguration3_2.operationMode = operationMode;
3418 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003419 requestedConfiguration3_7.operationMode = operationMode;
3420 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003421 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003422 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003423 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003424 requestedConfiguration3_7.operationMode = operationMode;
3425 requestedConfiguration3_7.sessionParams.setToExternal(
3426 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003427 sessionParamSize);
Emilian Peev2295df72021-11-12 18:14:10 -08003428 requestedConfiguration3_8.operationMode = operationMode;
3429 requestedConfiguration3_8.sessionParams.setToExternal(
3430 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3431 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003432
Emilian Peev31abd0a2017-05-11 18:37:46 +01003433 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003434 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003435 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003436 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003437 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003438
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003439 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003440 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3441 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003442 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003443 };
3444
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003445 auto configStream36Cb = [&status, &finalConfiguration3_6]
3446 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3447 finalConfiguration3_6 = halConfiguration;
3448 status = s;
3449 };
3450
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003451 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3452 (hardware::Return<void>& err) -> status_t {
3453 if (!err.isOk()) {
3454 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3455 return DEAD_OBJECT;
3456 }
3457 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3458 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3459 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3460 }
3461 return OK;
3462 };
3463
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003464 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3465 (hardware::Return<void>& err) -> status_t {
3466 if (!err.isOk()) {
3467 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3468 return DEAD_OBJECT;
3469 }
3470 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3471 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3472 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3473 }
3474 return OK;
3475 };
3476
Shuzhen Wang92653952019-05-07 15:11:43 -07003477 // See which version of HAL we have
Emilian Peev2295df72021-11-12 18:14:10 -08003478 if (mHidlSession_3_8 != nullptr) {
3479 ALOGV("%s: v3.8 device found", __FUNCTION__);
3480 requestedConfiguration3_8.streamConfigCounter = mNextStreamConfigCounter++;
3481 requestedConfiguration3_8.multiResolutionInputImage = config->input_is_multi_resolution;
3482 auto err = mHidlSession_3_8->configureStreams_3_8(requestedConfiguration3_8,
3483 configStream36Cb);
3484 res = postprocConfigStream36(err);
3485 if (res != OK) {
3486 return res;
3487 }
3488 } else if (mHidlSession_3_7 != nullptr) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003489 ALOGV("%s: v3.7 device found", __FUNCTION__);
3490 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3491 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3492 auto err = mHidlSession_3_7->configureStreams_3_7(
3493 requestedConfiguration3_7, configStream36Cb);
3494 res = postprocConfigStream36(err);
3495 if (res != OK) {
3496 return res;
3497 }
3498 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003499 ALOGV("%s: v3.6 device found", __FUNCTION__);
3500 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3501 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3502 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3503 auto err = mHidlSession_3_6->configureStreams_3_6(
3504 requestedConfiguration3_5, configStream36Cb);
3505 res = postprocConfigStream36(err);
3506 if (res != OK) {
3507 return res;
3508 }
3509 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003510 ALOGV("%s: v3.5 device found", __FUNCTION__);
3511 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3512 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3513 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3514 auto err = mHidlSession_3_5->configureStreams_3_5(
3515 requestedConfiguration3_5, configStream34Cb);
3516 res = postprocConfigStream34(err);
3517 if (res != OK) {
3518 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003519 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003520 } else if (mHidlSession_3_4 != nullptr) {
3521 // We do; use v3.4 for the call
3522 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003523 auto err = mHidlSession_3_4->configureStreams_3_4(
3524 requestedConfiguration3_4, configStream34Cb);
3525 res = postprocConfigStream34(err);
3526 if (res != OK) {
3527 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003528 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003529 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003530 // We do; use v3.3 for the call
3531 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003532 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003533 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003534 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003535 finalConfiguration = halConfiguration;
3536 status = s;
3537 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003538 if (!err.isOk()) {
3539 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3540 return DEAD_OBJECT;
3541 }
3542 } else {
3543 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3544 ALOGV("%s: v3.2 device found", __FUNCTION__);
3545 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003546 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003547 [&status, &finalConfiguration_3_2]
3548 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3549 finalConfiguration_3_2 = halConfiguration;
3550 status = s;
3551 });
3552 if (!err.isOk()) {
3553 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3554 return DEAD_OBJECT;
3555 }
3556 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3557 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3558 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3559 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003560 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003561 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003562 }
3563
3564 if (status != common::V1_0::Status::OK ) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003565 return HidlProviderInfo::mapToStatusT(status);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003566 }
3567
3568 // And convert output stream configuration from HIDL
3569
3570 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003571 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003572 int streamId = Camera3Stream::cast(dst)->getId();
3573
3574 // Start scan at i, with the assumption that the stream order matches
3575 size_t realIdx = i;
3576 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003577 size_t halStreamCount = finalConfiguration.streams.size();
3578 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003579 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003580 found = true;
3581 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003582 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003583 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003584 }
3585 if (!found) {
3586 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3587 __FUNCTION__, streamId);
3588 return INVALID_OPERATION;
3589 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003590 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003591 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003592
Emilian Peev710c1422017-08-30 11:19:38 +01003593 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003594 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3595 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3596
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003597 if (mHidlSession_3_6 != nullptr) {
3598 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3599 }
3600
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003601 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003602 dstStream->setFormatOverride(false);
3603 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003604 if (dst->format != overrideFormat) {
3605 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3606 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003607 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003608 if (dst->data_space != overrideDataSpace) {
3609 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3610 streamId, dst->format);
3611 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003612 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003613 bool needFormatOverride =
3614 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3615 bool needDataspaceOverride =
3616 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003617 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003618 dstStream->setFormatOverride(needFormatOverride);
3619 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003620 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003621 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003622 }
3623
Emilian Peevf4816702020-04-03 15:44:51 -07003624 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003625 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003626 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003627 __FUNCTION__, streamId);
3628 return INVALID_OPERATION;
3629 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003630 dstStream->setUsage(
3631 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003632 } else {
3633 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003634 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003635 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3636 __FUNCTION__, streamId);
3637 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003638 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003639 dstStream->setUsage(
3640 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003641 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003642 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003643 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003644
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003645 return res;
3646}
3647
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003648status_t Camera3Device::HalInterface::configureInjectedStreams(
3649 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3650 const std::vector<uint32_t>& bufferSizes,
3651 const CameraMetadata& cameraCharacteristics) {
3652 ATRACE_NAME("InjectionCameraHal::configureStreams");
3653 if (!valid()) return INVALID_OPERATION;
3654 status_t res = OK;
3655
3656 if (config->input_is_multi_resolution) {
3657 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3658 "stream", __FUNCTION__);
3659 return BAD_VALUE;
3660 }
3661
3662 // Convert stream config to HIDL
3663 std::set<int> activeStreams;
3664 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3665 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3666 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3667 requestedConfiguration3_2.streams.resize(config->num_streams);
3668 requestedConfiguration3_4.streams.resize(config->num_streams);
3669 requestedConfiguration3_7.streams.resize(config->num_streams);
3670 for (size_t i = 0; i < config->num_streams; i++) {
3671 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3672 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3673 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3674 camera3::camera_stream_t* src = config->streams[i];
3675
3676 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3677 cam3stream->setBufferFreedListener(this);
3678 int streamId = cam3stream->getId();
3679 StreamType streamType;
3680 switch (src->stream_type) {
3681 case CAMERA_STREAM_OUTPUT:
3682 streamType = StreamType::OUTPUT;
3683 break;
3684 case CAMERA_STREAM_INPUT:
3685 streamType = StreamType::INPUT;
3686 break;
3687 default:
3688 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3689 streamId, config->streams[i]->stream_type);
3690 return BAD_VALUE;
3691 }
3692 dst3_2.id = streamId;
3693 dst3_2.streamType = streamType;
3694 dst3_2.width = src->width;
3695 dst3_2.height = src->height;
3696 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3697 dst3_2.rotation =
3698 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3699 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3700 // to HAL are original, not the overridden ones.
3701 if (mHidlSession_3_5 != nullptr) {
3702 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3703 ? cam3stream->getOriginalFormat()
3704 : src->format);
3705 dst3_2.dataSpace =
3706 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3707 ? cam3stream->getOriginalDataSpace()
3708 : src->data_space);
3709 } else {
3710 dst3_2.format = mapToPixelFormat(src->format);
3711 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3712 }
3713 dst3_4.v3_2 = dst3_2;
3714 dst3_4.bufferSize = bufferSizes[i];
3715 if (src->physical_camera_id != nullptr) {
3716 dst3_4.physicalCameraId = src->physical_camera_id;
3717 }
3718 dst3_7.v3_4 = dst3_4;
3719 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3720 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3721 size_t j = 0;
3722 for (int mode : src->sensor_pixel_modes_used) {
3723 dst3_7.sensorPixelModesUsed[j++] =
3724 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3725 }
3726 activeStreams.insert(streamId);
3727 // Create Buffer ID map if necessary
3728 mBufferRecords.tryCreateBufferCache(streamId);
3729 }
3730 // remove BufferIdMap for deleted streams
3731 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3732
3733 StreamConfigurationMode operationMode;
3734 res = mapToStreamConfigurationMode(
3735 (camera_stream_configuration_mode_t)config->operation_mode,
3736 /*out*/ &operationMode);
3737 if (res != OK) {
3738 return res;
3739 }
3740 requestedConfiguration3_7.operationMode = operationMode;
3741 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3742 requestedConfiguration3_7.operationMode = operationMode;
3743 requestedConfiguration3_7.sessionParams.setToExternal(
3744 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3745 sessionParamSize);
3746
3747 // See which version of HAL we have
3748 if (mHidlSession_3_7 != nullptr) {
3749 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3750 requestedConfiguration3_7.multiResolutionInputImage =
3751 config->input_is_multi_resolution;
3752
3753 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3754 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3755 hidlChars.setToExternal(
3756 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3757 get_camera_metadata_size(rawMetadata));
3758 cameraCharacteristics.unlock(rawMetadata);
3759
3760 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3761 hidlInjectionSession_3_7;
3762 auto castInjectionResult_3_7 =
3763 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3764 if (castInjectionResult_3_7.isOk()) {
3765 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3766 } else {
3767 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3768 castInjectionResult_3_7.description().c_str());
3769 return DEAD_OBJECT;
3770 }
3771
3772 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3773 requestedConfiguration3_7, hidlChars);
3774 if (!err.isOk()) {
3775 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3776 err.description().c_str());
3777 return DEAD_OBJECT;
3778 }
3779 } else {
3780 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3781 "session is 3.7", __FUNCTION__);
3782 return DEAD_OBJECT;
3783 }
3784
3785 return res;
3786}
3787
Emilian Peevf4816702020-04-03 15:44:51 -07003788status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003789 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003790 /*out*/std::vector<native_handle_t*>* handlesCreated,
3791 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003792 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003793 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3794 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3795 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003796 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003797 }
3798
3799 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003800
3801 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003802
3803 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003804 if (request->input_buffer != nullptr) {
3805 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3806 buffer_handle_t buf = *(request->input_buffer->buffer);
3807 auto pair = getBufferId(buf, streamId);
3808 bool isNewBuffer = pair.first;
3809 uint64_t bufferId = pair.second;
3810 captureRequest->inputBuffer.streamId = streamId;
3811 captureRequest->inputBuffer.bufferId = bufferId;
3812 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3813 captureRequest->inputBuffer.status = BufferStatus::OK;
3814 native_handle_t *acquireFence = nullptr;
3815 if (request->input_buffer->acquire_fence != -1) {
3816 acquireFence = native_handle_create(1,0);
3817 acquireFence->data[0] = request->input_buffer->acquire_fence;
3818 handlesCreated->push_back(acquireFence);
3819 }
3820 captureRequest->inputBuffer.acquireFence = acquireFence;
3821 captureRequest->inputBuffer.releaseFence = nullptr;
3822
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003823 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003824 request->input_buffer->buffer);
3825 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003826 } else {
3827 captureRequest->inputBuffer.streamId = -1;
3828 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3829 }
3830
3831 captureRequest->outputBuffers.resize(request->num_output_buffers);
3832 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003833 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003834 StreamBuffer &dst = captureRequest->outputBuffers[i];
3835 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003836 if (src->buffer != nullptr) {
3837 buffer_handle_t buf = *(src->buffer);
3838 auto pair = getBufferId(buf, streamId);
3839 bool isNewBuffer = pair.first;
3840 dst.bufferId = pair.second;
3841 dst.buffer = isNewBuffer ? buf : nullptr;
3842 native_handle_t *acquireFence = nullptr;
3843 if (src->acquire_fence != -1) {
3844 acquireFence = native_handle_create(1,0);
3845 acquireFence->data[0] = src->acquire_fence;
3846 handlesCreated->push_back(acquireFence);
3847 }
3848 dst.acquireFence = acquireFence;
3849 } else if (mUseHalBufManager) {
3850 // HAL buffer management path
3851 dst.bufferId = BUFFER_ID_NO_BUFFER;
3852 dst.buffer = nullptr;
3853 dst.acquireFence = nullptr;
3854 } else {
3855 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3856 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003857 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003858 dst.streamId = streamId;
3859 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003860 dst.releaseFence = nullptr;
3861
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003862 // Output buffers are empty when using HAL buffer manager
3863 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003864 mBufferRecords.pushInflightBuffer(
3865 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003866 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003867 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003868 }
3869 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003870 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003871}
3872
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003873void Camera3Device::HalInterface::cleanupNativeHandles(
3874 std::vector<native_handle_t*> *handles, bool closeFd) {
3875 if (handles == nullptr) {
3876 return;
3877 }
3878 if (closeFd) {
3879 for (auto& handle : *handles) {
3880 native_handle_close(handle);
3881 }
3882 }
3883 for (auto& handle : *handles) {
3884 native_handle_delete(handle);
3885 }
3886 handles->clear();
3887 return;
3888}
3889
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003890status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003891 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003892 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3893 if (!valid()) return INVALID_OPERATION;
3894
Emilian Peevaebbe412018-01-15 13:53:24 +00003895 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003896 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3897 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3898 if (castResult_3_7.isOk()) {
3899 hidlSession_3_7 = castResult_3_7;
3900 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003901 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3902 if (castResult_3_4.isOk()) {
3903 hidlSession_3_4 = castResult_3_4;
3904 }
3905
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003906 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003907 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003908 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003909 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003910 if (hidlSession_3_7 != nullptr) {
3911 captureRequests_3_7.resize(batchSize);
3912 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003913 captureRequests_3_4.resize(batchSize);
3914 } else {
3915 captureRequests.resize(batchSize);
3916 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003917 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003918 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003919
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003920 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003921 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003922 if (hidlSession_3_7 != nullptr) {
3923 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3924 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3925 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003926 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003927 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003928 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003929 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3930 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003931 }
3932 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003933 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003934 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003935 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003936 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003937 }
3938
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003939 std::vector<device::V3_2::BufferCache> cachesToRemove;
3940 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003941 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003942 for (auto& pair : mFreedBuffers) {
3943 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003944 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003945 cachesToRemove.push_back({pair.first, pair.second});
3946 }
3947 }
3948 mFreedBuffers.clear();
3949 }
3950
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003951 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3952 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003953
3954 // Write metadata to FMQ.
3955 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003956 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003957 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003958 if (hidlSession_3_7 != nullptr) {
3959 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3960 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003961 captureRequest = &captureRequests_3_4[i].v3_2;
3962 } else {
3963 captureRequest = &captureRequests[i];
3964 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003965
3966 if (request->settings != nullptr) {
3967 size_t settingsSize = get_camera_metadata_size(request->settings);
3968 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3969 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3970 captureRequest->settings.resize(0);
3971 captureRequest->fmqSettingsSize = settingsSize;
3972 } else {
3973 if (mRequestMetadataQueue != nullptr) {
3974 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3975 }
3976 captureRequest->settings.setToExternal(
3977 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3978 get_camera_metadata_size(request->settings));
3979 captureRequest->fmqSettingsSize = 0u;
3980 }
3981 } else {
3982 // A null request settings maps to a size-0 CameraMetadata
3983 captureRequest->settings.resize(0);
3984 captureRequest->fmqSettingsSize = 0u;
3985 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003986
Shuzhen Wang83bff122020-11-20 15:51:39 -08003987 // hidl session 3.7 specific handling.
3988 if (hidlSession_3_7 != nullptr) {
3989 captureRequests_3_7[i].inputWidth = request->input_width;
3990 captureRequests_3_7[i].inputHeight = request->input_height;
3991 }
3992
3993 // hidl session 3.7 and 3.4 specific handling.
3994 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3995 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3996 (hidlSession_3_7 != nullptr) ?
3997 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3998 captureRequests_3_4[i].physicalCameraSettings;
3999 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00004000 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004001 if (request->physcam_settings != nullptr) {
4002 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4003 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4004 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4005 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004006 physicalCameraSettings[j].settings.resize(0);
4007 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00004008 } else {
4009 if (mRequestMetadataQueue != nullptr) {
4010 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4011 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08004012 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00004013 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4014 request->physcam_settings[j])),
4015 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08004016 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004017 }
Emilian Peev00420d22018-02-05 21:33:13 +00004018 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08004019 physicalCameraSettings[j].fmqSettingsSize = 0u;
4020 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004021 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08004022 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00004023 }
4024 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004025 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004026
4027 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004028 auto resultCallback =
4029 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4030 status = s;
4031 *numRequestProcessed = n;
4032 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08004033 if (hidlSession_3_7 != nullptr) {
4034 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
4035 resultCallback);
4036 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004037 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004038 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004039 } else {
4040 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004041 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004042 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004043 if (!err.isOk()) {
4044 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004045 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004046 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004047
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004048 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4049 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4050 __FUNCTION__, *numRequestProcessed, batchSize);
4051 status = common::V1_0::Status::INTERNAL_ERROR;
4052 }
4053
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07004054 res = HidlProviderInfo::mapToStatusT(status);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004055 if (res == OK) {
4056 if (mHidlSession->isRemote()) {
4057 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4058 // sent to camera HAL processes)
4059 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4060 } else {
4061 // In passthrough mode the FDs are now owned by HAL
4062 cleanupNativeHandles(&handlesCreated);
4063 }
4064 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004065 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004066 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004067 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004068 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004069}
4070
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004071status_t Camera3Device::HalInterface::flush() {
4072 ATRACE_NAME("CameraHal::flush");
4073 if (!valid()) return INVALID_OPERATION;
4074 status_t res = OK;
4075
Emilian Peev31abd0a2017-05-11 18:37:46 +01004076 auto err = mHidlSession->flush();
4077 if (!err.isOk()) {
4078 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4079 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004080 } else {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07004081 res = HidlProviderInfo::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004082 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004083
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004084 return res;
4085}
4086
Emilian Peev31abd0a2017-05-11 18:37:46 +01004087status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004088 ATRACE_NAME("CameraHal::dump");
4089 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004090
Emilian Peev31abd0a2017-05-11 18:37:46 +01004091 // Handled by CameraProviderManager::dump
4092
4093 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004094}
4095
Emilian Peev2295df72021-11-12 18:14:10 -08004096status_t Camera3Device::HalInterface::repeatingRequestEnd(uint32_t frameNumber,
4097 hardware::hidl_vec<int32_t> streamIds) {
4098 ATRACE_NAME("CameraHal::repeatingRequestEnd");
4099 if (!valid()) return INVALID_OPERATION;
4100
4101 if (mHidlSession_3_8.get() != nullptr) {
4102 mHidlSession_3_8->repeatingRequestEnd(frameNumber, streamIds);
4103 }
4104
4105 return OK;
4106}
4107
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004108status_t Camera3Device::HalInterface::close() {
4109 ATRACE_NAME("CameraHal::close()");
4110 if (!valid()) return INVALID_OPERATION;
4111 status_t res = OK;
4112
Emilian Peev31abd0a2017-05-11 18:37:46 +01004113 auto err = mHidlSession->close();
4114 // Interface will be dead shortly anyway, so don't log errors
4115 if (!err.isOk()) {
4116 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004119 return res;
4120}
4121
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004122void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4123 ATRACE_NAME("CameraHal::signalPipelineDrain");
4124 if (!valid() || mHidlSession_3_5 == nullptr) {
4125 ALOGE("%s called on invalid camera!", __FUNCTION__);
4126 return;
4127 }
4128
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004129 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004130 if (!err.isOk()) {
4131 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4132 return;
4133 }
4134}
4135
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004136status_t Camera3Device::HalInterface::switchToOffline(
4137 const std::vector<int32_t>& streamsToKeep,
4138 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004139 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4140 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004141 ATRACE_NAME("CameraHal::switchToOffline");
4142 if (!valid() || mHidlSession_3_6 == nullptr) {
4143 ALOGE("%s called on invalid camera!", __FUNCTION__);
4144 return INVALID_OPERATION;
4145 }
4146
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004147 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4148 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004149 return INVALID_OPERATION;
4150 }
4151
4152 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004153 auto resultCallback =
4154 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4155 status = s;
4156 *offlineSessionInfo = info;
4157 *offlineSession = session;
4158 };
4159 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4160
4161 if (!err.isOk()) {
4162 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4163 return DEAD_OBJECT;
4164 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004165
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07004166 status_t ret = HidlProviderInfo::mapToStatusT(status);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004167 if (ret != OK) {
4168 return ret;
4169 }
4170
4171 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4172 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4173 // returns from switchToOffline.
4174
4175
4176 // Validate buffer caches
4177 std::vector<int32_t> streams;
4178 streams.reserve(offlineSessionInfo->offlineStreams.size());
4179 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4180 int32_t id = offlineStream.id;
4181 streams.push_back(id);
4182 // Verify buffer caches
4183 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4184 offlineStream.circulatingBufferIds.end());
4185 if (!verifyBufferIds(id, bufIds)) {
4186 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4187 return UNKNOWN_ERROR;
4188 }
4189 }
4190
4191 // Move buffer records
4192 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4193 bufferRecords->takeInflightBufferMap(mBufferRecords);
4194 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4195 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004196}
4197
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004198void Camera3Device::HalInterface::getInflightBufferKeys(
4199 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004200 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004201 return;
4202}
4203
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004204void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4205 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004206 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004207 return;
4208}
4209
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004210bool Camera3Device::HalInterface::verifyBufferIds(
4211 int32_t streamId, std::vector<uint64_t>& bufIds) {
4212 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004213}
4214
4215status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004216 int32_t frameNumber, int32_t streamId,
4217 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004218 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004219}
4220
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004221status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004222 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004223 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004224}
4225
4226// Find and pop a buffer_handle_t based on bufferId
4227status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004228 uint64_t bufferId,
4229 /*out*/ buffer_handle_t** buffer,
4230 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004231 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004232}
4233
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004234std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4235 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004236 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004237}
4238
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07004239uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
4240 const native_handle_t* handle) {
4241 return mBufferRecords.removeOneBufferCache(streamId, handle);
4242}
4243
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004244void Camera3Device::HalInterface::onBufferFreed(
4245 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004246 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4247 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4248 if (bufferId != BUFFER_ID_NO_BUFFER) {
4249 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004250 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004251}
4252
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004253void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004254 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4255 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4256 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004257 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4258 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004259}
4260
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004261/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004262 * RequestThread inner class methods
4263 */
4264
4265Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004266 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004267 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004268 bool useHalBufManager,
4269 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004270 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004271 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004272 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004273 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004274 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004275 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004276 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004277 mReconfigured(false),
4278 mDoPause(false),
4279 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004280 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004281 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004282 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004283 mCurrentAfTriggerId(0),
4284 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004285 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07004286 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004287 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004288 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004289 mRepeatingLastFrameNumber(
4290 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004291 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004292 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004293 mRequestLatency(kRequestLatencyBinSize),
4294 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004295 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004296 mUseHalBufManager(useHalBufManager),
4297 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004298 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299}
4300
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004301Camera3Device::RequestThread::~RequestThread() {}
4302
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004303void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004304 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004305 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004306 Mutex::Autolock l(mRequestLock);
4307 mListener = listener;
4308}
4309
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004310void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004311 const CameraMetadata& sessionParams,
4312 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004313 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 Mutex::Autolock l(mRequestLock);
4315 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004316 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004317 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004318 // Prepare video stream for high speed recording.
4319 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004320 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321}
4322
Jianing Wei90e59c92014-03-12 18:29:36 -07004323status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004324 List<sp<CaptureRequest> > &requests,
4325 /*out*/
4326 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004327 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004328 Mutex::Autolock l(mRequestLock);
4329 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4330 ++it) {
4331 mRequestQueue.push_back(*it);
4332 }
4333
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004334 if (lastFrameNumber != NULL) {
4335 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4336 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4337 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4338 *lastFrameNumber);
4339 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004340
Jianing Wei90e59c92014-03-12 18:29:36 -07004341 unpauseForNewRequests();
4342
4343 return OK;
4344}
4345
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004346
4347status_t Camera3Device::RequestThread::queueTrigger(
4348 RequestTrigger trigger[],
4349 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004350 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004351 Mutex::Autolock l(mTriggerMutex);
4352 status_t ret;
4353
4354 for (size_t i = 0; i < count; ++i) {
4355 ret = queueTriggerLocked(trigger[i]);
4356
4357 if (ret != OK) {
4358 return ret;
4359 }
4360 }
4361
4362 return OK;
4363}
4364
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004365const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4366 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004367 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004368 if (d != nullptr) return d->mId;
4369 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004370}
4371
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004372status_t Camera3Device::RequestThread::queueTriggerLocked(
4373 RequestTrigger trigger) {
4374
4375 uint32_t tag = trigger.metadataTag;
4376 ssize_t index = mTriggerMap.indexOfKey(tag);
4377
4378 switch (trigger.getTagType()) {
4379 case TYPE_BYTE:
4380 // fall-through
4381 case TYPE_INT32:
4382 break;
4383 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004384 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4385 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004386 return INVALID_OPERATION;
4387 }
4388
4389 /**
4390 * Collect only the latest trigger, since we only have 1 field
4391 * in the request settings per trigger tag, and can't send more than 1
4392 * trigger per request.
4393 */
4394 if (index != NAME_NOT_FOUND) {
4395 mTriggerMap.editValueAt(index) = trigger;
4396 } else {
4397 mTriggerMap.add(tag, trigger);
4398 }
4399
4400 return OK;
4401}
4402
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004403status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004404 const RequestList &requests,
4405 /*out*/
4406 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004407 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004409 if (lastFrameNumber != NULL) {
4410 *lastFrameNumber = mRepeatingLastFrameNumber;
4411 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004412 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004413 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004414 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4415 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004416
4417 unpauseForNewRequests();
4418
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004419 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004420 return OK;
4421}
4422
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004423bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004424 if (mRepeatingRequests.empty()) {
4425 return false;
4426 }
4427 int32_t requestId = requestIn->mResultExtras.requestId;
4428 const RequestList &repeatRequests = mRepeatingRequests;
4429 // All repeating requests are guaranteed to have same id so only check first quest
4430 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4431 return (firstRequest->mResultExtras.requestId == requestId);
4432}
4433
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004434status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004435 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004436 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004437 return clearRepeatingRequestsLocked(lastFrameNumber);
4438
4439}
4440
4441status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08004442 std::vector<int32_t> streamIds;
4443 for (const auto& request : mRepeatingRequests) {
4444 for (const auto& stream : request->mOutputStreams) {
4445 streamIds.push_back(stream->getId());
4446 }
4447 }
4448
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004449 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004450 if (lastFrameNumber != NULL) {
4451 *lastFrameNumber = mRepeatingLastFrameNumber;
4452 }
Emilian Peev2295df72021-11-12 18:14:10 -08004453
4454 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
4455
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004456 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457 return OK;
4458}
4459
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004460status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004461 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004462 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004463 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004464 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004465
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004466 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004467
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004468 // Send errors for all requests pending in the request queue, including
4469 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004470 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004471 if (listener != NULL) {
4472 for (RequestList::iterator it = mRequestQueue.begin();
4473 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004474 // Abort the input buffers for reprocess requests.
4475 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004476 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004477 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004478 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004479 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004480 if (res != OK) {
4481 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4482 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4483 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004484 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004485 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4486 if (res != OK) {
4487 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4488 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4489 }
4490 }
4491 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004492 // Set the frame number this request would have had, if it
4493 // had been submitted; this frame number will not be reused.
4494 // The requestId and burstId fields were set when the request was
4495 // submitted originally (in convertMetadataListToRequestListLocked)
4496 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004497 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004498 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004499 }
4500 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004501 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004502
4503 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004504 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004505 if (lastFrameNumber != NULL) {
4506 *lastFrameNumber = mRepeatingLastFrameNumber;
4507 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004508 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004509 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004510 return OK;
4511}
4512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004513status_t Camera3Device::RequestThread::flush() {
4514 ATRACE_CALL();
4515 Mutex::Autolock l(mFlushLock);
4516
Emilian Peev08dd2452017-04-06 16:55:14 +01004517 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004518}
4519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004520void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004521 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004522 Mutex::Autolock l(mPauseLock);
4523 mDoPause = paused;
4524 mDoPauseSignal.signal();
4525}
4526
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004527status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4528 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004529 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004530 Mutex::Autolock l(mLatestRequestMutex);
4531 status_t res;
4532 while (mLatestRequestId != requestId) {
4533 nsecs_t startTime = systemTime();
4534
4535 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4536 if (res != OK) return res;
4537
4538 timeout -= (systemTime() - startTime);
4539 }
4540
4541 return OK;
4542}
4543
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004544void Camera3Device::RequestThread::requestExit() {
4545 // Call parent to set up shutdown
4546 Thread::requestExit();
4547 // The exit from any possible waits
4548 mDoPauseSignal.signal();
4549 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004550
4551 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4552 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004553}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004554
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004555void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004556 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004557 bool surfaceAbandoned = false;
4558 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004559 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004560 {
4561 Mutex::Autolock l(mRequestLock);
4562 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4563 // repeating requests.
4564 for (const auto& request : mRepeatingRequests) {
4565 for (const auto& s : request->mOutputStreams) {
4566 if (s->isAbandoned()) {
4567 surfaceAbandoned = true;
4568 clearRepeatingRequestsLocked(&lastFrameNumber);
4569 break;
4570 }
4571 }
4572 if (surfaceAbandoned) {
4573 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004574 }
4575 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004576 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004577 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004578
4579 if (listener != NULL && surfaceAbandoned) {
4580 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004581 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004582}
4583
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004584bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004585 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004586 status_t res;
4587 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004588 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004589 uint32_t numRequestProcessed = 0;
4590 for (size_t i = 0; i < batchSize; i++) {
4591 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004592 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004593 }
4594
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004595 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4596
4597 bool triggerRemoveFailed = false;
4598 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4599 for (size_t i = 0; i < numRequestProcessed; i++) {
4600 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4601 nextRequest.submitted = true;
4602
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004603 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004604
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004605 if (!triggerRemoveFailed) {
4606 // Remove any previously queued triggers (after unlock)
4607 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4608 if (removeTriggerRes != OK) {
4609 triggerRemoveFailed = true;
4610 triggerFailedRequest = nextRequest;
4611 }
4612 }
4613 }
4614
4615 if (triggerRemoveFailed) {
4616 SET_ERR("RequestThread: Unable to remove triggers "
4617 "(capture request %d, HAL device: %s (%d)",
4618 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4619 cleanUpFailedRequests(/*sendRequestError*/ false);
4620 return false;
4621 }
4622
4623 if (res != OK) {
4624 // Should only get a failure here for malformed requests or device-level
4625 // errors, so consider all errors fatal. Bad metadata failures should
4626 // come through notify.
4627 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4628 mNextRequests[numRequestProcessed].halRequest.frame_number,
4629 strerror(-res), res);
4630 cleanUpFailedRequests(/*sendRequestError*/ false);
4631 return false;
4632 }
4633 return true;
4634}
4635
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004636nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4637 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4638 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4639 find_camera_metadata_ro_entry(request,
4640 ANDROID_CONTROL_AE_MODE,
4641 &e);
4642 if (e.count == 0) return maxExpectedDuration;
4643
4644 switch (e.data.u8[0]) {
4645 case ANDROID_CONTROL_AE_MODE_OFF:
4646 find_camera_metadata_ro_entry(request,
4647 ANDROID_SENSOR_EXPOSURE_TIME,
4648 &e);
4649 if (e.count > 0) {
4650 maxExpectedDuration = e.data.i64[0];
4651 }
4652 find_camera_metadata_ro_entry(request,
4653 ANDROID_SENSOR_FRAME_DURATION,
4654 &e);
4655 if (e.count > 0) {
4656 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4657 }
4658 break;
4659 default:
4660 find_camera_metadata_ro_entry(request,
4661 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4662 &e);
4663 if (e.count > 1) {
4664 maxExpectedDuration = 1e9 / e.data.u8[0];
4665 }
4666 break;
4667 }
4668
4669 return maxExpectedDuration;
4670}
4671
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004672bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4673 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4674 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4675 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4676 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4677 return true;
4678 }
4679
4680 return false;
4681}
4682
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004683void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4684 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004685 camera_capture_request_t& halRequest = nextRequest.halRequest;
4686 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004687 Mutex::Autolock al(mLatestRequestMutex);
4688
Shuzhen Wang83bff122020-11-20 15:51:39 -08004689 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004690 mLatestRequest.acquire(cloned);
4691
4692 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004693 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4694 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4695 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004696 CameraMetadata(cloned));
4697 }
4698
4699 sp<Camera3Device> parent = mParent.promote();
4700 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07004701 int32_t inputStreamId = -1;
4702 if (halRequest.input_buffer != nullptr) {
4703 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
4704 }
4705
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004706 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004707 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07004708 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
4709 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004710 }
4711 }
4712
Shuzhen Wang83bff122020-11-20 15:51:39 -08004713 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004714 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004715 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004716 }
4717
Shuzhen Wang83bff122020-11-20 15:51:39 -08004718 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004719}
4720
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004721bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4722 ATRACE_CALL();
4723 bool updatesDetected = false;
4724
Emilian Peev4ec17882019-01-24 17:16:58 -08004725 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004726 for (auto tag : mSessionParamKeys) {
4727 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004728 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004729
4730 if (entry.count > 0) {
4731 bool isDifferent = false;
4732 if (lastEntry.count > 0) {
4733 // Have a last value, compare to see if changed
4734 if (lastEntry.type == entry.type &&
4735 lastEntry.count == entry.count) {
4736 // Same type and count, compare values
4737 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4738 size_t entryBytes = bytesPerValue * lastEntry.count;
4739 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4740 if (cmp != 0) {
4741 isDifferent = true;
4742 }
4743 } else {
4744 // Count or type has changed
4745 isDifferent = true;
4746 }
4747 } else {
4748 // No last entry, so always consider to be different
4749 isDifferent = true;
4750 }
4751
4752 if (isDifferent) {
4753 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004754 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4755 updatesDetected = true;
4756 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004757 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004758 }
4759 } else if (lastEntry.count > 0) {
4760 // Value has been removed
4761 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004762 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004763 updatesDetected = true;
4764 }
4765 }
4766
Emilian Peev4ec17882019-01-24 17:16:58 -08004767 bool reconfigureRequired;
4768 if (updatesDetected) {
4769 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4770 updatedParams);
4771 mLatestSessionParams = updatedParams;
4772 } else {
4773 reconfigureRequired = false;
4774 }
4775
4776 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004777}
4778
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004779bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004780 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004781 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004782 // Any function called from threadLoop() must not hold mInterfaceLock since
4783 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4784 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004785
4786 // Handle paused state.
4787 if (waitIfPaused()) {
4788 return true;
4789 }
4790
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004791 // Wait for the next batch of requests.
4792 waitForNextRequestBatch();
4793 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004794 return true;
4795 }
4796
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004797 // Get the latest request ID, if any
4798 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004799 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004800 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004801 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004802 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004803 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004804 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4805 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004806 }
4807
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004808 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4809 // or a single request from streaming or burst. In either case the first element
4810 // should contain the latest camera settings that we need to check for any session
4811 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004812 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004813 res = OK;
4814
4815 //Input stream buffers are already acquired at this point so an input stream
4816 //will not be able to move to idle state unless we force it.
4817 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4818 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4819 if (res != OK) {
4820 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4821 cleanUpFailedRequests(/*sendRequestError*/ false);
4822 return false;
4823 }
4824 }
4825
4826 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004827 sp<Camera3Device> parent = mParent.promote();
4828 if (parent != nullptr) {
4829 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004830 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004831 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004832
4833 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4834 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4835 if (res != OK) {
4836 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4837 cleanUpFailedRequests(/*sendRequestError*/ false);
4838 return false;
4839 }
4840 }
4841 }
4842 }
4843
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004844 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004845 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004846 if (res == TIMED_OUT) {
4847 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004848 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004849 // Check if any stream is abandoned.
4850 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004851 return true;
4852 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004853 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004854 return false;
4855 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004856
Zhijun Hecc27e112013-10-03 16:12:43 -07004857 // Inform waitUntilRequestProcessed thread of a new request ID
4858 {
4859 Mutex::Autolock al(mLatestRequestMutex);
4860
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004861 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004862 mLatestRequestSignal.signal();
4863 }
4864
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004865 // Submit a batch of requests to HAL.
4866 // Use flush lock only when submitting multilple requests in a batch.
4867 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4868 // which may take a long time to finish so synchronizing flush() and
4869 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4870 // For now, only synchronize for high speed recording and we should figure something out for
4871 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004872 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004873
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004874 if (useFlushLock) {
4875 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004876 }
4877
Zhijun Hef0645c12016-08-02 00:58:11 -07004878 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004879 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004880
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004881 sp<Camera3Device> parent = mParent.promote();
4882 if (parent != nullptr) {
4883 parent->mRequestBufferSM.onSubmittingRequest();
4884 }
4885
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004886 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004887 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004888 submitRequestSuccess = sendRequestsBatch();
4889
Shuzhen Wang686f6442017-06-20 16:16:04 -07004890 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4891 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004892
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004893 if (useFlushLock) {
4894 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004895 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004896
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004897 // Unset as current request
4898 {
4899 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004900 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004901 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004902 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004903
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004904 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004905}
4906
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004907status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
4908 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
4909 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
4910 ANDROID_SCALER_CROP_REGION_SET};
4911 if (request == nullptr) {
4912 ALOGE("%s request metadata nullptr", __FUNCTION__);
4913 return BAD_VALUE;
4914 }
4915 status_t res = OK;
4916 for (const auto &key : kFwkOnlyRegionKeys) {
4917 if (request->exists(key)) {
4918 res = request->erase(key);
4919 if (res != OK) {
4920 return res;
4921 }
4922 }
4923 }
4924 return OK;
4925}
4926
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004927status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004928 ATRACE_CALL();
4929
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004930 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004931 for (size_t i = 0; i < mNextRequests.size(); i++) {
4932 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004933 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004934 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4935 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004936
4937 // Prepare a request to HAL
4938 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4939
4940 // Insert any queued triggers (before metadata is locked)
4941 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004942 if (res < 0) {
4943 SET_ERR("RequestThread: Unable to insert triggers "
4944 "(capture request %d, HAL device: %s (%d)",
4945 halRequest->frame_number, strerror(-res), res);
4946 return INVALID_OPERATION;
4947 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004948
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004949 int triggerCount = res;
4950 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4951 mPrevTriggers = triggerCount;
4952
Emilian Peeve23f1d92021-09-20 14:56:01 -07004953 // Do not override rotate&crop for stream configurations that include
4954 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
4955 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
4956 bool rotateAndCropChanged = mComposerOutput ? false :
4957 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004958 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004959
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004960 // If the request is the same as last, or we had triggers now or last time or
4961 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004962 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004963 (mPrevRequest != captureRequest || triggersMixedIn ||
4964 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004965 // Request settings are all the same within one batch, so only treat the first
4966 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004967 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004968 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004969 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004970 /**
4971 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004972 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004973 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004974 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004976 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004977 "(capture request %d, HAL device: %s (%d)",
4978 halRequest->frame_number, strerror(-res), res);
4979 return INVALID_OPERATION;
4980 }
4981
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004982 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004983 sp<Camera3Device> parent = mParent.promote();
4984 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004985 List<PhysicalCameraSettings>::iterator it;
4986 for (it = captureRequest->mSettingsList.begin();
4987 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004988 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
4989 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00004990 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
4991 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
4992 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
4993 res);
4994 return INVALID_OPERATION;
4995 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07004996 continue;
4997 }
4998
4999 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
5000 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
5001 updateCaptureRequest(&(it->metadata));
5002 if (res != OK) {
5003 SET_ERR("RequestThread: Unable to correct capture requests "
5004 "for scaler crop region and metering regions for request "
5005 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
5006 res);
5007 return INVALID_OPERATION;
5008 }
5009 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00005010 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
5011 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
5012 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
5013 res);
5014 return INVALID_OPERATION;
5015 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07005016 }
5017 }
5018
5019 // Correct metadata regions for distortion correction if enabled
5020 for (it = captureRequest->mSettingsList.begin();
5021 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005022 if (parent->mDistortionMappers.find(it->cameraId) ==
5023 parent->mDistortionMappers.end()) {
5024 continue;
5025 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005026
5027 if (!captureRequest->mDistortionCorrectionUpdated) {
5028 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5029 &(it->metadata));
5030 if (res != OK) {
5031 SET_ERR("RequestThread: Unable to correct capture requests "
5032 "for lens distortion for request %d: %s (%d)",
5033 halRequest->frame_number, strerror(-res), res);
5034 return INVALID_OPERATION;
5035 }
5036 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005037 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005038 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005039
5040 for (it = captureRequest->mSettingsList.begin();
5041 it != captureRequest->mSettingsList.end(); it++) {
5042 if (parent->mZoomRatioMappers.find(it->cameraId) ==
5043 parent->mZoomRatioMappers.end()) {
5044 continue;
5045 }
5046
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005047 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005048 cameraIdsWithZoom.insert(it->cameraId);
5049 }
5050
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005051 if (!captureRequest->mZoomRatioUpdated) {
5052 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
5053 &(it->metadata));
5054 if (res != OK) {
5055 SET_ERR("RequestThread: Unable to correct capture requests "
5056 "for zoom ratio for request %d: %s (%d)",
5057 halRequest->frame_number, strerror(-res), res);
5058 return INVALID_OPERATION;
5059 }
5060 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005061 }
5062 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005063 if (captureRequest->mRotateAndCropAuto &&
5064 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005065 for (it = captureRequest->mSettingsList.begin();
5066 it != captureRequest->mSettingsList.end(); it++) {
5067 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
5068 if (mapper != parent->mRotateAndCropMappers.end()) {
5069 res = mapper->second.updateCaptureRequest(&(it->metadata));
5070 if (res != OK) {
5071 SET_ERR("RequestThread: Unable to correct capture requests "
5072 "for rotate-and-crop for request %d: %s (%d)",
5073 halRequest->frame_number, strerror(-res), res);
5074 return INVALID_OPERATION;
5075 }
5076 }
5077 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07005078 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005079 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005080 }
5081 }
5082
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005083 /**
5084 * The request should be presorted so accesses in HAL
5085 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5086 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005087 captureRequest->mSettingsList.begin()->metadata.sort();
5088 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005090 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005091 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5092
5093 IF_ALOGV() {
5094 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5095 find_camera_metadata_ro_entry(
5096 halRequest->settings,
5097 ANDROID_CONTROL_AF_TRIGGER,
5098 &e
5099 );
5100 if (e.count > 0) {
5101 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5102 __FUNCTION__,
5103 halRequest->frame_number,
5104 e.data.u8[0]);
5105 }
5106 }
5107 } else {
5108 // leave request.settings NULL to indicate 'reuse latest given'
5109 ALOGVV("%s: Request settings are REUSED",
5110 __FUNCTION__);
5111 }
5112
Emilian Peevaebbe412018-01-15 13:53:24 +00005113 if (captureRequest->mSettingsList.size() > 1) {
5114 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5115 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005116 if (newRequest) {
5117 halRequest->physcam_settings =
5118 new const camera_metadata* [halRequest->num_physcam_settings];
5119 } else {
5120 halRequest->physcam_settings = nullptr;
5121 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005122 auto it = ++captureRequest->mSettingsList.begin();
5123 size_t i = 0;
5124 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5125 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005126 if (newRequest) {
5127 it->metadata.sort();
5128 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5129 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005130 }
5131 }
5132
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005133 uint32_t totalNumBuffers = 0;
5134
5135 // Fill in buffers
5136 if (captureRequest->mInputStream != NULL) {
5137 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08005138
5139 halRequest->input_width = captureRequest->mInputBufferSize.width;
5140 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005141 totalNumBuffers += 1;
5142 } else {
5143 halRequest->input_buffer = NULL;
5144 }
5145
Emilian Peevf4816702020-04-03 15:44:51 -07005146 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005147 captureRequest->mOutputStreams.size());
5148 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08005149 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005150
5151 sp<Camera3Device> parent = mParent.promote();
5152 if (parent == NULL) {
5153 // Should not happen, and nowhere to send errors to, so just log it
5154 CLOGE("RequestThread: Parent is gone");
5155 return INVALID_OPERATION;
5156 }
5157 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5158
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005159 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005160 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005161 sp<Camera3OutputStreamInterface> outputStream =
5162 captureRequest->mOutputStreams.editItemAt(j);
5163 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005164
5165 // Prepare video buffers for high speed recording on the first video request.
5166 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5167 // Only try to prepare video stream on the first video request.
5168 mPrepareVideoStream = false;
5169
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005170 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5171 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005172 while (res == NOT_ENOUGH_DATA) {
5173 res = outputStream->prepareNextBuffer();
5174 }
5175 if (res != OK) {
5176 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5177 __FUNCTION__, strerror(-res), res);
5178 outputStream->cancelPrepare();
5179 }
5180 }
5181
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005182 std::vector<size_t> uniqueSurfaceIds;
5183 res = outputStream->getUniqueSurfaceIds(
5184 captureRequest->mOutputSurfaces[streamId],
5185 &uniqueSurfaceIds);
5186 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5187 if (res != OK && res != INVALID_OPERATION) {
5188 ALOGE("%s: failed to query stream %d unique surface IDs",
5189 __FUNCTION__, streamId);
5190 return res;
5191 }
5192 if (res == OK) {
5193 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5194 }
5195
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005196 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005197 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005198 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005199 return TIMED_OUT;
5200 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005201 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005202 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005203 buffer.stream = outputStream->asHalStream();
5204 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005205 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005206 buffer.acquire_fence = -1;
5207 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005208 // Mark the output stream as unpreparable to block clients from calling
5209 // 'prepare' after this request reaches CameraHal and before the respective
5210 // buffers are requested.
5211 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005212 } else {
5213 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5214 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005215 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005216 if (res != OK) {
5217 // Can't get output buffer from gralloc queue - this could be due to
5218 // abandoned queue or other consumer misbehavior, so not a fatal
5219 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005220 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005221 " %s (%d)", strerror(-res), res);
5222
5223 return TIMED_OUT;
5224 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005225 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005226
5227 {
5228 sp<Camera3Device> parent = mParent.promote();
5229 if (parent != nullptr) {
5230 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5231 for (const auto& settings : captureRequest->mSettingsList) {
5232 if ((streamCameraId.isEmpty() &&
5233 parent->getId() == settings.cameraId.c_str()) ||
5234 streamCameraId == settings.cameraId.c_str()) {
5235 outputStream->fireBufferRequestForFrameNumber(
5236 captureRequest->mResultExtras.frameNumber,
5237 settings.metadata);
5238 }
5239 }
5240 }
5241 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005242
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005243 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005244 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5245 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5246 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5247 } else if (!physicalCameraId.isEmpty()) {
5248 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005249 }
5250 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005251 }
5252 totalNumBuffers += halRequest->num_output_buffers;
5253
5254 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005255 // If this request list is for constrained high speed recording (not
5256 // preview), and the current request is not the last one in the batch,
5257 // do not send callback to the app.
5258 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005259 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005260 hasCallback = false;
5261 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005262 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005263 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005264 const camera_metadata_t* settings = halRequest->settings;
5265 bool shouldUnlockSettings = false;
5266 if (settings == nullptr) {
5267 shouldUnlockSettings = true;
5268 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5269 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005270 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5271 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005272 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005273 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5274 isStillCapture = true;
5275 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5276 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005277
Emilian Peevaf8416e2021-02-04 17:52:43 -08005278 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005279 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005280 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5281 isZslCapture = true;
5282 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005283 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005284 res = parent->registerInFlight(halRequest->frame_number,
5285 totalNumBuffers, captureRequest->mResultExtras,
5286 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005287 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005288 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005289 requestedPhysicalCameras, isStillCapture, isZslCapture,
5290 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005291 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005292 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005293 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5294 ", burstId = %" PRId32 ".",
5295 __FUNCTION__,
5296 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5297 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005298
5299 if (shouldUnlockSettings) {
5300 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5301 }
5302
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005303 if (res != OK) {
5304 SET_ERR("RequestThread: Unable to register new in-flight request:"
5305 " %s (%d)", strerror(-res), res);
5306 return INVALID_OPERATION;
5307 }
5308 }
5309
5310 return OK;
5311}
5312
Igor Murashkin1e479c02013-09-06 16:55:14 -07005313CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005314 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005315 Mutex::Autolock al(mLatestRequestMutex);
5316
5317 ALOGV("RequestThread::%s", __FUNCTION__);
5318
5319 return mLatestRequest;
5320}
5321
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005322bool Camera3Device::RequestThread::isStreamPending(
5323 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005324 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005325 Mutex::Autolock l(mRequestLock);
5326
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005327 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005328 if (!nextRequest.submitted) {
5329 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5330 if (stream == s) return true;
5331 }
5332 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005333 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005334 }
5335
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005336 for (const auto& request : mRequestQueue) {
5337 for (const auto& s : request->mOutputStreams) {
5338 if (stream == s) return true;
5339 }
5340 if (stream == request->mInputStream) return true;
5341 }
5342
5343 for (const auto& request : mRepeatingRequests) {
5344 for (const auto& s : request->mOutputStreams) {
5345 if (stream == s) return true;
5346 }
5347 if (stream == request->mInputStream) return true;
5348 }
5349
5350 return false;
5351}
Jianing Weicb0652e2014-03-12 18:29:36 -07005352
Emilian Peev40ead602017-09-26 15:46:36 +01005353bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5354 ATRACE_CALL();
5355 Mutex::Autolock l(mRequestLock);
5356
5357 for (const auto& nextRequest : mNextRequests) {
5358 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5359 if (s.first == streamId) {
5360 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5361 if (it != s.second.end()) {
5362 return true;
5363 }
5364 }
5365 }
5366 }
5367
5368 for (const auto& request : mRequestQueue) {
5369 for (const auto& s : request->mOutputSurfaces) {
5370 if (s.first == streamId) {
5371 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5372 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005373 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005374 }
5375 }
5376 }
5377 }
5378
5379 for (const auto& request : mRepeatingRequests) {
5380 for (const auto& s : request->mOutputSurfaces) {
5381 if (s.first == streamId) {
5382 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5383 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005384 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005385 }
5386 }
5387 }
5388 }
5389
5390 return false;
5391}
5392
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005393void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5394 if (!mUseHalBufManager) {
5395 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5396 return;
5397 }
5398
5399 Mutex::Autolock pl(mPauseLock);
5400 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005401 mInterface->signalPipelineDrain(streamIds);
5402 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005403 }
5404 // If request thread is still busy, wait until paused then notify HAL
5405 mNotifyPipelineDrain = true;
5406 mStreamIdsToBeDrained = streamIds;
5407}
5408
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005409void Camera3Device::RequestThread::resetPipelineDrain() {
5410 Mutex::Autolock pl(mPauseLock);
5411 mNotifyPipelineDrain = false;
5412 mStreamIdsToBeDrained.clear();
5413}
5414
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005415void Camera3Device::RequestThread::clearPreviousRequest() {
5416 Mutex::Autolock l(mRequestLock);
5417 mPrevRequest.clear();
5418}
5419
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005420status_t Camera3Device::RequestThread::switchToOffline(
5421 const std::vector<int32_t>& streamsToKeep,
5422 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005423 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5424 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005425 Mutex::Autolock l(mRequestLock);
5426 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5427
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005428 // Wait until request thread is fully stopped
5429 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5430
5431 // We could also check for mRepeatingRequests.empty(), but the API interface
5432 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5433 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005434 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5435 while (!queueEmpty) {
5436 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5437 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005438 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005439 return res;
5440 } else if (res != OK) {
5441 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5442 __FUNCTION__, strerror(-res), res);
5443 return res;
5444 }
5445 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5446 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005447
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005448 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005449 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005450}
5451
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005452status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5453 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5454 ATRACE_CALL();
5455 Mutex::Autolock l(mTriggerMutex);
5456 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5457 return BAD_VALUE;
5458 }
5459 mRotateAndCropOverride = rotateAndCropValue;
5460 return OK;
5461}
5462
Emilian Peeve23f1d92021-09-20 14:56:01 -07005463status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
5464 ATRACE_CALL();
5465 Mutex::Autolock l(mTriggerMutex);
5466 mComposerOutput = composerSurfacePresent;
5467 return OK;
5468}
5469
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005470status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005471 ATRACE_CALL();
5472 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005473 if (muteMode != mCameraMute) {
5474 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005475 mCameraMuteChanged = true;
5476 }
5477 return OK;
5478}
5479
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005480nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005481 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005482 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005483 return mExpectedInflightDuration > kMinInflightDuration ?
5484 mExpectedInflightDuration : kMinInflightDuration;
5485}
5486
Emilian Peevaebbe412018-01-15 13:53:24 +00005487void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005488 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005489 if ((request == nullptr) || (halRequest == nullptr)) {
5490 ALOGE("%s: Invalid request!", __FUNCTION__);
5491 return;
5492 }
5493
5494 if (halRequest->num_physcam_settings > 0) {
5495 if (halRequest->physcam_id != nullptr) {
5496 delete [] halRequest->physcam_id;
5497 halRequest->physcam_id = nullptr;
5498 }
5499 if (halRequest->physcam_settings != nullptr) {
5500 auto it = ++(request->mSettingsList.begin());
5501 size_t i = 0;
5502 for (; it != request->mSettingsList.end(); it++, i++) {
5503 it->metadata.unlock(halRequest->physcam_settings[i]);
5504 }
5505 delete [] halRequest->physcam_settings;
5506 halRequest->physcam_settings = nullptr;
5507 }
5508 }
5509}
5510
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005511void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5512 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005513 return;
5514 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005515
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005516 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005517 // Skip the ones that have been submitted successfully.
5518 if (nextRequest.submitted) {
5519 continue;
5520 }
5521
5522 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005523 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5524 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005525
5526 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005527 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005528 }
5529
Emilian Peevaebbe412018-01-15 13:53:24 +00005530 cleanupPhysicalSettings(captureRequest, halRequest);
5531
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005532 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005533 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005534 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5535 }
5536
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005537 // No output buffer can be returned when using HAL buffer manager
5538 if (!mUseHalBufManager) {
5539 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5540 //Buffers that failed processing could still have
5541 //valid acquire fence.
5542 int acquireFence = (*outputBuffers)[i].acquire_fence;
5543 if (0 <= acquireFence) {
5544 close(acquireFence);
5545 outputBuffers->editItemAt(i).acquire_fence = -1;
5546 }
Emilian Peevf4816702020-04-03 15:44:51 -07005547 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07005548 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
5549 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005550 /*timestampIncreasing*/true, std::vector<size_t> (),
5551 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005552 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005553 }
5554
5555 if (sendRequestError) {
5556 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005557 sp<NotificationListener> listener = mListener.promote();
5558 if (listener != NULL) {
5559 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005560 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005561 captureRequest->mResultExtras);
5562 }
5563 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005564
5565 // Remove yet-to-be submitted inflight request from inflightMap
5566 {
5567 sp<Camera3Device> parent = mParent.promote();
5568 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005569 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005570 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5571 if (idx >= 0) {
5572 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5573 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5574 parent->removeInFlightMapEntryLocked(idx);
5575 }
5576 }
5577 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005578 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005579
5580 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005581 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005582}
5583
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005584void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005585 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005586 // Optimized a bit for the simple steady-state case (single repeating
5587 // request), to avoid putting that request in the queue temporarily.
5588 Mutex::Autolock l(mRequestLock);
5589
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005590 assert(mNextRequests.empty());
5591
5592 NextRequest nextRequest;
5593 nextRequest.captureRequest = waitForNextRequestLocked();
5594 if (nextRequest.captureRequest == nullptr) {
5595 return;
5596 }
5597
Emilian Peevf4816702020-04-03 15:44:51 -07005598 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005599 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005600 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005601
5602 // Wait for additional requests
5603 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5604
5605 for (size_t i = 1; i < batchSize; i++) {
5606 NextRequest additionalRequest;
5607 additionalRequest.captureRequest = waitForNextRequestLocked();
5608 if (additionalRequest.captureRequest == nullptr) {
5609 break;
5610 }
5611
Emilian Peevf4816702020-04-03 15:44:51 -07005612 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005613 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005614 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005615 }
5616
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005617 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005618 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005619 mNextRequests.size(), batchSize);
5620 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005621 }
5622
5623 return;
5624}
5625
5626sp<Camera3Device::CaptureRequest>
5627 Camera3Device::RequestThread::waitForNextRequestLocked() {
5628 status_t res;
5629 sp<CaptureRequest> nextRequest;
5630
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005631 while (mRequestQueue.empty()) {
5632 if (!mRepeatingRequests.empty()) {
5633 // Always atomically enqueue all requests in a repeating request
5634 // list. Guarantees a complete in-sequence set of captures to
5635 // application.
5636 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005637 if (mFirstRepeating) {
5638 mFirstRepeating = false;
5639 } else {
5640 for (auto& request : requests) {
5641 // For repeating requests, override timestamp request using
5642 // the time a request is inserted into the request queue,
5643 // because the original repeating request will have an old
5644 // fixed timestamp.
5645 request->mRequestTimeNs = systemTime();
5646 }
5647 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005648 RequestList::const_iterator firstRequest =
5649 requests.begin();
5650 nextRequest = *firstRequest;
5651 mRequestQueue.insert(mRequestQueue.end(),
5652 ++firstRequest,
5653 requests.end());
5654 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005655
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005656 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005657
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005658 break;
5659 }
5660
5661 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5662
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005663 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5664 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005665 Mutex::Autolock pl(mPauseLock);
5666 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005667 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005668 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005669 if (mNotifyPipelineDrain) {
5670 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5671 mNotifyPipelineDrain = false;
5672 mStreamIdsToBeDrained.clear();
5673 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005674 // Let the tracker know
5675 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5676 if (statusTracker != 0) {
5677 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5678 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005679 sp<Camera3Device> parent = mParent.promote();
5680 if (parent != nullptr) {
5681 parent->mRequestBufferSM.onRequestThreadPaused();
5682 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005683 }
5684 // Stop waiting for now and let thread management happen
5685 return NULL;
5686 }
5687 }
5688
5689 if (nextRequest == NULL) {
5690 // Don't have a repeating request already in hand, so queue
5691 // must have an entry now.
5692 RequestList::iterator firstRequest =
5693 mRequestQueue.begin();
5694 nextRequest = *firstRequest;
5695 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005696 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5697 sp<NotificationListener> listener = mListener.promote();
5698 if (listener != NULL) {
5699 listener->notifyRequestQueueEmpty();
5700 }
5701 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005702 }
5703
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005704 // In case we've been unpaused by setPaused clearing mDoPause, need to
5705 // update internal pause state (capture/setRepeatingRequest unpause
5706 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005707 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005708 if (mPaused) {
5709 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5710 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5711 if (statusTracker != 0) {
5712 statusTracker->markComponentActive(mStatusId);
5713 }
5714 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005715 mPaused = false;
5716
5717 // Check if we've reconfigured since last time, and reset the preview
5718 // request if so. Can't use 'NULL request == repeat' across configure calls.
5719 if (mReconfigured) {
5720 mPrevRequest.clear();
5721 mReconfigured = false;
5722 }
5723
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005724 if (nextRequest != NULL) {
5725 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005726 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5727 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005728
5729 // Since RequestThread::clear() removes buffers from the input stream,
5730 // get the right buffer here before unlocking mRequestLock
5731 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005732 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5733 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005734 if (res != OK) {
5735 // Can't get input buffer from gralloc queue - this could be due to
5736 // disconnected queue or other producer misbehavior, so not a fatal
5737 // error
5738 ALOGE("%s: Can't get input buffer, skipping request:"
5739 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005740
5741 sp<NotificationListener> listener = mListener.promote();
5742 if (listener != NULL) {
5743 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005744 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005745 nextRequest->mResultExtras);
5746 }
5747 return NULL;
5748 }
5749 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005750 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005751
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005752 return nextRequest;
5753}
5754
5755bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005756 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005757 status_t res;
5758 Mutex::Autolock l(mPauseLock);
5759 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005760 if (mPaused == false) {
5761 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005762 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005763 if (mNotifyPipelineDrain) {
5764 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5765 mNotifyPipelineDrain = false;
5766 mStreamIdsToBeDrained.clear();
5767 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005768 // Let the tracker know
5769 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5770 if (statusTracker != 0) {
5771 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5772 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005773 sp<Camera3Device> parent = mParent.promote();
5774 if (parent != nullptr) {
5775 parent->mRequestBufferSM.onRequestThreadPaused();
5776 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005777 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005778
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005779 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005780 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005781 return true;
5782 }
5783 }
5784 // We don't set mPaused to false here, because waitForNextRequest needs
5785 // to further manage the paused state in case of starvation.
5786 return false;
5787}
5788
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005789void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005790 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005791 // With work to do, mark thread as unpaused.
5792 // If paused by request (setPaused), don't resume, to avoid
5793 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005794 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005795 Mutex::Autolock p(mPauseLock);
5796 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005797 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5798 if (mPaused) {
5799 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5800 if (statusTracker != 0) {
5801 statusTracker->markComponentActive(mStatusId);
5802 }
5803 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005804 mPaused = false;
5805 }
5806}
5807
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005808void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5809 sp<Camera3Device> parent = mParent.promote();
5810 if (parent != NULL) {
5811 va_list args;
5812 va_start(args, fmt);
5813
5814 parent->setErrorStateV(fmt, args);
5815
5816 va_end(args);
5817 }
5818}
5819
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005820status_t Camera3Device::RequestThread::insertTriggers(
5821 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005822 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005823 Mutex::Autolock al(mTriggerMutex);
5824
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005825 sp<Camera3Device> parent = mParent.promote();
5826 if (parent == NULL) {
5827 CLOGE("RequestThread: Parent is gone");
5828 return DEAD_OBJECT;
5829 }
5830
Emilian Peevaebbe412018-01-15 13:53:24 +00005831 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005832 size_t count = mTriggerMap.size();
5833
5834 for (size_t i = 0; i < count; ++i) {
5835 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005836 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005837
5838 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5839 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5840 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005841 if (isAeTrigger) {
5842 request->mResultExtras.precaptureTriggerId = triggerId;
5843 mCurrentPreCaptureTriggerId = triggerId;
5844 } else {
5845 request->mResultExtras.afTriggerId = triggerId;
5846 mCurrentAfTriggerId = triggerId;
5847 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005848 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005849 }
5850
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005851 camera_metadata_entry entry = metadata.find(tag);
5852
5853 if (entry.count > 0) {
5854 /**
5855 * Already has an entry for this trigger in the request.
5856 * Rewrite it with our requested trigger value.
5857 */
5858 RequestTrigger oldTrigger = trigger;
5859
5860 oldTrigger.entryValue = entry.data.u8[0];
5861
5862 mTriggerReplacedMap.add(tag, oldTrigger);
5863 } else {
5864 /**
5865 * More typical, no trigger entry, so we just add it
5866 */
5867 mTriggerRemovedMap.add(tag, trigger);
5868 }
5869
5870 status_t res;
5871
5872 switch (trigger.getTagType()) {
5873 case TYPE_BYTE: {
5874 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5875 res = metadata.update(tag,
5876 &entryValue,
5877 /*count*/1);
5878 break;
5879 }
5880 case TYPE_INT32:
5881 res = metadata.update(tag,
5882 &trigger.entryValue,
5883 /*count*/1);
5884 break;
5885 default:
5886 ALOGE("%s: Type not supported: 0x%x",
5887 __FUNCTION__,
5888 trigger.getTagType());
5889 return INVALID_OPERATION;
5890 }
5891
5892 if (res != OK) {
5893 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5894 ", value %d", __FUNCTION__, trigger.getTagName(),
5895 trigger.entryValue);
5896 return res;
5897 }
5898
5899 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5900 trigger.getTagName(),
5901 trigger.entryValue);
5902 }
5903
5904 mTriggerMap.clear();
5905
5906 return count;
5907}
5908
5909status_t Camera3Device::RequestThread::removeTriggers(
5910 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005911 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005912 Mutex::Autolock al(mTriggerMutex);
5913
Emilian Peevaebbe412018-01-15 13:53:24 +00005914 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005915
5916 /**
5917 * Replace all old entries with their old values.
5918 */
5919 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5920 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5921
5922 status_t res;
5923
5924 uint32_t tag = trigger.metadataTag;
5925 switch (trigger.getTagType()) {
5926 case TYPE_BYTE: {
5927 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5928 res = metadata.update(tag,
5929 &entryValue,
5930 /*count*/1);
5931 break;
5932 }
5933 case TYPE_INT32:
5934 res = metadata.update(tag,
5935 &trigger.entryValue,
5936 /*count*/1);
5937 break;
5938 default:
5939 ALOGE("%s: Type not supported: 0x%x",
5940 __FUNCTION__,
5941 trigger.getTagType());
5942 return INVALID_OPERATION;
5943 }
5944
5945 if (res != OK) {
5946 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5947 ", trigger value %d", __FUNCTION__,
5948 trigger.getTagName(), trigger.entryValue);
5949 return res;
5950 }
5951 }
5952 mTriggerReplacedMap.clear();
5953
5954 /**
5955 * Remove all new entries.
5956 */
5957 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5958 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5959 status_t res = metadata.erase(trigger.metadataTag);
5960
5961 if (res != OK) {
5962 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5963 ", trigger value %d", __FUNCTION__,
5964 trigger.getTagName(), trigger.entryValue);
5965 return res;
5966 }
5967 }
5968 mTriggerRemovedMap.clear();
5969
5970 return OK;
5971}
5972
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005973status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005974 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005975 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005976 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005977 status_t res;
5978
Emilian Peevaebbe412018-01-15 13:53:24 +00005979 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005980
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005981 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005982 // exists
5983 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5984 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5985 if (afTrigger.count > 0 &&
5986 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5987 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005988 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005989 if (res != OK) return res;
5990 }
5991
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005992 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005993 // if none already exists
5994 camera_metadata_entry pcTrigger =
5995 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5996 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5997 if (pcTrigger.count > 0 &&
5998 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5999 pcId.count == 0) {
6000 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04006001 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006002 if (res != OK) return res;
6003 }
6004
6005 return OK;
6006}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006007
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006008bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
6009 const sp<CaptureRequest> &request) {
6010 ATRACE_CALL();
6011
6012 if (request->mRotateAndCropAuto) {
6013 Mutex::Autolock l(mTriggerMutex);
6014 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
6015
6016 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
6017 if (rotateAndCropEntry.count > 0) {
6018 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
6019 return false;
6020 } else {
6021 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
6022 return true;
6023 }
6024 } else {
6025 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
6026 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
6027 &rotateAndCrop_u8, 1);
6028 return true;
6029 }
6030 }
6031 return false;
6032}
6033
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006034bool Camera3Device::RequestThread::overrideTestPattern(
6035 const sp<CaptureRequest> &request) {
6036 ATRACE_CALL();
6037
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07006038 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07006039
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006040 Mutex::Autolock l(mTriggerMutex);
6041
6042 bool changed = false;
6043
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006044 // For a multi-camera, the physical cameras support the same set of
6045 // test pattern modes as the logical camera.
6046 for (auto& settings : request->mSettingsList) {
6047 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006048
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006049 int32_t testPatternMode = settings.mOriginalTestPatternMode;
6050 int32_t testPatternData[4] = {
6051 settings.mOriginalTestPatternData[0],
6052 settings.mOriginalTestPatternData[1],
6053 settings.mOriginalTestPatternData[2],
6054 settings.mOriginalTestPatternData[3]
6055 };
6056 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
6057 testPatternMode = mCameraMute;
6058 testPatternData[0] = 0;
6059 testPatternData[1] = 0;
6060 testPatternData[2] = 0;
6061 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006062 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006063
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006064 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
6065 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
6066 if (testPatternEntry.count > 0) {
6067 if (testPatternEntry.data.i32[0] != testPatternMode) {
6068 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006069 changed = true;
6070 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006071 } else if (supportTestPatternModeKey) {
6072 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
6073 &testPatternMode, 1);
6074 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006075 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07006076
6077 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
6078 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
6079 if (testPatternColor.count >= 4) {
6080 for (size_t i = 0; i < 4; i++) {
6081 if (testPatternColor.data.i32[i] != testPatternData[i]) {
6082 testPatternColor.data.i32[i] = testPatternData[i];
6083 changed = true;
6084 }
6085 }
6086 } else if (supportTestPatternDataKey) {
6087 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
6088 testPatternData, 4);
6089 changed = true;
6090 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006091 }
6092
6093 return changed;
6094}
6095
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006096status_t Camera3Device::RequestThread::setHalInterface(
6097 sp<HalInterface> newHalInterface) {
6098 if (newHalInterface.get() == nullptr) {
6099 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
6100 return DEAD_OBJECT;
6101 }
6102
6103 mInterface = newHalInterface;
6104
6105 return OK;
6106}
6107
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006108/**
6109 * PreparerThread inner class methods
6110 */
6111
6112Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006113 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006114 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006115}
6116
6117Camera3Device::PreparerThread::~PreparerThread() {
6118 Thread::requestExitAndWait();
6119 if (mCurrentStream != nullptr) {
6120 mCurrentStream->cancelPrepare();
6121 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6122 mCurrentStream.clear();
6123 }
6124 clear();
6125}
6126
Ruben Brunkc78ac262015-08-13 17:58:46 -07006127status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006128 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006129 status_t res;
6130
6131 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006132 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006133
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006134 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006135 if (res == OK) {
6136 // No preparation needed, fire listener right off
6137 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006138 if (listener != NULL) {
6139 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006140 }
6141 return OK;
6142 } else if (res != NOT_ENOUGH_DATA) {
6143 return res;
6144 }
6145
6146 // Need to prepare, start up thread if necessary
6147 if (!mActive) {
6148 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6149 // isn't running
6150 Thread::requestExitAndWait();
6151 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6152 if (res != OK) {
6153 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006154 if (listener != NULL) {
6155 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006156 }
6157 return res;
6158 }
6159 mCancelNow = false;
6160 mActive = true;
6161 ALOGV("%s: Preparer stream started", __FUNCTION__);
6162 }
6163
6164 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006165 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006166 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6167
6168 return OK;
6169}
6170
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006171void Camera3Device::PreparerThread::pause() {
6172 ATRACE_CALL();
6173
6174 Mutex::Autolock l(mLock);
6175
6176 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6177 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6178 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6179 int currentMaxCount = mCurrentMaxCount;
6180 mPendingStreams.clear();
6181 mCancelNow = true;
6182 while (mActive) {
6183 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6184 if (res == TIMED_OUT) {
6185 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6186 return;
6187 } else if (res != OK) {
6188 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6189 return;
6190 }
6191 }
6192
6193 //Check whether the prepare thread was able to complete the current
6194 //stream. In case work is still pending emplace it along with the rest
6195 //of the streams in the pending list.
6196 if (currentStream != nullptr) {
6197 if (!mCurrentPrepareComplete) {
6198 pendingStreams.emplace(currentMaxCount, currentStream);
6199 }
6200 }
6201
6202 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6203 for (const auto& it : mPendingStreams) {
6204 it.second->cancelPrepare();
6205 }
6206}
6207
6208status_t Camera3Device::PreparerThread::resume() {
6209 ATRACE_CALL();
6210 status_t res;
6211
6212 Mutex::Autolock l(mLock);
6213 sp<NotificationListener> listener = mListener.promote();
6214
6215 if (mActive) {
6216 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6217 return NO_INIT;
6218 }
6219
6220 auto it = mPendingStreams.begin();
6221 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006222 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006223 if (res == OK) {
6224 if (listener != NULL) {
6225 listener->notifyPrepared(it->second->getId());
6226 }
6227 it = mPendingStreams.erase(it);
6228 } else if (res != NOT_ENOUGH_DATA) {
6229 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6230 res, strerror(-res));
6231 it = mPendingStreams.erase(it);
6232 } else {
6233 it++;
6234 }
6235 }
6236
6237 if (mPendingStreams.empty()) {
6238 return OK;
6239 }
6240
6241 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6242 if (res != OK) {
6243 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6244 __FUNCTION__, res, strerror(-res));
6245 return res;
6246 }
6247 mCancelNow = false;
6248 mActive = true;
6249 ALOGV("%s: Preparer stream started", __FUNCTION__);
6250
6251 return OK;
6252}
6253
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006254status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006255 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006256 Mutex::Autolock l(mLock);
6257
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006258 for (const auto& it : mPendingStreams) {
6259 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006260 }
6261 mPendingStreams.clear();
6262 mCancelNow = true;
6263
6264 return OK;
6265}
6266
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006267void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006268 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006269 Mutex::Autolock l(mLock);
6270 mListener = listener;
6271}
6272
6273bool Camera3Device::PreparerThread::threadLoop() {
6274 status_t res;
6275 {
6276 Mutex::Autolock l(mLock);
6277 if (mCurrentStream == nullptr) {
6278 // End thread if done with work
6279 if (mPendingStreams.empty()) {
6280 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6281 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6282 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6283 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006284 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006285 return false;
6286 }
6287
6288 // Get next stream to prepare
6289 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006290 mCurrentStream = it->second;
6291 mCurrentMaxCount = it->first;
6292 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006293 mPendingStreams.erase(it);
6294 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6295 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6296 } else if (mCancelNow) {
6297 mCurrentStream->cancelPrepare();
6298 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6299 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6300 mCurrentStream.clear();
6301 mCancelNow = false;
6302 return true;
6303 }
6304 }
6305
6306 res = mCurrentStream->prepareNextBuffer();
6307 if (res == NOT_ENOUGH_DATA) return true;
6308 if (res != OK) {
6309 // Something bad happened; try to recover by cancelling prepare and
6310 // signalling listener anyway
6311 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6312 mCurrentStream->getId(), res, strerror(-res));
6313 mCurrentStream->cancelPrepare();
6314 }
6315
6316 // This stream has finished, notify listener
6317 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006318 sp<NotificationListener> listener = mListener.promote();
6319 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006320 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6321 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006322 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006323 }
6324
6325 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6326 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006327 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006328
6329 return true;
6330}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006331
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006332status_t Camera3Device::RequestBufferStateMachine::initialize(
6333 sp<camera3::StatusTracker> statusTracker) {
6334 if (statusTracker == nullptr) {
6335 ALOGE("%s: statusTracker is null", __FUNCTION__);
6336 return BAD_VALUE;
6337 }
6338
6339 std::lock_guard<std::mutex> lock(mLock);
6340 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006341 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006342 return OK;
6343}
6344
6345bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6346 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006347 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006348 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006349 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006350 return true;
6351 }
6352 return false;
6353}
6354
6355void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6356 std::lock_guard<std::mutex> lock(mLock);
6357 if (!mRequestBufferOngoing) {
6358 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6359 return;
6360 }
6361 mRequestBufferOngoing = false;
6362 if (mStatus == RB_STATUS_PENDING_STOP) {
6363 checkSwitchToStopLocked();
6364 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006365 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006366}
6367
6368void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6369 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006370 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006371 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006372 return;
6373}
6374
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006375void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006376 std::lock_guard<std::mutex> lock(mLock);
6377 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006378 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6379 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006380 mInflightMapEmpty = false;
6381 if (mStatus == RB_STATUS_STOPPED) {
6382 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006383 }
6384 return;
6385}
6386
6387void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6388 std::lock_guard<std::mutex> lock(mLock);
6389 mRequestThreadPaused = true;
6390 if (mStatus == RB_STATUS_PENDING_STOP) {
6391 checkSwitchToStopLocked();
6392 }
6393 return;
6394}
6395
6396void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6397 std::lock_guard<std::mutex> lock(mLock);
6398 mInflightMapEmpty = true;
6399 if (mStatus == RB_STATUS_PENDING_STOP) {
6400 checkSwitchToStopLocked();
6401 }
6402 return;
6403}
6404
6405void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6406 std::lock_guard<std::mutex> lock(mLock);
6407 if (!checkSwitchToStopLocked()) {
6408 mStatus = RB_STATUS_PENDING_STOP;
6409 }
6410 return;
6411}
6412
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006413bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6414 std::lock_guard<std::mutex> lock(mLock);
6415 if (mRequestBufferOngoing) {
6416 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6417 __FUNCTION__);
6418 return false;
6419 }
6420 mSwitchedToOffline = true;
6421 mInflightMapEmpty = true;
6422 mRequestThreadPaused = true;
6423 mStatus = RB_STATUS_STOPPED;
6424 return true;
6425}
6426
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006427void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6428 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6429 if (statusTracker != nullptr) {
6430 if (active) {
6431 statusTracker->markComponentActive(mRequestBufferStatusId);
6432 } else {
6433 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6434 }
6435 }
6436}
6437
6438bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6439 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6440 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006441 return true;
6442 }
6443 return false;
6444}
6445
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006446bool Camera3Device::startRequestBuffer() {
6447 return mRequestBufferSM.startRequestBuffer();
6448}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006449
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006450void Camera3Device::endRequestBuffer() {
6451 mRequestBufferSM.endRequestBuffer();
6452}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006453
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006454nsecs_t Camera3Device::getWaitDuration() {
6455 return kBaseGetBufferWait + getExpectedInFlightDuration();
6456}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006457
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006458void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6459 mInterface->getInflightBufferKeys(out);
6460}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006461
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006462void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6463 mInterface->getInflightRequestBufferKeys(out);
6464}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006465
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006466std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6467 std::vector<sp<Camera3StreamInterface>> ret;
6468 bool hasInputStream = mInputStream != nullptr;
6469 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6470 if (hasInputStream) {
6471 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006472 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006473 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6474 ret.push_back(mOutputStreams[i]);
6475 }
6476 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6477 ret.push_back(mDeletedStreams[i]);
6478 }
6479 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006480}
6481
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006482status_t Camera3Device::switchToOffline(
6483 const std::vector<int32_t>& streamsToKeep,
6484 /*out*/ sp<CameraOfflineSessionBase>* session) {
6485 ATRACE_CALL();
6486 if (session == nullptr) {
6487 ALOGE("%s: session must not be null", __FUNCTION__);
6488 return BAD_VALUE;
6489 }
6490
6491 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006492
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006493 bool hasInputStream = mInputStream != nullptr;
6494 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6495 bool inputStreamSupportsOffline = hasInputStream ?
6496 mInputStream->getOfflineProcessingSupport() : false;
6497 auto outputStreamIds = mOutputStreams.getStreamIds();
6498 auto streamIds = outputStreamIds;
6499 if (hasInputStream) {
6500 streamIds.push_back(mInputStream->getId());
6501 }
6502
6503 // Check all streams in streamsToKeep supports offline mode
6504 for (auto id : streamsToKeep) {
6505 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6506 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6507 return BAD_VALUE;
6508 } else if (id == inputStreamId) {
6509 if (!inputStreamSupportsOffline) {
6510 ALOGE("%s: input stream %d cannot be switched to offline",
6511 __FUNCTION__, id);
6512 return BAD_VALUE;
6513 }
6514 } else {
6515 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6516 if (!stream->getOfflineProcessingSupport()) {
6517 ALOGE("%s: output stream %d cannot be switched to offline",
6518 __FUNCTION__, id);
6519 return BAD_VALUE;
6520 }
6521 }
6522 }
6523
6524 // TODO: block surface sharing and surface group streams until we can support them
6525
6526 // Stop repeating request, wait until all remaining requests are submitted, then call into
6527 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006528 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6529 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006530 camera3::BufferRecords bufferRecords;
6531 status_t ret = mRequestThread->switchToOffline(
6532 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006533
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006534 if (ret != OK) {
6535 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6536 return ret;
6537 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006538
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006539 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6540 if (!succ) {
6541 SET_ERR("HAL must not be calling requestStreamBuffers call");
6542 // TODO: block ALL callbacks from HAL till app configured new streams?
6543 return UNKNOWN_ERROR;
6544 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006545
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006546 // Verify offlineSessionInfo
6547 std::vector<int32_t> offlineStreamIds;
6548 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6549 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6550 // verify stream IDs
6551 int32_t id = offlineStream.id;
6552 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6553 SET_ERR("stream ID %d not found!", id);
6554 return UNKNOWN_ERROR;
6555 }
6556
6557 // When not using HAL buf manager, only allow streams requested by app to be preserved
6558 if (!mUseHalBufManager) {
6559 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6560 SET_ERR("stream ID %d must not be switched to offline!", id);
6561 return UNKNOWN_ERROR;
6562 }
6563 }
6564
6565 offlineStreamIds.push_back(id);
6566 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6567 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6568 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6569 // Verify number of outstanding buffers
6570 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6571 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6572 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6573 return UNKNOWN_ERROR;
6574 }
6575 }
6576
6577 // Verify all streams to be deleted don't have any outstanding buffers
6578 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6579 inputStreamId) == offlineStreamIds.end()) {
6580 if (mInputStream->hasOutstandingBuffers()) {
6581 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6582 inputStreamId, mInputStream->getOutstandingBuffersCount());
6583 return UNKNOWN_ERROR;
6584 }
6585 }
6586
6587 for (const auto& outStreamId : outputStreamIds) {
6588 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6589 outStreamId) == offlineStreamIds.end()) {
6590 auto outStream = mOutputStreams.get(outStreamId);
6591 if (outStream->hasOutstandingBuffers()) {
6592 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6593 outStreamId, outStream->getOutstandingBuffersCount());
6594 return UNKNOWN_ERROR;
6595 }
6596 }
6597 }
6598
6599 InFlightRequestMap offlineReqs;
6600 // Verify inflight requests and their pending buffers
6601 {
6602 std::lock_guard<std::mutex> l(mInFlightLock);
6603 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6604 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6605 if (idx == NAME_NOT_FOUND) {
6606 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6607 return UNKNOWN_ERROR;
6608 }
6609
6610 const auto& inflightReq = mInFlightMap.valueAt(idx);
6611 // TODO: check specific stream IDs
6612 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6613 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6614 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6615 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6616 return UNKNOWN_ERROR;
6617 }
6618 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6619 }
6620 }
6621
6622 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006623 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006624 camera3::StreamSet offlineStreamSet;
6625 sp<camera3::Camera3Stream> inputStream;
6626 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6627 int32_t id = offlineStream.id;
6628 if (mInputStream != nullptr && id == mInputStream->getId()) {
6629 inputStream = mInputStream;
6630 } else {
6631 offlineStreamSet.add(id, mOutputStreams.get(id));
6632 }
6633 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006634
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006635 // TODO: check if we need to lock before copying states
6636 // though technically no other thread should be talking to Camera3Device at this point
6637 Camera3OfflineStates offlineStates(
6638 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006639 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6640 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6641 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6642 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6643 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6644 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6645 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006646
6647 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6648 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6649
6650 // Delete all streams that has been transferred to offline session
6651 Mutex::Autolock l(mLock);
6652 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6653 int32_t id = offlineStream.id;
6654 if (mInputStream != nullptr && id == mInputStream->getId()) {
6655 mInputStream.clear();
6656 } else {
6657 mOutputStreams.remove(id);
6658 }
6659 }
6660
6661 // disconnect all other streams and switch to UNCONFIGURED state
6662 if (mInputStream != nullptr) {
6663 ret = mInputStream->disconnect();
6664 if (ret != OK) {
6665 SET_ERR_L("disconnect input stream failed!");
6666 return UNKNOWN_ERROR;
6667 }
6668 }
6669
6670 for (auto streamId : mOutputStreams.getStreamIds()) {
6671 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6672 ret = stream->disconnect();
6673 if (ret != OK) {
6674 SET_ERR_L("disconnect output stream %d failed!", streamId);
6675 return UNKNOWN_ERROR;
6676 }
6677 }
6678
6679 mInputStream.clear();
6680 mOutputStreams.clear();
6681 mNeedConfig = true;
6682 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6683 mOperatingMode = NO_MODE;
6684 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006685 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006686
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006687 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006688 // TO be done by CameraDeviceClient/Camera3OfflineSession
6689 // register the offline client to camera service
6690 // Setup result passthing threads etc
6691 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6692 // TODO: check how many onIdle callback will be sent
6693 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006694}
6695
Emilian Peevcc0b7952020-01-07 13:54:47 -08006696void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6697 ATRACE_CALL();
6698
6699 if (offlineStreamIds == nullptr) {
6700 return;
6701 }
6702
6703 Mutex::Autolock il(mInterfaceLock);
6704
6705 auto streamIds = mOutputStreams.getStreamIds();
6706 bool hasInputStream = mInputStream != nullptr;
6707 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6708 offlineStreamIds->push_back(mInputStream->getId());
6709 }
6710
6711 for (const auto & streamId : streamIds) {
6712 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6713 // Streams that use the camera buffer manager are currently not supported in
6714 // offline mode
6715 if (stream->getOfflineProcessingSupport() &&
6716 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6717 offlineStreamIds->push_back(streamId);
6718 }
6719 }
6720}
6721
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006722status_t Camera3Device::setRotateAndCropAutoBehavior(
6723 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6724 ATRACE_CALL();
6725 Mutex::Autolock il(mInterfaceLock);
6726 Mutex::Autolock l(mLock);
6727 if (mRequestThread == nullptr) {
6728 return INVALID_OPERATION;
6729 }
6730 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6731}
6732
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006733bool Camera3Device::supportsCameraMute() {
6734 Mutex::Autolock il(mInterfaceLock);
6735 Mutex::Autolock l(mLock);
6736
6737 return mSupportCameraMute;
6738}
6739
6740status_t Camera3Device::setCameraMute(bool enabled) {
6741 ATRACE_CALL();
6742 Mutex::Autolock il(mInterfaceLock);
6743 Mutex::Autolock l(mLock);
6744
6745 if (mRequestThread == nullptr || !mSupportCameraMute) {
6746 return INVALID_OPERATION;
6747 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006748 int32_t muteMode =
6749 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6750 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6751 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6752 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006753}
6754
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006755status_t Camera3Device::injectCamera(const String8& injectedCamId,
6756 sp<CameraProviderManager> manager) {
6757 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6758 ATRACE_CALL();
6759 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006760 // When the camera device is active, injectCamera() and stopInjection() will call
6761 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
6762 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
6763 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
6764 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
6765 // waitUntilStateThenRelock().
6766 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006767
6768 status_t res = NO_ERROR;
6769 if (mInjectionMethods->isInjecting()) {
6770 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6771 return OK;
6772 } else {
6773 res = mInjectionMethods->stopInjection();
6774 if (res != OK) {
6775 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6776 __FUNCTION__, res);
6777 return res;
6778 }
6779 }
6780 }
6781
6782 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6783 if (res != OK) {
6784 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6785 __FUNCTION__, res);
6786 return res;
6787 }
6788
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006789 // When the second display of android is cast to the remote device, and the opened camera is
6790 // also cast to the second display, in this case, because the camera has configured the streams
6791 // at this time, we can directly call injectCamera() to replace the internal camera with
6792 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08006793 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
6794 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6795
6796 camera3::camera_stream_configuration injectionConfig;
6797 std::vector<uint32_t> injectionBufferSizes;
6798 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6799 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
6800 || injectionBufferSizes.size() <= 0) {
6801 ALOGE("Failed to inject camera due to abandoned configuration! "
6802 "mOperatingMode: %d injectionConfig.num_streams: %d "
6803 "injectionBufferSizes.size(): %zu", mOperatingMode,
6804 injectionConfig.num_streams, injectionBufferSizes.size());
6805 return DEAD_OBJECT;
6806 }
6807
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006808 res = mInjectionMethods->injectCamera(
6809 injectionConfig, injectionBufferSizes);
6810 if (res != OK) {
6811 ALOGE("Can't finish inject camera process!");
6812 return res;
6813 }
6814 }
6815
6816 return OK;
6817}
6818
6819status_t Camera3Device::stopInjection() {
6820 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6821 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08006822 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006823 return mInjectionMethods->stopInjection();
6824}
6825
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006826}; // namespace android