blob: 59b030582406728469d2905bdd5e1d436264b12c [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
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
98 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
104Camera3Device::~Camera3Device()
105{
106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700108 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109}
110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800112 return mId;
113}
114
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115status_t Camera3Device::initializeCommonLocked() {
116
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700117 /** Start up status tracker thread */
118 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700120 if (res != OK) {
121 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
122 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700124 mStatusTracker.clear();
125 return res;
126 }
127
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700128 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700129 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700130
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700131 if (mUseHalBufManager) {
132 res = mRequestBufferSM.initialize(mStatusTracker);
133 if (res != OK) {
134 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
135 strerror(-res), res);
136 mInterface->close();
137 mStatusTracker.clear();
138 return res;
139 }
140 }
141
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800142 /** Create buffer manager */
143 mBufferManager = new Camera3BufferManager();
144
145 Vector<int32_t> sessionParamKeys;
146 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
147 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
148 if (sessionKeysEntry.count > 0) {
149 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
150 }
151
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700152 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
153 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
154 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
155 if (availableTestPatternModes.data.i32[i] ==
156 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
157 mSupportCameraMute = true;
158 mSupportTestPatternSolidColor = true;
159 break;
160 } else if (availableTestPatternModes.data.i32[i] ==
161 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
162 mSupportCameraMute = true;
163 mSupportTestPatternSolidColor = false;
164 }
165 }
166
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700167 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800168 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700169 this, mStatusTracker, mInterface, sessionParamKeys,
170 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800171 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800172 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700173 SET_ERR_L("Unable to start request queue thread: %s (%d)",
174 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800175 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800176 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800177 return res;
178 }
179
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700180 mPreparerThread = new PreparerThread();
181
Ruben Brunk183f0562015-08-12 12:55:02 -0700182 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800183 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400184 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700185 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700186 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800187 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800188
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800189 // Measure the clock domain offset between camera and video/hw_composer
190 camera_metadata_entry timestampSource =
191 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
192 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
193 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
194 mTimestampOffset = getMonoToBoottimeOffset();
195 }
196
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700197 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100198 camera_metadata_entry partialResultsCount =
199 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
200 if (partialResultsCount.count > 0) {
201 mNumPartialResults = partialResultsCount.data.i32[0];
202 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700203 }
204
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800205 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
206 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700207 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700208 if (res != OK) {
209 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
210 return res;
211 }
212 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800213
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800214 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800216
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700217 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
218 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
219 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
220 }
221
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800222 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
223 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
224 }
225
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800226 // Hidl/AidlCamera3DeviceInjectionMethods
227 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800228
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800229 return OK;
230}
231
232status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700233 return disconnectImpl();
234}
235
236status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800237 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700238 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800239
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700240 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700241 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700242 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800243 Mutex::Autolock il(mInterfaceLock);
244 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
245 {
246 Mutex::Autolock l(mLock);
247 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700248
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800249 if (mStatus == STATUS_ACTIVE ||
250 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
251 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700252 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800253 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 } else {
256 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
257 if (res != OK) {
258 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
259 maxExpectedDuration);
260 // Continue to close device even in case of error
261 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700263 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800264
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800265 if (mStatus == STATUS_ERROR) {
266 CLOGE("Shutting down in an error state");
267 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800269 if (mStatusTracker != NULL) {
270 mStatusTracker->requestExit();
271 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800273 if (mRequestThread != NULL) {
274 mRequestThread->requestExit();
275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800277 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
278 for (size_t i = 0; i < mOutputStreams.size(); i++) {
279 streams.push_back(mOutputStreams[i]);
280 }
281 if (mInputStream != nullptr) {
282 streams.push_back(mInputStream);
283 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700284 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700285 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800286 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
287 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700288 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
289 // HAL may be in a bad state, so waiting for request thread
290 // (which may be stuck in the HAL processCaptureRequest call)
291 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800292 // give up mInterfaceLock here and then lock it again. Could this lead
293 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 mRequestThread->join();
295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800297 Mutex::Autolock il(mInterfaceLock);
298 if (mStatusTracker != NULL) {
299 mStatusTracker->join();
300 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800301
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800302 if (mInjectionMethods->isInjecting()) {
303 mInjectionMethods->stopInjection();
304 }
305
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800306 HalInterface* interface;
307 {
308 Mutex::Autolock l(mLock);
309 mRequestThread.clear();
310 Mutex::Autolock stLock(mTrackerLock);
311 mStatusTracker.clear();
312 interface = mInterface.get();
313 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700314
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800315 // Call close without internal mutex held, as the HAL close may need to
316 // wait on assorted callbacks,etc, to complete before it can return.
317 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700318
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800319 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 {
322 Mutex::Autolock l(mLock);
323 mInterface->clear();
324 mOutputStreams.clear();
325 mInputStream.clear();
326 mDeletedStreams.clear();
327 mBufferManager.clear();
328 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
329 }
330
331 for (auto& weakStream : streams) {
332 sp<Camera3StreamInterface> stream = weakStream.promote();
333 if (stream != nullptr) {
334 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
335 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
336 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700337 }
338 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700339 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341}
342
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343// For dumping/debugging only -
344// try to acquire a lock a few times, eventually give up to proceed with
345// debug/dump operations
346bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
347 bool gotLock = false;
348 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
349 if (lock.tryLock() == NO_ERROR) {
350 gotLock = true;
351 break;
352 } else {
353 usleep(kDumpSleepDuration);
354 }
355 }
356 return gotLock;
357}
358
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800359nsecs_t Camera3Device::getMonoToBoottimeOffset() {
360 // try three times to get the clock offset, choose the one
361 // with the minimum gap in measurements.
362 const int tries = 3;
363 nsecs_t bestGap, measured;
364 for (int i = 0; i < tries; ++i) {
365 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
366 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
367 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t gap = tmono2 - tmono;
369 if (i == 0 || gap < bestGap) {
370 bestGap = gap;
371 measured = tbase - ((tmono + tmono2) >> 1);
372 }
373 }
374 return measured;
375}
376
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800377ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
378 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700379 // Get max jpeg size (area-wise) for default sensor pixel mode
380 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800381 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700382 /*isUltraHighResolutionSensor*/false);
383 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
384 // not ultra high res sensor
385 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800386 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700387 /*isUltraHighResolution*/true);
388 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800389 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
390 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700391 return BAD_VALUE;
392 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700393 bool useMaxSensorPixelModeThreshold = false;
394 if (uhrMaxJpegResolution.width != 0 &&
395 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
396 // Use the ultra high res max jpeg size and max jpeg buffer size
397 useMaxSensorPixelModeThreshold = true;
398 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700399
Zhijun Hef7da0962014-04-24 13:27:56 -0700400 // Get max jpeg buffer size
401 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800402 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700403 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800404 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
405 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700406 return BAD_VALUE;
407 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700408 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700409
410 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
411 if (useMaxSensorPixelModeThreshold) {
412 maxJpegBufferSize =
413 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
414 maxDefaultJpegResolution, maxJpegBufferSize);
415 chosenMaxJpegResolution = uhrMaxJpegResolution;
416 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800417 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700418
419 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700421 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800422 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
423 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700424 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800425 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
426 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700427 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700428 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 return jpegBufferSize;
430}
431
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800432ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700433 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700435 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800436 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
437 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700438 return BAD_VALUE;
439 }
440 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
441 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
442 return maxBytesForPointCloud;
443}
444
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800445ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
446 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800447 const int PER_CONFIGURATION_SIZE = 3;
448 const int WIDTH_OFFSET = 0;
449 const int HEIGHT_OFFSET = 1;
450 const int SIZE_OFFSET = 2;
451 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800452 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800453 camera3::SessionConfigurationUtils::getAppropriateModeTag(
454 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
455 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800456 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800457 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800458 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
459 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800460 return BAD_VALUE;
461 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700462
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800463 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
464 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
465 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
466 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
467 }
468 }
469
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800470 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
471 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800472 return BAD_VALUE;
473}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700474
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800475status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
476 ATRACE_CALL();
477 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700478
479 // Try to lock, but continue in case of failure (to avoid blocking in
480 // deadlocks)
481 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
482 bool gotLock = tryLockSpinRightRound(mLock);
483
484 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800485 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
486 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700487 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
489 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700490
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800491 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700492
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800493 String16 templatesOption("-t");
494 int n = args.size();
495 for (int i = 0; i < n; i++) {
496 if (args[i] == templatesOption) {
497 dumpTemplates = true;
498 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000499 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700500 if (i + 1 < n) {
501 String8 monitorTags = String8(args[i + 1]);
502 if (monitorTags == "off") {
503 mTagMonitor.disableMonitoring();
504 } else {
505 mTagMonitor.parseTagsToMonitor(monitorTags);
506 }
507 } else {
508 mTagMonitor.disableMonitoring();
509 }
510 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800511 }
512
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800513 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800515 const char *status =
516 mStatus == STATUS_ERROR ? "ERROR" :
517 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700518 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
519 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800520 mStatus == STATUS_ACTIVE ? "ACTIVE" :
521 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800523 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700524 if (mStatus == STATUS_ERROR) {
525 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
526 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800527 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800528 const char *mode =
529 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
530 mOperatingMode == static_cast<int>(
531 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
532 "CUSTOM";
533 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800534
535 if (mInputStream != NULL) {
536 write(fd, lines.string(), lines.size());
537 mInputStream->dump(fd, args);
538 } else {
539 lines.appendFormat(" No input stream.\n");
540 write(fd, lines.string(), lines.size());
541 }
542 for (size_t i = 0; i < mOutputStreams.size(); i++) {
543 mOutputStreams[i]->dump(fd,args);
544 }
545
Zhijun He431503c2016-03-07 17:30:16 -0800546 if (mBufferManager != NULL) {
547 lines = String8(" Camera3 Buffer Manager:\n");
548 write(fd, lines.string(), lines.size());
549 mBufferManager->dump(fd, args);
550 }
Zhijun He125684a2015-12-26 15:07:30 -0800551
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700552 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700553 if (mInFlightLock.try_lock()) {
554 if (mInFlightMap.size() == 0) {
555 lines.append(" None\n");
556 } else {
557 for (size_t i = 0; i < mInFlightMap.size(); i++) {
558 InFlightRequest r = mInFlightMap.valueAt(i);
559 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
560 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
561 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
562 r.numBuffersLeft);
563 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700564 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700565 mInFlightLock.unlock();
566 } else {
567 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700568 }
569 write(fd, lines.string(), lines.size());
570
Shuzhen Wang686f6442017-06-20 16:16:04 -0700571 if (mRequestThread != NULL) {
572 mRequestThread->dumpCaptureRequestLatency(fd,
573 " ProcessCaptureRequest latency histogram:");
574 }
575
Igor Murashkin1e479c02013-09-06 16:55:14 -0700576 {
577 lines = String8(" Last request sent:\n");
578 write(fd, lines.string(), lines.size());
579
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700580 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700581 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
582 }
583
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800584 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700585 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 "TEMPLATE_PREVIEW",
587 "TEMPLATE_STILL_CAPTURE",
588 "TEMPLATE_VIDEO_RECORD",
589 "TEMPLATE_VIDEO_SNAPSHOT",
590 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800591 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800592 };
593
Emilian Peevf4816702020-04-03 15:44:51 -0700594 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800595 camera_metadata_t *templateRequest = nullptr;
596 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700597 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800598 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800599 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 lines.append(" Not supported\n");
601 write(fd, lines.string(), lines.size());
602 } else {
603 write(fd, lines.string(), lines.size());
604 dump_indented_camera_metadata(templateRequest,
605 fd, /*verbosity*/2, /*indentation*/8);
606 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800607 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800608 }
609 }
610
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700611 mTagMonitor.dumpMonitoredMetadata(fd);
612
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800613 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800614 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800615 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800618
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700619 if (gotLock) mLock.unlock();
620 if (gotInterfaceLock) mInterfaceLock.unlock();
621
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800622 return OK;
623}
624
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700625status_t Camera3Device::startWatchingTags(const String8 &tags) {
626 mTagMonitor.parseTagsToMonitor(tags);
627 return OK;
628}
629
630status_t Camera3Device::stopWatchingTags() {
631 mTagMonitor.disableMonitoring();
632 return OK;
633}
634
635status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
636 mTagMonitor.getLatestMonitoredTagEvents(out);
637 return OK;
638}
639
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800640const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800641 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800642 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
643 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700644 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800645 mStatus == STATUS_ERROR ?
646 "when in error state" : "before init");
647 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700648 if (physicalId.isEmpty()) {
649 return mDeviceInfo;
650 } else {
651 std::string id(physicalId.c_str());
652 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
653 return mPhysicalDeviceInfoMap.at(id);
654 } else {
655 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
656 return mDeviceInfo;
657 }
658 }
659}
660
661const CameraMetadata& Camera3Device::info() const {
662 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800663 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800664}
665
Jianing Wei90e59c92014-03-12 18:29:36 -0700666status_t Camera3Device::checkStatusOkToCaptureLocked() {
667 switch (mStatus) {
668 case STATUS_ERROR:
669 CLOGE("Device has encountered a serious error");
670 return INVALID_OPERATION;
671 case STATUS_UNINITIALIZED:
672 CLOGE("Device not initialized");
673 return INVALID_OPERATION;
674 case STATUS_UNCONFIGURED:
675 case STATUS_CONFIGURED:
676 case STATUS_ACTIVE:
677 // OK
678 break;
679 default:
680 SET_ERR_L("Unexpected status: %d", mStatus);
681 return INVALID_OPERATION;
682 }
683 return OK;
684}
685
686status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000687 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700688 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700689 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700690 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700691 if (requestList == NULL) {
692 CLOGE("requestList cannot be NULL.");
693 return BAD_VALUE;
694 }
695
Jianing Weicb0652e2014-03-12 18:29:36 -0700696 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000697 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700698 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
699 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
700 ++metadataIt, ++surfaceMapIt) {
701 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700702 if (newRequest == 0) {
703 CLOGE("Can't create capture request");
704 return BAD_VALUE;
705 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700706
Shuzhen Wang9d066012016-09-30 11:30:20 -0700707 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700708 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700709
Jianing Weicb0652e2014-03-12 18:29:36 -0700710 // Setup burst Id and request Id
711 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800712 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
713 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700714 CLOGE("RequestID does not exist in metadata");
715 return BAD_VALUE;
716 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800717 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700718
Jianing Wei90e59c92014-03-12 18:29:36 -0700719 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700720
721 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700722 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700723 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
724 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
725 return BAD_VALUE;
726 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700727
728 // Setup batch size if this is a high speed video recording request.
729 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
730 auto firstRequest = requestList->begin();
731 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
732 if (outputStream->isVideoStream()) {
733 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800734 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700735 break;
736 }
737 }
738 }
739
Jianing Wei90e59c92014-03-12 18:29:36 -0700740 return OK;
741}
742
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800743status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800744 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800745
Emilian Peevaebbe412018-01-15 13:53:24 +0000746 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700747 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000748 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800750 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751}
752
Emilian Peevaebbe412018-01-15 13:53:24 +0000753void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700754 std::list<const SurfaceMap>& surfaceMaps,
755 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000756 PhysicalCameraSettingsList requestList;
757 requestList.push_back({std::string(getId().string()), request});
758 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700759
760 SurfaceMap surfaceMap;
761 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
762 // With no surface list passed in, stream and surface will have 1-to-1
763 // mapping. So the surface index is 0 for each stream in the surfaceMap.
764 for (size_t i = 0; i < streams.count; i++) {
765 surfaceMap[streams.data.i32[i]].push_back(0);
766 }
767 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800768}
769
Jianing Wei90e59c92014-03-12 18:29:36 -0700770status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000771 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700772 const std::list<const SurfaceMap> &surfaceMaps,
773 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700774 /*out*/
775 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700776 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700777 nsecs_t requestTimeNs = systemTime();
778
Jianing Wei90e59c92014-03-12 18:29:36 -0700779 Mutex::Autolock il(mInterfaceLock);
780 Mutex::Autolock l(mLock);
781
782 status_t res = checkStatusOkToCaptureLocked();
783 if (res != OK) {
784 // error logged by previous call
785 return res;
786 }
787
788 RequestList requestList;
789
Shuzhen Wang0129d522016-10-30 22:43:41 -0700790 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700791 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700792 if (res != OK) {
793 // error logged by previous call
794 return res;
795 }
796
797 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700798 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 }
802
803 if (res == OK) {
804 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
805 if (res != OK) {
806 SET_ERR_L("Can't transition to active in %f seconds!",
807 kActiveTimeout/1e9);
808 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800809 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700810 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 } else {
812 CLOGE("Cannot queue request. Impossible.");
813 return BAD_VALUE;
814 }
815
816 return res;
817}
818
Emilian Peevaebbe412018-01-15 13:53:24 +0000819status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700821 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700822 ATRACE_CALL();
823
Emilian Peevaebbe412018-01-15 13:53:24 +0000824 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800826
Jianing Weicb0652e2014-03-12 18:29:36 -0700827status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
828 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800829 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800830
Emilian Peevaebbe412018-01-15 13:53:24 +0000831 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800837}
838
Emilian Peevaebbe412018-01-15 13:53:24 +0000839status_t Camera3Device::setStreamingRequestList(
840 const List<const PhysicalCameraSettingsList> &requestsList,
841 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700842 ATRACE_CALL();
843
Emilian Peevaebbe412018-01-15 13:53:24 +0000844 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700845}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800846
847sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000848 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800849 status_t res;
850
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700851 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800852 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
853 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000854 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700855 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700856 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800857 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700858 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 } else if (mStatus == STATUS_UNCONFIGURED) {
861 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700862 CLOGE("No streams configured");
863 return NULL;
864 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800865 }
866
Shuzhen Wang0129d522016-10-30 22:43:41 -0700867 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800868 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800869}
870
Jianing Weicb0652e2014-03-12 18:29:36 -0700871status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800872 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700873 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800874 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800875
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 switch (mStatus) {
877 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700878 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800879 return INVALID_OPERATION;
880 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700881 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800882 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700883 case STATUS_UNCONFIGURED:
884 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885 case STATUS_ACTIVE:
886 // OK
887 break;
888 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700889 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800890 return INVALID_OPERATION;
891 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800892 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700893
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700894 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800895}
896
897status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800900
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700901 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902}
903
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700904status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800905 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700906 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700907 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700908 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700909 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800910 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
911 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700912
913 status_t res;
914 bool wasActive = false;
915
916 switch (mStatus) {
917 case STATUS_ERROR:
918 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
919 return INVALID_OPERATION;
920 case STATUS_UNINITIALIZED:
921 ALOGE("%s: Device not initialized", __FUNCTION__);
922 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700923 case STATUS_UNCONFIGURED:
924 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700925 // OK
926 break;
927 case STATUS_ACTIVE:
928 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700929 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700930 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700931 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 return res;
933 }
934 wasActive = true;
935 break;
936 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700937 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700938 return INVALID_OPERATION;
939 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700940 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700941
942 if (mInputStream != 0) {
943 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
944 return INVALID_OPERATION;
945 }
946
947 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
948 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950
951 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800952 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700953
954 *id = mNextStreamId++;
955
956 // Continue captures if active at start
957 if (wasActive) {
958 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100959 // Reuse current operating mode and session parameters for new stream config
960 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700961 if (res != OK) {
962 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
963 __FUNCTION__, mNextStreamId, strerror(-res), res);
964 return res;
965 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700966 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700967 }
968
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800969 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700970 return OK;
971}
972
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700973status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700974 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700975 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800976 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800977 const std::unordered_set<int32_t> &sensorPixelModesUsed,
978 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800979 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700980 ATRACE_CALL();
981
982 if (consumer == nullptr) {
983 ALOGE("%s: consumer must not be null", __FUNCTION__);
984 return BAD_VALUE;
985 }
986
987 std::vector<sp<Surface>> consumers;
988 consumers.push_back(consumer);
989
990 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800991 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800992 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
993 streamUseCase);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800994}
995
996static bool isRawFormat(int format) {
997 switch (format) {
998 case HAL_PIXEL_FORMAT_RAW16:
999 case HAL_PIXEL_FORMAT_RAW12:
1000 case HAL_PIXEL_FORMAT_RAW10:
1001 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1002 return true;
1003 default:
1004 return false;
1005 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001006}
1007
1008status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1009 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001010 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001011 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001012 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001013 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001014 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001015
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001016 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001017 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001018 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001019 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001020 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1021 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1022 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001023
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001024 status_t res;
1025 bool wasActive = false;
1026
1027 switch (mStatus) {
1028 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001029 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001030 return INVALID_OPERATION;
1031 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001032 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001033 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001034 case STATUS_UNCONFIGURED:
1035 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001036 // OK
1037 break;
1038 case STATUS_ACTIVE:
1039 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001040 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001041 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001042 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001043 return res;
1044 }
1045 wasActive = true;
1046 break;
1047 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001048 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001049 return INVALID_OPERATION;
1050 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001051 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001052
1053 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001054
Shuzhen Wang0129d522016-10-30 22:43:41 -07001055 if (consumers.size() == 0 && !hasDeferredConsumer) {
1056 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1057 return BAD_VALUE;
1058 }
Zhijun He5d677d12016-05-29 16:52:39 -07001059
Shuzhen Wang0129d522016-10-30 22:43:41 -07001060 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001061 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1062 return BAD_VALUE;
1063 }
1064
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001065 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1066 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1067 // be found in only one sensor pixel mode.
1068 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1069 return BAD_VALUE;
1070 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001072 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001073 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001074 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001075 if (blobBufferSize <= 0) {
1076 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1077 return BAD_VALUE;
1078 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001079 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1080 blobBufferSize = width * height;
1081 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001082 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001083 if (blobBufferSize <= 0) {
1084 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1085 return BAD_VALUE;
1086 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001087 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001088 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001089 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001090 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001091 isMultiResolution, dynamicRangeProfile, streamUseCase);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001092 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001093 bool maxResolution =
1094 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1095 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001096 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1097 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001098 if (rawOpaqueBufferSize <= 0) {
1099 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1100 return BAD_VALUE;
1101 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001102 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001103 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001104 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001105 isMultiResolution, dynamicRangeProfile, streamUseCase);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001106 } else if (isShared) {
1107 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1108 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001109 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001110 mUseHalBufManager, dynamicRangeProfile, streamUseCase);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001111 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001112 newStream = new Camera3OutputStream(mNextStreamId,
1113 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001114 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001115 isMultiResolution, dynamicRangeProfile, streamUseCase);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001116 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001117 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001118 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001119 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001120 isMultiResolution, dynamicRangeProfile, streamUseCase);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 }
Emilian Peev40ead602017-09-26 15:46:36 +01001122
1123 size_t consumerCount = consumers.size();
1124 for (size_t i = 0; i < consumerCount; i++) {
1125 int id = newStream->getSurfaceId(consumers[i]);
1126 if (id < 0) {
1127 SET_ERR_L("Invalid surface id");
1128 return BAD_VALUE;
1129 }
1130 if (surfaceIds != nullptr) {
1131 surfaceIds->push_back(id);
1132 }
1133 }
1134
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001136
Emilian Peev08dd2452017-04-06 16:55:14 +01001137 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001138
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001139 newStream->setImageDumpMask(mImageDumpMask);
1140
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001141 res = mOutputStreams.add(mNextStreamId, newStream);
1142 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001143 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001144 return res;
1145 }
1146
Shuzhen Wang316781a2020-08-18 18:11:01 -07001147 mSessionStatsBuilder.addStream(mNextStreamId);
1148
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001150 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001151
1152 // Continue captures if active at start
1153 if (wasActive) {
1154 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001155 // Reuse current operating mode and session parameters for new stream config
1156 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001157 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001158 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1159 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001160 return res;
1161 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001162 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001164 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001165 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001166}
1167
Emilian Peev710c1422017-08-30 11:19:38 +01001168status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001170 if (nullptr == streamInfo) {
1171 return BAD_VALUE;
1172 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001175
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 switch (mStatus) {
1177 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001178 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179 return INVALID_OPERATION;
1180 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001181 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001183 case STATUS_UNCONFIGURED:
1184 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 case STATUS_ACTIVE:
1186 // OK
1187 break;
1188 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001189 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190 return INVALID_OPERATION;
1191 }
1192
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001193 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1194 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001195 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001196 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 }
1198
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001199 streamInfo->width = stream->getWidth();
1200 streamInfo->height = stream->getHeight();
1201 streamInfo->format = stream->getFormat();
1202 streamInfo->dataSpace = stream->getDataSpace();
1203 streamInfo->formatOverridden = stream->isFormatOverridden();
1204 streamInfo->originalFormat = stream->getOriginalFormat();
1205 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1206 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001207 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209}
1210
1211status_t Camera3Device::setStreamTransform(int id,
1212 int transform) {
1213 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001214 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001216
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 switch (mStatus) {
1218 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001219 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return INVALID_OPERATION;
1221 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001222 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 case STATUS_UNCONFIGURED:
1225 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 case STATUS_ACTIVE:
1227 // OK
1228 break;
1229 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001230 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 return INVALID_OPERATION;
1232 }
1233
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001234 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1235 if (stream == nullptr) {
1236 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 return BAD_VALUE;
1238 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001239 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240}
1241
1242status_t Camera3Device::deleteStream(int id) {
1243 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 Mutex::Autolock l(mLock);
1246 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001248 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001249
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 // CameraDevice semantics require device to already be idle before
1251 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001253 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001254 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 }
1256
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001257 if (mStatus == STATUS_ERROR) {
1258 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1259 __FUNCTION__, mId.string());
1260 return -EBUSY;
1261 }
1262
Igor Murashkin2fba5842013-04-22 14:03:54 -07001263 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001264 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 if (mInputStream != NULL && id == mInputStream->getId()) {
1266 deletedStream = mInputStream;
1267 mInputStream.clear();
1268 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001269 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return BAD_VALUE;
1272 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001273 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001274 }
1275
1276 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001277 if (stream != nullptr) {
1278 deletedStream = stream;
1279 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 }
1281
1282 // Free up the stream endpoint so that it can be used by some other stream
1283 res = deletedStream->disconnect();
1284 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001285 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 // fall through since we want to still list the stream as deleted.
1287 }
1288 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001289 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290
1291 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001292}
1293
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001294status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001295 ATRACE_CALL();
1296 ALOGV("%s: E", __FUNCTION__);
1297
1298 Mutex::Autolock il(mInterfaceLock);
1299 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001300
Emilian Peev811d2952018-05-25 11:08:40 +01001301 // In case the client doesn't include any session parameter, try a
1302 // speculative configuration using the values from the last cached
1303 // default request.
1304 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001305 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001306 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1307 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1308 mLastTemplateId);
1309 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1310 operatingMode);
1311 }
1312
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001313 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1314}
1315
1316status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1317 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001318 //Filter out any incoming session parameters
1319 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001320 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1321 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001322 CameraMetadata filteredParams(availableSessionKeys.count);
1323 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1324 filteredParams.getAndLock());
1325 set_camera_metadata_vendor_id(meta, mVendorTagId);
1326 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001327 if (availableSessionKeys.count > 0) {
1328 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1329 camera_metadata_ro_entry entry = params.find(
1330 availableSessionKeys.data.i32[i]);
1331 if (entry.count > 0) {
1332 filteredParams.update(entry);
1333 }
1334 }
1335 }
1336
1337 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001338}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001339
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001340status_t Camera3Device::getInputBufferProducer(
1341 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001342 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001343 Mutex::Autolock il(mInterfaceLock);
1344 Mutex::Autolock l(mLock);
1345
1346 if (producer == NULL) {
1347 return BAD_VALUE;
1348 } else if (mInputStream == NULL) {
1349 return INVALID_OPERATION;
1350 }
1351
1352 return mInputStream->getInputBufferProducer(producer);
1353}
1354
Emilian Peevf4816702020-04-03 15:44:51 -07001355status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001356 CameraMetadata *request) {
1357 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001358 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001359
Emilian Peevf4816702020-04-03 15:44:51 -07001360 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001361 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001362 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001363 return BAD_VALUE;
1364 }
1365
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001366 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001368 {
1369 Mutex::Autolock l(mLock);
1370 switch (mStatus) {
1371 case STATUS_ERROR:
1372 CLOGE("Device has encountered a serious error");
1373 return INVALID_OPERATION;
1374 case STATUS_UNINITIALIZED:
1375 CLOGE("Device is not initialized!");
1376 return INVALID_OPERATION;
1377 case STATUS_UNCONFIGURED:
1378 case STATUS_CONFIGURED:
1379 case STATUS_ACTIVE:
1380 // OK
1381 break;
1382 default:
1383 SET_ERR_L("Unexpected status: %d", mStatus);
1384 return INVALID_OPERATION;
1385 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001386
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001387 if (!mRequestTemplateCache[templateId].isEmpty()) {
1388 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001389 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001390 return OK;
1391 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001392 }
1393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001394 camera_metadata_t *rawRequest;
1395 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001396 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001397
1398 {
1399 Mutex::Autolock l(mLock);
1400 if (res == BAD_VALUE) {
1401 ALOGI("%s: template %d is not supported on this camera device",
1402 __FUNCTION__, templateId);
1403 return res;
1404 } else if (res != OK) {
1405 CLOGE("Unable to construct request template %d: %s (%d)",
1406 templateId, strerror(-res), res);
1407 return res;
1408 }
1409
1410 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1411 mRequestTemplateCache[templateId].acquire(rawRequest);
1412
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001413 // Override the template request with zoomRatioMapper
1414 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1415 &mRequestTemplateCache[templateId]);
1416 if (res != OK) {
1417 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1418 templateId, strerror(-res), res);
1419 return res;
1420 }
1421
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001422 // Fill in JPEG_QUALITY if not available
1423 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1424 static const uint8_t kDefaultJpegQuality = 95;
1425 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1426 &kDefaultJpegQuality, 1);
1427 }
1428
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001429 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001430 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001431 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001432 return OK;
1433}
1434
1435status_t Camera3Device::waitUntilDrained() {
1436 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001437 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001438 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001440
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001441 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001442}
1443
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001444status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 switch (mStatus) {
1446 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 ALOGV("%s: Already idle", __FUNCTION__);
1449 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001450 case STATUS_CONFIGURED:
1451 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 case STATUS_ERROR:
1453 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001454 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 break;
1456 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001457 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 return INVALID_OPERATION;
1459 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001460 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1461 maxExpectedDuration);
1462 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001463 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001464 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001465 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1466 res);
1467 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001468 return res;
1469}
1470
Ruben Brunk183f0562015-08-12 12:55:02 -07001471void Camera3Device::internalUpdateStatusLocked(Status status) {
1472 mStatus = status;
1473 mRecentStatusUpdates.add(mStatus);
1474 mStatusChanged.broadcast();
1475}
1476
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001477// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001478status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001479 if (mRequestThread.get() != nullptr) {
1480 mRequestThread->setPaused(true);
1481 } else {
1482 return NO_INIT;
1483 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001484
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001485 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1486 maxExpectedDuration);
1487 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488 if (res != OK) {
1489 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001490 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 }
1492
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 return res;
1494}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496// Resume after internalPauseAndWaitLocked
1497status_t Camera3Device::internalResumeLocked() {
1498 status_t res;
1499
1500 mRequestThread->setPaused(false);
1501
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001502 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1503 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1505 if (res != OK) {
1506 SET_ERR_L("Can't transition to active in %f seconds!",
1507 kActiveTimeout/1e9);
1508 }
1509 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511}
1512
Ruben Brunk183f0562015-08-12 12:55:02 -07001513status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001515
1516 size_t startIndex = 0;
1517 if (mStatusWaiters == 0) {
1518 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1519 // this status list
1520 mRecentStatusUpdates.clear();
1521 } else {
1522 // If other threads are waiting on updates to this status list, set the position of the
1523 // first element that this list will check rather than clearing the list.
1524 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 }
1526
Ruben Brunk183f0562015-08-12 12:55:02 -07001527 mStatusWaiters++;
1528
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001529 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001530 if (!active && mUseHalBufManager) {
1531 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001532 if (mStatus == STATUS_ACTIVE) {
1533 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001534 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001535 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001536 mRequestBufferSM.onWaitUntilIdle();
1537 }
1538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 bool stateSeen = false;
1540 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001541 if (active == (mStatus == STATUS_ACTIVE)) {
1542 // Desired state is current
1543 break;
1544 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545
1546 res = mStatusChanged.waitRelative(mLock, timeout);
1547 if (res != OK) break;
1548
Ruben Brunk183f0562015-08-12 12:55:02 -07001549 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1550 // transitions.
1551 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1552 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1553 __FUNCTION__);
1554
1555 // Encountered desired state since we began waiting
1556 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001557 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1558 stateSeen = true;
1559 break;
1560 }
1561 }
1562 } while (!stateSeen);
1563
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001564 if (signalPipelineDrain) {
1565 mRequestThread->resetPipelineDrain();
1566 }
1567
Ruben Brunk183f0562015-08-12 12:55:02 -07001568 mStatusWaiters--;
1569
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 return res;
1571}
1572
1573
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001574status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001575 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001576 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001578 if (listener != NULL && mListener != NULL) {
1579 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1580 }
1581 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001582 mRequestThread->setNotificationListener(listener);
1583 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001584
1585 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586}
1587
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001588bool Camera3Device::willNotify3A() {
1589 return false;
1590}
1591
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001592status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001593 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001594 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001596 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001597 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1598 if (st == std::cv_status::timeout) {
1599 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001600 }
1601 }
1602 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603}
1604
Jianing Weicb0652e2014-03-12 18:29:36 -07001605status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001606 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001607 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001609 if (mResultQueue.empty()) {
1610 return NOT_ENOUGH_DATA;
1611 }
1612
Jianing Weicb0652e2014-03-12 18:29:36 -07001613 if (frame == NULL) {
1614 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1615 return BAD_VALUE;
1616 }
1617
1618 CaptureResult &result = *(mResultQueue.begin());
1619 frame->mResultExtras = result.mResultExtras;
1620 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001621 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001622 mResultQueue.erase(mResultQueue.begin());
1623
1624 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625}
1626
1627status_t Camera3Device::triggerAutofocus(uint32_t id) {
1628 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001631 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1632 // Mix-in this trigger into the next request and only the next request.
1633 RequestTrigger trigger[] = {
1634 {
1635 ANDROID_CONTROL_AF_TRIGGER,
1636 ANDROID_CONTROL_AF_TRIGGER_START
1637 },
1638 {
1639 ANDROID_CONTROL_AF_TRIGGER_ID,
1640 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001641 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001642 };
1643
1644 return mRequestThread->queueTrigger(trigger,
1645 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646}
1647
1648status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1649 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001652 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1653 // Mix-in this trigger into the next request and only the next request.
1654 RequestTrigger trigger[] = {
1655 {
1656 ANDROID_CONTROL_AF_TRIGGER,
1657 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1658 },
1659 {
1660 ANDROID_CONTROL_AF_TRIGGER_ID,
1661 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001662 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001663 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001665 return mRequestThread->queueTrigger(trigger,
1666 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001667}
1668
1669status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1670 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001671 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001673 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1674 // Mix-in this trigger into the next request and only the next request.
1675 RequestTrigger trigger[] = {
1676 {
1677 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1678 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1679 },
1680 {
1681 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1682 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001683 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001684 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 return mRequestThread->queueTrigger(trigger,
1687 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001688}
1689
Jianing Weicb0652e2014-03-12 18:29:36 -07001690status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001691 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001692 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001693 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001694
Zhijun He7ef20392014-04-21 16:04:17 -07001695 {
1696 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001697
1698 // b/116514106 "disconnect()" can get called twice for the same device. The
1699 // camera device will not be initialized during the second run.
1700 if (mStatus == STATUS_UNINITIALIZED) {
1701 return OK;
1702 }
1703
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001704 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001705
1706 // Stop session and stream counter
1707 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001708 }
1709
Emilian Peev08dd2452017-04-06 16:55:14 +01001710 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001711}
1712
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001713status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001714 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1715}
1716
1717status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001718 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001719 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001720 Mutex::Autolock il(mInterfaceLock);
1721 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001722
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001723 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1724 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001725 CLOGE("Stream %d does not exist", streamId);
1726 return BAD_VALUE;
1727 }
1728
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001729 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001730 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001731 return BAD_VALUE;
1732 }
1733
1734 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001735 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001736 return BAD_VALUE;
1737 }
1738
Ruben Brunkc78ac262015-08-13 17:58:46 -07001739 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740}
1741
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001742status_t Camera3Device::tearDown(int streamId) {
1743 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001744 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001745 Mutex::Autolock il(mInterfaceLock);
1746 Mutex::Autolock l(mLock);
1747
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001748 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1749 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001750 CLOGE("Stream %d does not exist", streamId);
1751 return BAD_VALUE;
1752 }
1753
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001754 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1755 CLOGE("Stream %d is a target of a in-progress request", streamId);
1756 return BAD_VALUE;
1757 }
1758
1759 return stream->tearDown();
1760}
1761
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001762status_t Camera3Device::addBufferListenerForStream(int streamId,
1763 wp<Camera3StreamBufferListener> listener) {
1764 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001765 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001766 Mutex::Autolock il(mInterfaceLock);
1767 Mutex::Autolock l(mLock);
1768
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001769 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1770 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001771 CLOGE("Stream %d does not exist", streamId);
1772 return BAD_VALUE;
1773 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001774 stream->addBufferListener(listener);
1775
1776 return OK;
1777}
1778
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001779/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780 * Methods called by subclasses
1781 */
1782
1783void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001784 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001785 std::vector<int> streamIds;
1786 std::vector<hardware::CameraStreamStats> streamStats;
1787
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001788 {
1789 // Need mLock to safely update state and synchronize to current
1790 // state of methods in flight.
1791 Mutex::Autolock l(mLock);
1792 // We can get various system-idle notices from the status tracker
1793 // while starting up. Only care about them if we've actually sent
1794 // in some requests recently.
1795 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1796 return;
1797 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001798 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1799 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001800 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001801
1802 // Skip notifying listener if we're doing some user-transparent
1803 // state changes
1804 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001805
1806 // Populate stream statistics in case of Idle
1807 if (idle) {
1808 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1809 auto stream = mOutputStreams[i];
1810 if (stream.get() == nullptr) continue;
1811 streamIds.push_back(stream->getId());
1812 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1813 int64_t usage = 0LL;
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001814 int streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001815 if (camera3Stream != nullptr) {
1816 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001817 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001818 }
1819 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1820 stream->getFormat(), stream->getDataSpace(), usage,
1821 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001822 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001823 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001824 }
1825 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001826 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001827
1828 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001830 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001831 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001833 status_t res = OK;
1834 if (listener != nullptr) {
1835 if (idle) {
1836 // Get session stats from the builder, and notify the listener.
1837 int64_t requestCount, resultErrorCount;
1838 bool deviceError;
1839 std::map<int, StreamStats> streamStatsMap;
1840 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1841 &deviceError, &streamStatsMap);
1842 for (size_t i = 0; i < streamIds.size(); i++) {
1843 int streamId = streamIds[i];
1844 auto stats = streamStatsMap.find(streamId);
1845 if (stats != streamStatsMap.end()) {
1846 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1847 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1848 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1849 streamStats[i].mHistogramType =
1850 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1851 streamStats[i].mHistogramBins.assign(
1852 stats->second.mCaptureLatencyBins.begin(),
1853 stats->second.mCaptureLatencyBins.end());
1854 streamStats[i].mHistogramCounts.assign(
1855 stats->second.mCaptureLatencyHistogram.begin(),
1856 stats->second.mCaptureLatencyHistogram.end());
1857 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001858 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001859 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1860 } else {
1861 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001862 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001863 }
1864 if (res != OK) {
1865 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1866 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 }
1868}
1869
Shuzhen Wang758c2152017-01-10 18:26:18 -08001870status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001871 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001872 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001873 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1874 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001875
1876 if (surfaceIds == nullptr) {
1877 return BAD_VALUE;
1878 }
1879
Zhijun He5d677d12016-05-29 16:52:39 -07001880 Mutex::Autolock il(mInterfaceLock);
1881 Mutex::Autolock l(mLock);
1882
Shuzhen Wang758c2152017-01-10 18:26:18 -08001883 if (consumers.size() == 0) {
1884 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001885 return BAD_VALUE;
1886 }
1887
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001888 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1889 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001890 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001891 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001892 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001893
1894 // isConsumerConfigurationDeferred will be off after setConsumers
1895 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001896 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001897 if (res != OK) {
1898 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1899 return res;
1900 }
1901
Emilian Peev40ead602017-09-26 15:46:36 +01001902 for (auto &consumer : consumers) {
1903 int id = stream->getSurfaceId(consumer);
1904 if (id < 0) {
1905 CLOGE("Invalid surface id!");
1906 return BAD_VALUE;
1907 }
1908 surfaceIds->push_back(id);
1909 }
1910
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001911 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001912 if (!stream->isConfiguring()) {
1913 CLOGE("Stream %d was already fully configured.", streamId);
1914 return INVALID_OPERATION;
1915 }
Zhijun He5d677d12016-05-29 16:52:39 -07001916
Shuzhen Wang0129d522016-10-30 22:43:41 -07001917 res = stream->finishConfiguration();
1918 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001919 // If finishConfiguration fails due to abandoned surface, do not set
1920 // device to error state.
1921 bool isSurfaceAbandoned =
1922 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1923 if (!isSurfaceAbandoned) {
1924 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1925 stream->getId(), strerror(-res), res);
1926 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001927 return res;
1928 }
Zhijun He5d677d12016-05-29 16:52:39 -07001929 }
1930
1931 return OK;
1932}
1933
Emilian Peev40ead602017-09-26 15:46:36 +01001934status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1935 const std::vector<OutputStreamInfo> &outputInfo,
1936 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1937 Mutex::Autolock il(mInterfaceLock);
1938 Mutex::Autolock l(mLock);
1939
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001940 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1941 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001942 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001943 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001944 }
1945
1946 for (const auto &it : removedSurfaceIds) {
1947 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1948 CLOGE("Shared surface still part of a pending request!");
1949 return -EBUSY;
1950 }
1951 }
1952
Emilian Peev40ead602017-09-26 15:46:36 +01001953 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1954 if (res != OK) {
1955 CLOGE("Stream %d failed to update stream (error %d %s) ",
1956 streamId, res, strerror(-res));
1957 if (res == UNKNOWN_ERROR) {
1958 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1959 __FUNCTION__);
1960 }
1961 return res;
1962 }
1963
1964 return res;
1965}
1966
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001967status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1968 Mutex::Autolock il(mInterfaceLock);
1969 Mutex::Autolock l(mLock);
1970
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1972 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001973 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1974 return BAD_VALUE;
1975 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001976
1977 if (dropping) {
1978 mSessionStatsBuilder.stopCounter(streamId);
1979 } else {
1980 mSessionStatsBuilder.startCounter(streamId);
1981 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001982 return stream->dropBuffers(dropping);
1983}
1984
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001985/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986 * Camera3Device private methods
1987 */
1988
1989sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00001990 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001991 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001993 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00001994 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001995
1996 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00001997 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998 if (inputStreams.count > 0) {
1999 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002000 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002001 CLOGE("Request references unknown input stream %d",
2002 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002003 return NULL;
2004 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002005
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002006 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002007 SET_ERR_L("%s: input stream %d is not configured!",
2008 __FUNCTION__, mInputStream->getId());
2009 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002010 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002011 // Check if stream prepare is blocking requests.
2012 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002013 CLOGE("Request references an input stream that's being prepared!");
2014 return NULL;
2015 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016
2017 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002018 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019 }
2020
2021 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002022 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002023 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002024 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002025 return NULL;
2026 }
2027
2028 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002029 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2030 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002031 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002032 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002033 return NULL;
2034 }
Zhijun He5d677d12016-05-29 16:52:39 -07002035 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002036 auto iter = surfaceMap.find(streams.data.i32[i]);
2037 if (iter != surfaceMap.end()) {
2038 const std::vector<size_t>& surfaces = iter->second;
2039 for (const auto& surface : surfaces) {
2040 if (stream->isConsumerConfigurationDeferred(surface)) {
2041 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2042 "due to deferred consumer", stream->getId(), surface);
2043 return NULL;
2044 }
2045 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002046 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002047 }
2048
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002050 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2051 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002053 // Check if stream prepare is blocking requests.
2054 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002055 CLOGE("Request references an output stream that's being prepared!");
2056 return NULL;
2057 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058
2059 newRequest->mOutputStreams.push(stream);
2060 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002061 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002062 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002064 auto rotateAndCropEntry =
2065 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2066 if (rotateAndCropEntry.count > 0 &&
2067 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2068 newRequest->mRotateAndCropAuto = true;
2069 } else {
2070 newRequest->mRotateAndCropAuto = false;
2071 }
2072
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002073 auto zoomRatioEntry =
2074 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2075 if (zoomRatioEntry.count > 0 &&
2076 zoomRatioEntry.data.f[0] == 1.0f) {
2077 newRequest->mZoomRatioIs1x = true;
2078 } else {
2079 newRequest->mZoomRatioIs1x = false;
2080 }
2081
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002082 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002083 for (auto& settings : newRequest->mSettingsList) {
2084 auto testPatternModeEntry =
2085 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2086 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2087 testPatternModeEntry.data.i32[0] :
2088 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002089
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002090 auto testPatternDataEntry =
2091 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2092 if (testPatternDataEntry.count >= 4) {
2093 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2094 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2095 } else {
2096 settings.mOriginalTestPatternData[0] = 0;
2097 settings.mOriginalTestPatternData[1] = 0;
2098 settings.mOriginalTestPatternData[2] = 0;
2099 settings.mOriginalTestPatternData[3] = 0;
2100 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002101 }
2102 }
2103
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002105}
2106
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002107void Camera3Device::cancelStreamsConfigurationLocked() {
2108 int res = OK;
2109 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2110 res = mInputStream->cancelConfiguration();
2111 if (res != OK) {
2112 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2113 mInputStream->getId(), strerror(-res), res);
2114 }
2115 }
2116
2117 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002118 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002119 if (outputStream->isConfiguring()) {
2120 res = outputStream->cancelConfiguration();
2121 if (res != OK) {
2122 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2123 outputStream->getId(), strerror(-res), res);
2124 }
2125 }
2126 }
2127
2128 // Return state to that at start of call, so that future configures
2129 // properly clean things up
2130 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2131 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002132
2133 res = mPreparerThread->resume();
2134 if (res != OK) {
2135 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2136 }
2137}
2138
Emilian Peev0d0191e2020-04-21 17:01:18 -07002139bool Camera3Device::checkAbandonedStreamsLocked() {
2140 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2141 return true;
2142 }
2143
2144 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2145 auto stream = mOutputStreams[i];
2146 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2147 return true;
2148 }
2149 }
2150
2151 return false;
2152}
2153
Emilian Peev3bead5f2020-05-28 17:29:08 -07002154bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002155 ATRACE_CALL();
2156 bool ret = false;
2157
Shuzhen Wang316781a2020-08-18 18:11:01 -07002158 nsecs_t startTime = systemTime();
2159
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002160 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002161 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2162
2163 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002164 if (checkAbandonedStreamsLocked()) {
2165 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2166 __FUNCTION__);
2167 return true;
2168 }
2169
Emilian Peev3bead5f2020-05-28 17:29:08 -07002170 status_t rc = NO_ERROR;
2171 bool markClientActive = false;
2172 if (mStatus == STATUS_ACTIVE) {
2173 markClientActive = true;
2174 mPauseStateNotify = true;
2175 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2176
2177 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2178 }
2179
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002180 if (rc == NO_ERROR) {
2181 mNeedConfig = true;
2182 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2183 if (rc == NO_ERROR) {
2184 ret = true;
2185 mPauseStateNotify = false;
2186 //Moving to active state while holding 'mLock' is important.
2187 //There could be pending calls to 'create-/deleteStream' which
2188 //will trigger another stream configuration while the already
2189 //present streams end up with outstanding buffers that will
2190 //not get drained.
2191 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002192 } else if (rc == DEAD_OBJECT) {
2193 // DEAD_OBJECT can be returned if either the consumer surface is
2194 // abandoned, or the HAL has died.
2195 // - If the HAL has died, configureStreamsLocked call will set
2196 // device to error state,
2197 // - If surface is abandoned, we should not set device to error
2198 // state.
2199 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002200 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002201 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002202 }
2203 } else {
2204 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2205 }
2206
Shuzhen Wang316781a2020-08-18 18:11:01 -07002207 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2208 ns2ms(systemTime() - startTime));
2209
Emilian Peev3bead5f2020-05-28 17:29:08 -07002210 if (markClientActive) {
2211 mStatusTracker->markComponentActive(clientStatusId);
2212 }
2213
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002214 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002215}
2216
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002217status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002218 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002219 ATRACE_CALL();
2220 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002221
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002222 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002223 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224 return INVALID_OPERATION;
2225 }
2226
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002227 if (operatingMode < 0) {
2228 CLOGE("Invalid operating mode: %d", operatingMode);
2229 return BAD_VALUE;
2230 }
2231
2232 bool isConstrainedHighSpeed =
2233 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2234 operatingMode;
2235
2236 if (mOperatingMode != operatingMode) {
2237 mNeedConfig = true;
2238 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2239 mOperatingMode = operatingMode;
2240 }
2241
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002242 // In case called from configureStreams, abort queued input buffers not belonging to
2243 // any pending requests.
2244 if (mInputStream != NULL && notifyRequestThread) {
2245 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002246 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002247 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002248 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002249 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002250 if (res != OK) {
2251 // Exhausted acquiring all input buffers.
2252 break;
2253 }
2254
Emilian Peevf4816702020-04-03 15:44:51 -07002255 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002256 res = mInputStream->returnInputBuffer(inputBuffer);
2257 if (res != OK) {
2258 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2259 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2260 }
2261 }
2262 }
2263
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002264 if (!mNeedConfig) {
2265 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2266 return OK;
2267 }
2268
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002269 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002270 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002271 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2272 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002273 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002274 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002275 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002276 }
2277
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002278 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002279 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002280
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002281 mPreparerThread->pause();
2282
Emilian Peevf4816702020-04-03 15:44:51 -07002283 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002284 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002285 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002286 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287
Emilian Peevf4816702020-04-03 15:44:51 -07002288 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002290 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002291
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292
2293 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002294 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295 inputStream = mInputStream->startConfiguration();
2296 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002297 CLOGE("Can't start input stream configuration");
2298 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299 return INVALID_OPERATION;
2300 }
2301 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002302
2303 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304 }
2305
Shuzhen Wang99080502021-03-07 21:08:20 -08002306 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002307 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002309
2310 // Don't configure bidi streams twice, nor add them twice to the list
2311 if (mOutputStreams[i].get() ==
2312 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2313
2314 config.num_streams--;
2315 continue;
2316 }
2317
Emilian Peevf4816702020-04-03 15:44:51 -07002318 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002319 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002321 CLOGE("Can't start output stream configuration");
2322 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323 return INVALID_OPERATION;
2324 }
2325 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002326
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002327 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002328 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2329 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002330 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2331 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002332 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2333 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002334 } else if (outputStream->data_space ==
2335 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2336 bufferSizes[k] = outputStream->width * outputStream->height;
2337 } else {
2338 ALOGW("%s: Blob dataSpace %d not supported",
2339 __FUNCTION__, outputStream->data_space);
2340 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002341 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002342
2343 if (mOutputStreams[i]->isMultiResolution()) {
2344 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2345 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2346 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2347 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002348
2349 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2350 composerSurfacePresent = true;
2351 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002352 }
2353
2354 config.streams = streams.editArray();
2355
2356 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002357 // max_buffers, usage, and priv fields, as well as data_space and format
2358 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002359
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002360 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002361 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002362 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002364 if (res == BAD_VALUE) {
2365 // HAL rejected this set of streams as unsupported, clean up config
2366 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002367 CLOGE("Set of requested inputs/outputs not supported by HAL");
2368 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002369 return BAD_VALUE;
2370 } else if (res != OK) {
2371 // Some other kind of error from configure_streams - this is not
2372 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002373 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2374 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375 return res;
2376 }
2377
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002378 // Finish all stream configuration immediately.
2379 // TODO: Try to relax this later back to lazy completion, which should be
2380 // faster
2381
Igor Murashkin073f8572013-05-02 14:59:28 -07002382 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002383 bool streamReConfigured = false;
2384 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002385 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002386 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002387 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002388 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002389 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2390 return DEAD_OBJECT;
2391 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002392 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002393 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002394 if (streamReConfigured) {
2395 mInterface->onStreamReConfigured(mInputStream->getId());
2396 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002397 }
2398
2399 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002400 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002401 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002402 bool streamReConfigured = false;
2403 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002404 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002405 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002406 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002407 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002408 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2409 return DEAD_OBJECT;
2410 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002411 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002412 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002413 if (streamReConfigured) {
2414 mInterface->onStreamReConfigured(outputStream->getId());
2415 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002416 }
2417 }
2418
Emilian Peeve23f1d92021-09-20 14:56:01 -07002419 mRequestThread->setComposerSurface(composerSurfacePresent);
2420
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002421 // Request thread needs to know to avoid using repeat-last-settings protocol
2422 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002423 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002424 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2425 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002426 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427
Zhijun He90f7c372016-08-16 16:19:43 -07002428 char value[PROPERTY_VALUE_MAX];
2429 property_get("camera.fifo.disable", value, "0");
2430 int32_t disableFifo = atoi(value);
2431 if (disableFifo != 1) {
2432 // Boost priority of request thread to SCHED_FIFO.
2433 pid_t requestThreadTid = mRequestThread->getTid();
2434 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002435 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002436 if (res != OK) {
2437 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2438 strerror(-res), res);
2439 } else {
2440 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2441 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002442 }
2443
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002444 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002445 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2446 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2447 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2448 sessionParams.unlock(newSessionParams);
2449 mSessionParams.unlock(currentSessionParams);
2450 if (updateSessionParams) {
2451 mSessionParams = sessionParams;
2452 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002453
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002454 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002456 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002457 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002458
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002459 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002460
Zhijun He0a210512014-07-24 13:45:15 -07002461 // tear down the deleted streams after configure streams.
2462 mDeletedStreams.clear();
2463
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002464 auto rc = mPreparerThread->resume();
2465 if (rc != OK) {
2466 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2467 return rc;
2468 }
2469
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002470 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002471 mRequestBufferSM.onStreamsConfigured();
2472 }
2473
Cliff Wu3b268182021-07-06 15:44:43 +08002474 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002475 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002476 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002477 // configure the injection streams.
2478 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002479 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002480 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2481 res = mInjectionMethods->injectCamera(config, bufferSizes);
2482 if (res != OK) {
2483 ALOGE("Can't finish inject camera process!");
2484 return res;
2485 }
Cliff Wu3b268182021-07-06 15:44:43 +08002486 } else {
2487 // First run configureStreamsLocked() and then call injectCamera() case:
2488 // If the stream configuration has been completed and camera deive is active, but the
2489 // injection camera has not been injected yet, we need to store the stream configuration of
2490 // the internal camera (because the stream configuration of the injection camera is based
2491 // on the internal camera). When injecting occurs later, this configuration can be used by
2492 // the injection camera.
2493 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2494 " injection camera has not been injected yet.", __FUNCTION__);
2495 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002496 }
2497
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002498 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002499}
2500
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002501status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002502 ATRACE_CALL();
2503 status_t res;
2504
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002505 if (mFakeStreamId != NO_STREAM) {
2506 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002507 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002508 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002509 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002510 return INVALID_OPERATION;
2511 }
2512
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002513 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002514
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002515 sp<Camera3OutputStreamInterface> fakeStream =
2516 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002517
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002518 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002519 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002520 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002521 return res;
2522 }
2523
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002524 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002525 mNextStreamId++;
2526
2527 return OK;
2528}
2529
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002530status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002531 ATRACE_CALL();
2532 status_t res;
2533
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002534 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002535 if (mOutputStreams.size() == 1) return OK;
2536
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002537 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002538
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002539 // Ok, have a fake stream and there's at least one other output stream,
2540 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002541
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002542 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002543 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002544 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002545 return INVALID_OPERATION;
2546 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002547 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548
2549 // Free up the stream endpoint so that it can be used by some other stream
2550 res = deletedStream->disconnect();
2551 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002552 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002553 // fall through since we want to still list the stream as deleted.
2554 }
2555 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002556 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002557
2558 return res;
2559}
2560
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002561void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002562 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002563 Mutex::Autolock l(mLock);
2564 va_list args;
2565 va_start(args, fmt);
2566
2567 setErrorStateLockedV(fmt, args);
2568
2569 va_end(args);
2570}
2571
2572void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002573 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002574 Mutex::Autolock l(mLock);
2575 setErrorStateLockedV(fmt, args);
2576}
2577
2578void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2579 va_list args;
2580 va_start(args, fmt);
2581
2582 setErrorStateLockedV(fmt, args);
2583
2584 va_end(args);
2585}
2586
2587void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002588 // Print out all error messages to log
2589 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002590 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002591
2592 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002593 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002594
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002595 mErrorCause = errorCause;
2596
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002597 if (mRequestThread != nullptr) {
2598 mRequestThread->setPaused(true);
2599 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002600 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002601
2602 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002603 sp<NotificationListener> listener = mListener.promote();
2604 if (listener != NULL) {
2605 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002606 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002607 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002608 }
2609
2610 // Save stack trace. View by dumping it later.
2611 CameraTraces::saveTrace();
2612 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002613}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614
2615/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002616 * In-flight request management
2617 */
2618
Jianing Weicb0652e2014-03-12 18:29:36 -07002619status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002620 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002621 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002622 const std::set<std::set<String8>>& physicalCameraIds,
2623 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2624 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002625 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002626 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002627 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002628
2629 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002630 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002631 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002632 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002633 if (res < 0) return res;
2634
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002635 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002636 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2637 // avoid a deadlock during reprocess requests.
2638 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002639 if (mStatusTracker != nullptr) {
2640 mStatusTracker->markComponentActive(mInFlightStatusId);
2641 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002642 }
2643
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002644 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002645 return OK;
2646}
2647
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002648void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002649 // Indicate idle inFlightMap to the status tracker
2650 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002651 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002652 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2653 // avoid a deadlock during reprocess requests.
2654 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002655 if (mStatusTracker != nullptr) {
2656 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2657 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002658 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002659 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002660}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002661
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002662void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002663 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002664 // something has likely gone wrong. This might still be legit only if application send in
2665 // a long burst of long exposure requests.
2666 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2667 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2668 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2669 mInFlightMap.size(), mExpectedInflightDuration);
2670 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2671 kInFlightWarnLimitHighSpeed) {
2672 CLOGW("In-flight list too large for high speed configuration: %zu,"
2673 "total inflight duration %" PRIu64,
2674 mInFlightMap.size(), mExpectedInflightDuration);
2675 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002676 }
2677}
2678
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002679void Camera3Device::onInflightMapFlushedLocked() {
2680 mExpectedInflightDuration = 0;
2681}
2682
2683void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002684 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002685 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2686 mInFlightMap.removeItemsAt(idx, 1);
2687
2688 onInflightEntryRemovedLocked(duration);
2689}
2690
2691
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002692void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002693 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002694 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002695 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002696 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002697 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002698 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002699
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002700 FlushInflightReqStates states {
2701 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002702 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002703
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002704 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002705}
2706
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002707CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002708 ALOGV("%s", __FUNCTION__);
2709
Igor Murashkin1e479c02013-09-06 16:55:14 -07002710 CameraMetadata retVal;
2711
2712 if (mRequestThread != NULL) {
2713 retVal = mRequestThread->getLatestRequest();
2714 }
2715
Igor Murashkin1e479c02013-09-06 16:55:14 -07002716 return retVal;
2717}
2718
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002719void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002720 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002721 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002722 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2723 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002724
2725 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002726 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002727}
2728
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002729void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002730 std::vector<native_handle_t*> *handles, bool closeFd) {
2731 if (handles == nullptr) {
2732 return;
2733 }
2734 if (closeFd) {
2735 for (auto& handle : *handles) {
2736 native_handle_close(handle);
2737 }
2738 }
2739 for (auto& handle : *handles) {
2740 native_handle_delete(handle);
2741 }
2742 handles->clear();
2743 return;
2744}
2745
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002746/**
2747 * HalInterface inner class methods
2748 */
2749
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002750void Camera3Device::HalInterface::getInflightBufferKeys(
2751 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002752 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002753 return;
2754}
2755
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002756void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2757 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002758 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002759 return;
2760}
2761
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002762bool Camera3Device::HalInterface::verifyBufferIds(
2763 int32_t streamId, std::vector<uint64_t>& bufIds) {
2764 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002765}
2766
2767status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002768 int32_t frameNumber, int32_t streamId,
2769 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002770 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002771}
2772
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002773status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002774 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002775 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002776}
2777
2778// Find and pop a buffer_handle_t based on bufferId
2779status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002780 uint64_t bufferId,
2781 /*out*/ buffer_handle_t** buffer,
2782 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002783 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002784}
2785
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002786std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2787 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002788 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002789}
2790
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002791uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2792 const native_handle_t* handle) {
2793 return mBufferRecords.removeOneBufferCache(streamId, handle);
2794}
2795
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002796void Camera3Device::HalInterface::onBufferFreed(
2797 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002798 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2799 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2800 if (bufferId != BUFFER_ID_NO_BUFFER) {
2801 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002802 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002803}
2804
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002805void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002806 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2807 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2808 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002809 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2810 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002811}
2812
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002813/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002814 * RequestThread inner class methods
2815 */
2816
2817Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002818 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002819 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002820 bool useHalBufManager,
2821 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002822 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002823 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002824 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002825 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002826 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002827 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002828 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002829 mReconfigured(false),
2830 mDoPause(false),
2831 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002832 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002833 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002834 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002835 mCurrentAfTriggerId(0),
2836 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002837 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002838 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002839 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002840 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002841 mRepeatingLastFrameNumber(
2842 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002843 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002844 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002845 mRequestLatency(kRequestLatencyBinSize),
2846 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002847 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002848 mUseHalBufManager(useHalBufManager),
2849 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002850 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002851}
2852
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002853Camera3Device::RequestThread::~RequestThread() {}
2854
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002855void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002856 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002857 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858 Mutex::Autolock l(mRequestLock);
2859 mListener = listener;
2860}
2861
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002862void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002863 const CameraMetadata& sessionParams,
2864 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002865 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002866 Mutex::Autolock l(mRequestLock);
2867 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002868 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002869 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002870 // Prepare video stream for high speed recording.
2871 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002872 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002873}
2874
Jianing Wei90e59c92014-03-12 18:29:36 -07002875status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002876 List<sp<CaptureRequest> > &requests,
2877 /*out*/
2878 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002879 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002880 Mutex::Autolock l(mRequestLock);
2881 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2882 ++it) {
2883 mRequestQueue.push_back(*it);
2884 }
2885
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002886 if (lastFrameNumber != NULL) {
2887 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2888 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2889 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2890 *lastFrameNumber);
2891 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002892
Jianing Wei90e59c92014-03-12 18:29:36 -07002893 unpauseForNewRequests();
2894
2895 return OK;
2896}
2897
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002898
2899status_t Camera3Device::RequestThread::queueTrigger(
2900 RequestTrigger trigger[],
2901 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002902 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002903 Mutex::Autolock l(mTriggerMutex);
2904 status_t ret;
2905
2906 for (size_t i = 0; i < count; ++i) {
2907 ret = queueTriggerLocked(trigger[i]);
2908
2909 if (ret != OK) {
2910 return ret;
2911 }
2912 }
2913
2914 return OK;
2915}
2916
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002917const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2918 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002919 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002920 if (d != nullptr) return d->mId;
2921 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002922}
2923
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002924status_t Camera3Device::RequestThread::queueTriggerLocked(
2925 RequestTrigger trigger) {
2926
2927 uint32_t tag = trigger.metadataTag;
2928 ssize_t index = mTriggerMap.indexOfKey(tag);
2929
2930 switch (trigger.getTagType()) {
2931 case TYPE_BYTE:
2932 // fall-through
2933 case TYPE_INT32:
2934 break;
2935 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002936 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2937 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002938 return INVALID_OPERATION;
2939 }
2940
2941 /**
2942 * Collect only the latest trigger, since we only have 1 field
2943 * in the request settings per trigger tag, and can't send more than 1
2944 * trigger per request.
2945 */
2946 if (index != NAME_NOT_FOUND) {
2947 mTriggerMap.editValueAt(index) = trigger;
2948 } else {
2949 mTriggerMap.add(tag, trigger);
2950 }
2951
2952 return OK;
2953}
2954
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002956 const RequestList &requests,
2957 /*out*/
2958 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002959 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002960 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002961 if (lastFrameNumber != NULL) {
2962 *lastFrameNumber = mRepeatingLastFrameNumber;
2963 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002964 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002965 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002966 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2967 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002968
2969 unpauseForNewRequests();
2970
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002971 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002972 return OK;
2973}
2974
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002975bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002976 if (mRepeatingRequests.empty()) {
2977 return false;
2978 }
2979 int32_t requestId = requestIn->mResultExtras.requestId;
2980 const RequestList &repeatRequests = mRepeatingRequests;
2981 // All repeating requests are guaranteed to have same id so only check first quest
2982 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2983 return (firstRequest->mResultExtras.requestId == requestId);
2984}
2985
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002986status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002987 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002988 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07002989 return clearRepeatingRequestsLocked(lastFrameNumber);
2990
2991}
2992
2993status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08002994 std::vector<int32_t> streamIds;
2995 for (const auto& request : mRepeatingRequests) {
2996 for (const auto& stream : request->mOutputStreams) {
2997 streamIds.push_back(stream->getId());
2998 }
2999 }
3000
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003001 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003002 if (lastFrameNumber != NULL) {
3003 *lastFrameNumber = mRepeatingLastFrameNumber;
3004 }
Emilian Peev2295df72021-11-12 18:14:10 -08003005
3006 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3007
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003008 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003009 return OK;
3010}
3011
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003012status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003013 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003014 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003015 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003016 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003017
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003018 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003019
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003020 // Send errors for all requests pending in the request queue, including
3021 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003022 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003023 if (listener != NULL) {
3024 for (RequestList::iterator it = mRequestQueue.begin();
3025 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003026 // Abort the input buffers for reprocess requests.
3027 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003028 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003029 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003030 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003031 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003032 if (res != OK) {
3033 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3034 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3035 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003036 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003037 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3038 if (res != OK) {
3039 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3040 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3041 }
3042 }
3043 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003044 // Set the frame number this request would have had, if it
3045 // had been submitted; this frame number will not be reused.
3046 // The requestId and burstId fields were set when the request was
3047 // submitted originally (in convertMetadataListToRequestListLocked)
3048 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003050 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003051 }
3052 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003053 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003054
3055 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003056 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003057 if (lastFrameNumber != NULL) {
3058 *lastFrameNumber = mRepeatingLastFrameNumber;
3059 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003060 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003061 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003062 return OK;
3063}
3064
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003065status_t Camera3Device::RequestThread::flush() {
3066 ATRACE_CALL();
3067 Mutex::Autolock l(mFlushLock);
3068
Emilian Peev08dd2452017-04-06 16:55:14 +01003069 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003070}
3071
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003072void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003073 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003074 Mutex::Autolock l(mPauseLock);
3075 mDoPause = paused;
3076 mDoPauseSignal.signal();
3077}
3078
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003079status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3080 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003081 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003082 Mutex::Autolock l(mLatestRequestMutex);
3083 status_t res;
3084 while (mLatestRequestId != requestId) {
3085 nsecs_t startTime = systemTime();
3086
3087 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3088 if (res != OK) return res;
3089
3090 timeout -= (systemTime() - startTime);
3091 }
3092
3093 return OK;
3094}
3095
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003096void Camera3Device::RequestThread::requestExit() {
3097 // Call parent to set up shutdown
3098 Thread::requestExit();
3099 // The exit from any possible waits
3100 mDoPauseSignal.signal();
3101 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003102
3103 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3104 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003105}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003106
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003107void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003108 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003109 bool surfaceAbandoned = false;
3110 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003111 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003112 {
3113 Mutex::Autolock l(mRequestLock);
3114 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3115 // repeating requests.
3116 for (const auto& request : mRepeatingRequests) {
3117 for (const auto& s : request->mOutputStreams) {
3118 if (s->isAbandoned()) {
3119 surfaceAbandoned = true;
3120 clearRepeatingRequestsLocked(&lastFrameNumber);
3121 break;
3122 }
3123 }
3124 if (surfaceAbandoned) {
3125 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003126 }
3127 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003128 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003129 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003130
3131 if (listener != NULL && surfaceAbandoned) {
3132 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003133 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003134}
3135
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003136bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003137 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003138 status_t res;
3139 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003140 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003141 uint32_t numRequestProcessed = 0;
3142 for (size_t i = 0; i < batchSize; i++) {
3143 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003144 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003145 }
3146
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003147 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3148
3149 bool triggerRemoveFailed = false;
3150 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3151 for (size_t i = 0; i < numRequestProcessed; i++) {
3152 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3153 nextRequest.submitted = true;
3154
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003155 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003156
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003157 if (!triggerRemoveFailed) {
3158 // Remove any previously queued triggers (after unlock)
3159 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3160 if (removeTriggerRes != OK) {
3161 triggerRemoveFailed = true;
3162 triggerFailedRequest = nextRequest;
3163 }
3164 }
3165 }
3166
3167 if (triggerRemoveFailed) {
3168 SET_ERR("RequestThread: Unable to remove triggers "
3169 "(capture request %d, HAL device: %s (%d)",
3170 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3171 cleanUpFailedRequests(/*sendRequestError*/ false);
3172 return false;
3173 }
3174
3175 if (res != OK) {
3176 // Should only get a failure here for malformed requests or device-level
3177 // errors, so consider all errors fatal. Bad metadata failures should
3178 // come through notify.
3179 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3180 mNextRequests[numRequestProcessed].halRequest.frame_number,
3181 strerror(-res), res);
3182 cleanUpFailedRequests(/*sendRequestError*/ false);
3183 return false;
3184 }
3185 return true;
3186}
3187
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003188nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3189 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3190 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3191 find_camera_metadata_ro_entry(request,
3192 ANDROID_CONTROL_AE_MODE,
3193 &e);
3194 if (e.count == 0) return maxExpectedDuration;
3195
3196 switch (e.data.u8[0]) {
3197 case ANDROID_CONTROL_AE_MODE_OFF:
3198 find_camera_metadata_ro_entry(request,
3199 ANDROID_SENSOR_EXPOSURE_TIME,
3200 &e);
3201 if (e.count > 0) {
3202 maxExpectedDuration = e.data.i64[0];
3203 }
3204 find_camera_metadata_ro_entry(request,
3205 ANDROID_SENSOR_FRAME_DURATION,
3206 &e);
3207 if (e.count > 0) {
3208 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3209 }
3210 break;
3211 default:
3212 find_camera_metadata_ro_entry(request,
3213 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3214 &e);
3215 if (e.count > 1) {
3216 maxExpectedDuration = 1e9 / e.data.u8[0];
3217 }
3218 break;
3219 }
3220
3221 return maxExpectedDuration;
3222}
3223
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003224bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3225 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3226 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3227 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3228 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3229 return true;
3230 }
3231
3232 return false;
3233}
3234
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003235void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3236 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003237 camera_capture_request_t& halRequest = nextRequest.halRequest;
3238 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003239 Mutex::Autolock al(mLatestRequestMutex);
3240
Shuzhen Wang83bff122020-11-20 15:51:39 -08003241 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003242 mLatestRequest.acquire(cloned);
3243
3244 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003245 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3246 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3247 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003248 CameraMetadata(cloned));
3249 }
3250
3251 sp<Camera3Device> parent = mParent.promote();
3252 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003253 int32_t inputStreamId = -1;
3254 if (halRequest.input_buffer != nullptr) {
3255 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3256 }
3257
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003258 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003259 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003260 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3261 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003262 }
3263 }
3264
Shuzhen Wang83bff122020-11-20 15:51:39 -08003265 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003266 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003267 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003268 }
3269
Shuzhen Wang83bff122020-11-20 15:51:39 -08003270 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003271}
3272
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003273bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3274 ATRACE_CALL();
3275 bool updatesDetected = false;
3276
Emilian Peev4ec17882019-01-24 17:16:58 -08003277 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003278 for (auto tag : mSessionParamKeys) {
3279 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003280 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003281
3282 if (entry.count > 0) {
3283 bool isDifferent = false;
3284 if (lastEntry.count > 0) {
3285 // Have a last value, compare to see if changed
3286 if (lastEntry.type == entry.type &&
3287 lastEntry.count == entry.count) {
3288 // Same type and count, compare values
3289 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3290 size_t entryBytes = bytesPerValue * lastEntry.count;
3291 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3292 if (cmp != 0) {
3293 isDifferent = true;
3294 }
3295 } else {
3296 // Count or type has changed
3297 isDifferent = true;
3298 }
3299 } else {
3300 // No last entry, so always consider to be different
3301 isDifferent = true;
3302 }
3303
3304 if (isDifferent) {
3305 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003306 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3307 updatesDetected = true;
3308 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003309 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003310 }
3311 } else if (lastEntry.count > 0) {
3312 // Value has been removed
3313 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003314 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003315 updatesDetected = true;
3316 }
3317 }
3318
Emilian Peev4ec17882019-01-24 17:16:58 -08003319 bool reconfigureRequired;
3320 if (updatesDetected) {
3321 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3322 updatedParams);
3323 mLatestSessionParams = updatedParams;
3324 } else {
3325 reconfigureRequired = false;
3326 }
3327
3328 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003329}
3330
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003331bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003332 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003333 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003334 // Any function called from threadLoop() must not hold mInterfaceLock since
3335 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3336 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003337
3338 // Handle paused state.
3339 if (waitIfPaused()) {
3340 return true;
3341 }
3342
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003343 // Wait for the next batch of requests.
3344 waitForNextRequestBatch();
3345 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003346 return true;
3347 }
3348
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003349 // Get the latest request ID, if any
3350 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003351 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003352 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003353 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003354 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003355 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003356 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3357 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003358 }
3359
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003360 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3361 // or a single request from streaming or burst. In either case the first element
3362 // should contain the latest camera settings that we need to check for any session
3363 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003364 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003365 res = OK;
3366
3367 //Input stream buffers are already acquired at this point so an input stream
3368 //will not be able to move to idle state unless we force it.
3369 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3370 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3371 if (res != OK) {
3372 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3373 cleanUpFailedRequests(/*sendRequestError*/ false);
3374 return false;
3375 }
3376 }
3377
3378 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003379 sp<Camera3Device> parent = mParent.promote();
3380 if (parent != nullptr) {
3381 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003382 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003383 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003384
3385 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3386 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3387 if (res != OK) {
3388 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3389 cleanUpFailedRequests(/*sendRequestError*/ false);
3390 return false;
3391 }
3392 }
3393 }
3394 }
3395
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003396 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003397 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003398 if (res == TIMED_OUT) {
3399 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003400 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003401 // Check if any stream is abandoned.
3402 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003403 return true;
3404 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003405 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003406 return false;
3407 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003408
Zhijun Hecc27e112013-10-03 16:12:43 -07003409 // Inform waitUntilRequestProcessed thread of a new request ID
3410 {
3411 Mutex::Autolock al(mLatestRequestMutex);
3412
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003413 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003414 mLatestRequestSignal.signal();
3415 }
3416
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003417 // Submit a batch of requests to HAL.
3418 // Use flush lock only when submitting multilple requests in a batch.
3419 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3420 // which may take a long time to finish so synchronizing flush() and
3421 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3422 // For now, only synchronize for high speed recording and we should figure something out for
3423 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003424 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003425
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003426 if (useFlushLock) {
3427 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003428 }
3429
Zhijun Hef0645c12016-08-02 00:58:11 -07003430 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003431 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003432
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003433 sp<Camera3Device> parent = mParent.promote();
3434 if (parent != nullptr) {
3435 parent->mRequestBufferSM.onSubmittingRequest();
3436 }
3437
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003438 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003439 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003440 submitRequestSuccess = sendRequestsBatch();
3441
Shuzhen Wang686f6442017-06-20 16:16:04 -07003442 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3443 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003444
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003445 if (useFlushLock) {
3446 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003447 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003448
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003449 // Unset as current request
3450 {
3451 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003452 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003453 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003454 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003455
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003456 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003457}
3458
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003459status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3460 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3461 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3462 ANDROID_SCALER_CROP_REGION_SET};
3463 if (request == nullptr) {
3464 ALOGE("%s request metadata nullptr", __FUNCTION__);
3465 return BAD_VALUE;
3466 }
3467 status_t res = OK;
3468 for (const auto &key : kFwkOnlyRegionKeys) {
3469 if (request->exists(key)) {
3470 res = request->erase(key);
3471 if (res != OK) {
3472 return res;
3473 }
3474 }
3475 }
3476 return OK;
3477}
3478
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003479status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003480 ATRACE_CALL();
3481
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003482 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003483 for (size_t i = 0; i < mNextRequests.size(); i++) {
3484 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003485 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003486 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3487 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003488
3489 // Prepare a request to HAL
3490 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3491
3492 // Insert any queued triggers (before metadata is locked)
3493 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003494 if (res < 0) {
3495 SET_ERR("RequestThread: Unable to insert triggers "
3496 "(capture request %d, HAL device: %s (%d)",
3497 halRequest->frame_number, strerror(-res), res);
3498 return INVALID_OPERATION;
3499 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003500
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003501 int triggerCount = res;
3502 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3503 mPrevTriggers = triggerCount;
3504
Emilian Peeve23f1d92021-09-20 14:56:01 -07003505 // Do not override rotate&crop for stream configurations that include
3506 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3507 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3508 bool rotateAndCropChanged = mComposerOutput ? false :
3509 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003510 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003511
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003512 // If the request is the same as last, or we had triggers now or last time or
3513 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003514 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003515 (mPrevRequest != captureRequest || triggersMixedIn ||
3516 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003517 // Request settings are all the same within one batch, so only treat the first
3518 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003519 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003520 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003521 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003522 /**
3523 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003524 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003525 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003526 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003527 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003528 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003529 "(capture request %d, HAL device: %s (%d)",
3530 halRequest->frame_number, strerror(-res), res);
3531 return INVALID_OPERATION;
3532 }
3533
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003534 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003535 sp<Camera3Device> parent = mParent.promote();
3536 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003537 List<PhysicalCameraSettings>::iterator it;
3538 for (it = captureRequest->mSettingsList.begin();
3539 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003540 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3541 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003542 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3543 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3544 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3545 res);
3546 return INVALID_OPERATION;
3547 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003548 continue;
3549 }
3550
3551 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3552 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3553 updateCaptureRequest(&(it->metadata));
3554 if (res != OK) {
3555 SET_ERR("RequestThread: Unable to correct capture requests "
3556 "for scaler crop region and metering regions for request "
3557 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3558 res);
3559 return INVALID_OPERATION;
3560 }
3561 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003562 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3563 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3564 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3565 res);
3566 return INVALID_OPERATION;
3567 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003568 }
3569 }
3570
3571 // Correct metadata regions for distortion correction if enabled
3572 for (it = captureRequest->mSettingsList.begin();
3573 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003574 if (parent->mDistortionMappers.find(it->cameraId) ==
3575 parent->mDistortionMappers.end()) {
3576 continue;
3577 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003578
3579 if (!captureRequest->mDistortionCorrectionUpdated) {
3580 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3581 &(it->metadata));
3582 if (res != OK) {
3583 SET_ERR("RequestThread: Unable to correct capture requests "
3584 "for lens distortion for request %d: %s (%d)",
3585 halRequest->frame_number, strerror(-res), res);
3586 return INVALID_OPERATION;
3587 }
3588 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003589 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003590 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003591
3592 for (it = captureRequest->mSettingsList.begin();
3593 it != captureRequest->mSettingsList.end(); it++) {
3594 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3595 parent->mZoomRatioMappers.end()) {
3596 continue;
3597 }
3598
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003599 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003600 cameraIdsWithZoom.insert(it->cameraId);
3601 }
3602
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003603 if (!captureRequest->mZoomRatioUpdated) {
3604 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3605 &(it->metadata));
3606 if (res != OK) {
3607 SET_ERR("RequestThread: Unable to correct capture requests "
3608 "for zoom ratio for request %d: %s (%d)",
3609 halRequest->frame_number, strerror(-res), res);
3610 return INVALID_OPERATION;
3611 }
3612 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003613 }
3614 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003615 if (captureRequest->mRotateAndCropAuto &&
3616 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003617 for (it = captureRequest->mSettingsList.begin();
3618 it != captureRequest->mSettingsList.end(); it++) {
3619 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3620 if (mapper != parent->mRotateAndCropMappers.end()) {
3621 res = mapper->second.updateCaptureRequest(&(it->metadata));
3622 if (res != OK) {
3623 SET_ERR("RequestThread: Unable to correct capture requests "
3624 "for rotate-and-crop for request %d: %s (%d)",
3625 halRequest->frame_number, strerror(-res), res);
3626 return INVALID_OPERATION;
3627 }
3628 }
3629 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003630 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003631 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003632 }
3633 }
3634
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003635 /**
3636 * The request should be presorted so accesses in HAL
3637 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3638 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003639 captureRequest->mSettingsList.begin()->metadata.sort();
3640 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003641 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003642 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3644
3645 IF_ALOGV() {
3646 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3647 find_camera_metadata_ro_entry(
3648 halRequest->settings,
3649 ANDROID_CONTROL_AF_TRIGGER,
3650 &e
3651 );
3652 if (e.count > 0) {
3653 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3654 __FUNCTION__,
3655 halRequest->frame_number,
3656 e.data.u8[0]);
3657 }
3658 }
3659 } else {
3660 // leave request.settings NULL to indicate 'reuse latest given'
3661 ALOGVV("%s: Request settings are REUSED",
3662 __FUNCTION__);
3663 }
3664
Emilian Peevaebbe412018-01-15 13:53:24 +00003665 if (captureRequest->mSettingsList.size() > 1) {
3666 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3667 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003668 if (newRequest) {
3669 halRequest->physcam_settings =
3670 new const camera_metadata* [halRequest->num_physcam_settings];
3671 } else {
3672 halRequest->physcam_settings = nullptr;
3673 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003674 auto it = ++captureRequest->mSettingsList.begin();
3675 size_t i = 0;
3676 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3677 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003678 if (newRequest) {
3679 it->metadata.sort();
3680 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3681 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003682 }
3683 }
3684
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003685 uint32_t totalNumBuffers = 0;
3686
3687 // Fill in buffers
3688 if (captureRequest->mInputStream != NULL) {
3689 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003690
3691 halRequest->input_width = captureRequest->mInputBufferSize.width;
3692 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003693 totalNumBuffers += 1;
3694 } else {
3695 halRequest->input_buffer = NULL;
3696 }
3697
Emilian Peevf4816702020-04-03 15:44:51 -07003698 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003699 captureRequest->mOutputStreams.size());
3700 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003701 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003702
3703 sp<Camera3Device> parent = mParent.promote();
3704 if (parent == NULL) {
3705 // Should not happen, and nowhere to send errors to, so just log it
3706 CLOGE("RequestThread: Parent is gone");
3707 return INVALID_OPERATION;
3708 }
3709 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3710
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003711 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003712 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003713 sp<Camera3OutputStreamInterface> outputStream =
3714 captureRequest->mOutputStreams.editItemAt(j);
3715 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003716
3717 // Prepare video buffers for high speed recording on the first video request.
3718 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3719 // Only try to prepare video stream on the first video request.
3720 mPrepareVideoStream = false;
3721
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003722 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3723 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003724 while (res == NOT_ENOUGH_DATA) {
3725 res = outputStream->prepareNextBuffer();
3726 }
3727 if (res != OK) {
3728 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3729 __FUNCTION__, strerror(-res), res);
3730 outputStream->cancelPrepare();
3731 }
3732 }
3733
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003734 std::vector<size_t> uniqueSurfaceIds;
3735 res = outputStream->getUniqueSurfaceIds(
3736 captureRequest->mOutputSurfaces[streamId],
3737 &uniqueSurfaceIds);
3738 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3739 if (res != OK && res != INVALID_OPERATION) {
3740 ALOGE("%s: failed to query stream %d unique surface IDs",
3741 __FUNCTION__, streamId);
3742 return res;
3743 }
3744 if (res == OK) {
3745 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3746 }
3747
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003748 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003749 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003750 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003751 return TIMED_OUT;
3752 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003753 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003754 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003755 buffer.stream = outputStream->asHalStream();
3756 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003757 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003758 buffer.acquire_fence = -1;
3759 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003760 // Mark the output stream as unpreparable to block clients from calling
3761 // 'prepare' after this request reaches CameraHal and before the respective
3762 // buffers are requested.
3763 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003764 } else {
3765 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3766 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003767 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003768 if (res != OK) {
3769 // Can't get output buffer from gralloc queue - this could be due to
3770 // abandoned queue or other consumer misbehavior, so not a fatal
3771 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003772 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003773 " %s (%d)", strerror(-res), res);
3774
3775 return TIMED_OUT;
3776 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003777 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003778
3779 {
3780 sp<Camera3Device> parent = mParent.promote();
3781 if (parent != nullptr) {
3782 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3783 for (const auto& settings : captureRequest->mSettingsList) {
3784 if ((streamCameraId.isEmpty() &&
3785 parent->getId() == settings.cameraId.c_str()) ||
3786 streamCameraId == settings.cameraId.c_str()) {
3787 outputStream->fireBufferRequestForFrameNumber(
3788 captureRequest->mResultExtras.frameNumber,
3789 settings.metadata);
3790 }
3791 }
3792 }
3793 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003794
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003795 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003796 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3797 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3798 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3799 } else if (!physicalCameraId.isEmpty()) {
3800 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003801 }
3802 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003803 }
3804 totalNumBuffers += halRequest->num_output_buffers;
3805
3806 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003807 // If this request list is for constrained high speed recording (not
3808 // preview), and the current request is not the last one in the batch,
3809 // do not send callback to the app.
3810 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003811 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003812 hasCallback = false;
3813 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003814 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003815 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003816 const camera_metadata_t* settings = halRequest->settings;
3817 bool shouldUnlockSettings = false;
3818 if (settings == nullptr) {
3819 shouldUnlockSettings = true;
3820 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3821 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003822 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3823 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003824 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003825 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3826 isStillCapture = true;
3827 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3828 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003829
Emilian Peevaf8416e2021-02-04 17:52:43 -08003830 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003831 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003832 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3833 isZslCapture = true;
3834 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003835 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003836 res = parent->registerInFlight(halRequest->frame_number,
3837 totalNumBuffers, captureRequest->mResultExtras,
3838 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003839 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003840 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003841 requestedPhysicalCameras, isStillCapture, isZslCapture,
3842 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003843 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003844 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003845 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3846 ", burstId = %" PRId32 ".",
3847 __FUNCTION__,
3848 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3849 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003850
3851 if (shouldUnlockSettings) {
3852 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3853 }
3854
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003855 if (res != OK) {
3856 SET_ERR("RequestThread: Unable to register new in-flight request:"
3857 " %s (%d)", strerror(-res), res);
3858 return INVALID_OPERATION;
3859 }
3860 }
3861
3862 return OK;
3863}
3864
Igor Murashkin1e479c02013-09-06 16:55:14 -07003865CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003866 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003867 Mutex::Autolock al(mLatestRequestMutex);
3868
3869 ALOGV("RequestThread::%s", __FUNCTION__);
3870
3871 return mLatestRequest;
3872}
3873
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003874bool Camera3Device::RequestThread::isStreamPending(
3875 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003876 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003877 Mutex::Autolock l(mRequestLock);
3878
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003879 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003880 if (!nextRequest.submitted) {
3881 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3882 if (stream == s) return true;
3883 }
3884 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003885 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003886 }
3887
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003888 for (const auto& request : mRequestQueue) {
3889 for (const auto& s : request->mOutputStreams) {
3890 if (stream == s) return true;
3891 }
3892 if (stream == request->mInputStream) return true;
3893 }
3894
3895 for (const auto& request : mRepeatingRequests) {
3896 for (const auto& s : request->mOutputStreams) {
3897 if (stream == s) return true;
3898 }
3899 if (stream == request->mInputStream) return true;
3900 }
3901
3902 return false;
3903}
Jianing Weicb0652e2014-03-12 18:29:36 -07003904
Emilian Peev40ead602017-09-26 15:46:36 +01003905bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3906 ATRACE_CALL();
3907 Mutex::Autolock l(mRequestLock);
3908
3909 for (const auto& nextRequest : mNextRequests) {
3910 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3911 if (s.first == streamId) {
3912 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3913 if (it != s.second.end()) {
3914 return true;
3915 }
3916 }
3917 }
3918 }
3919
3920 for (const auto& request : mRequestQueue) {
3921 for (const auto& s : request->mOutputSurfaces) {
3922 if (s.first == streamId) {
3923 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3924 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003925 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003926 }
3927 }
3928 }
3929 }
3930
3931 for (const auto& request : mRepeatingRequests) {
3932 for (const auto& s : request->mOutputSurfaces) {
3933 if (s.first == streamId) {
3934 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3935 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003936 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003937 }
3938 }
3939 }
3940 }
3941
3942 return false;
3943}
3944
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003945void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3946 if (!mUseHalBufManager) {
3947 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3948 return;
3949 }
3950
3951 Mutex::Autolock pl(mPauseLock);
3952 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003953 mInterface->signalPipelineDrain(streamIds);
3954 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003955 }
3956 // If request thread is still busy, wait until paused then notify HAL
3957 mNotifyPipelineDrain = true;
3958 mStreamIdsToBeDrained = streamIds;
3959}
3960
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003961void Camera3Device::RequestThread::resetPipelineDrain() {
3962 Mutex::Autolock pl(mPauseLock);
3963 mNotifyPipelineDrain = false;
3964 mStreamIdsToBeDrained.clear();
3965}
3966
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003967void Camera3Device::RequestThread::clearPreviousRequest() {
3968 Mutex::Autolock l(mRequestLock);
3969 mPrevRequest.clear();
3970}
3971
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003972status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3973 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3974 ATRACE_CALL();
3975 Mutex::Autolock l(mTriggerMutex);
3976 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3977 return BAD_VALUE;
3978 }
3979 mRotateAndCropOverride = rotateAndCropValue;
3980 return OK;
3981}
3982
Emilian Peeve23f1d92021-09-20 14:56:01 -07003983status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3984 ATRACE_CALL();
3985 Mutex::Autolock l(mTriggerMutex);
3986 mComposerOutput = composerSurfacePresent;
3987 return OK;
3988}
3989
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003990status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003991 ATRACE_CALL();
3992 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003993 if (muteMode != mCameraMute) {
3994 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003995 mCameraMuteChanged = true;
3996 }
3997 return OK;
3998}
3999
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004000nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004001 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004002 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004003 return mExpectedInflightDuration > kMinInflightDuration ?
4004 mExpectedInflightDuration : kMinInflightDuration;
4005}
4006
Emilian Peevaebbe412018-01-15 13:53:24 +00004007void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004008 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004009 if ((request == nullptr) || (halRequest == nullptr)) {
4010 ALOGE("%s: Invalid request!", __FUNCTION__);
4011 return;
4012 }
4013
4014 if (halRequest->num_physcam_settings > 0) {
4015 if (halRequest->physcam_id != nullptr) {
4016 delete [] halRequest->physcam_id;
4017 halRequest->physcam_id = nullptr;
4018 }
4019 if (halRequest->physcam_settings != nullptr) {
4020 auto it = ++(request->mSettingsList.begin());
4021 size_t i = 0;
4022 for (; it != request->mSettingsList.end(); it++, i++) {
4023 it->metadata.unlock(halRequest->physcam_settings[i]);
4024 }
4025 delete [] halRequest->physcam_settings;
4026 halRequest->physcam_settings = nullptr;
4027 }
4028 }
4029}
4030
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004031void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4032 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004033 return;
4034 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004035
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004036 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004037 // Skip the ones that have been submitted successfully.
4038 if (nextRequest.submitted) {
4039 continue;
4040 }
4041
4042 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004043 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4044 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004045
4046 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004047 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004048 }
4049
Emilian Peevaebbe412018-01-15 13:53:24 +00004050 cleanupPhysicalSettings(captureRequest, halRequest);
4051
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004052 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004053 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004054 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4055 }
4056
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004057 // No output buffer can be returned when using HAL buffer manager
4058 if (!mUseHalBufManager) {
4059 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4060 //Buffers that failed processing could still have
4061 //valid acquire fence.
4062 int acquireFence = (*outputBuffers)[i].acquire_fence;
4063 if (0 <= acquireFence) {
4064 close(acquireFence);
4065 outputBuffers->editItemAt(i).acquire_fence = -1;
4066 }
Emilian Peevf4816702020-04-03 15:44:51 -07004067 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004068 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4069 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004070 /*timestampIncreasing*/true, std::vector<size_t> (),
4071 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004072 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004073 }
4074
4075 if (sendRequestError) {
4076 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004077 sp<NotificationListener> listener = mListener.promote();
4078 if (listener != NULL) {
4079 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004080 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004081 captureRequest->mResultExtras);
4082 }
4083 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004084
4085 // Remove yet-to-be submitted inflight request from inflightMap
4086 {
4087 sp<Camera3Device> parent = mParent.promote();
4088 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004089 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004090 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4091 if (idx >= 0) {
4092 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4093 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4094 parent->removeInFlightMapEntryLocked(idx);
4095 }
4096 }
4097 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004098 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004099
4100 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004101 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004102}
4103
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004104void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004105 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004106 // Optimized a bit for the simple steady-state case (single repeating
4107 // request), to avoid putting that request in the queue temporarily.
4108 Mutex::Autolock l(mRequestLock);
4109
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004110 assert(mNextRequests.empty());
4111
4112 NextRequest nextRequest;
4113 nextRequest.captureRequest = waitForNextRequestLocked();
4114 if (nextRequest.captureRequest == nullptr) {
4115 return;
4116 }
4117
Emilian Peevf4816702020-04-03 15:44:51 -07004118 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004119 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004120 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004121
4122 // Wait for additional requests
4123 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4124
4125 for (size_t i = 1; i < batchSize; i++) {
4126 NextRequest additionalRequest;
4127 additionalRequest.captureRequest = waitForNextRequestLocked();
4128 if (additionalRequest.captureRequest == nullptr) {
4129 break;
4130 }
4131
Emilian Peevf4816702020-04-03 15:44:51 -07004132 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004133 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004134 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004135 }
4136
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004137 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004138 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004139 mNextRequests.size(), batchSize);
4140 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004141 }
4142
4143 return;
4144}
4145
4146sp<Camera3Device::CaptureRequest>
4147 Camera3Device::RequestThread::waitForNextRequestLocked() {
4148 status_t res;
4149 sp<CaptureRequest> nextRequest;
4150
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004151 while (mRequestQueue.empty()) {
4152 if (!mRepeatingRequests.empty()) {
4153 // Always atomically enqueue all requests in a repeating request
4154 // list. Guarantees a complete in-sequence set of captures to
4155 // application.
4156 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004157 if (mFirstRepeating) {
4158 mFirstRepeating = false;
4159 } else {
4160 for (auto& request : requests) {
4161 // For repeating requests, override timestamp request using
4162 // the time a request is inserted into the request queue,
4163 // because the original repeating request will have an old
4164 // fixed timestamp.
4165 request->mRequestTimeNs = systemTime();
4166 }
4167 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004168 RequestList::const_iterator firstRequest =
4169 requests.begin();
4170 nextRequest = *firstRequest;
4171 mRequestQueue.insert(mRequestQueue.end(),
4172 ++firstRequest,
4173 requests.end());
4174 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004175
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004176 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004177
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004178 break;
4179 }
4180
4181 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4182
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004183 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4184 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004185 Mutex::Autolock pl(mPauseLock);
4186 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004187 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004188 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004189 if (mNotifyPipelineDrain) {
4190 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4191 mNotifyPipelineDrain = false;
4192 mStreamIdsToBeDrained.clear();
4193 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004194 // Let the tracker know
4195 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4196 if (statusTracker != 0) {
4197 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4198 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004199 sp<Camera3Device> parent = mParent.promote();
4200 if (parent != nullptr) {
4201 parent->mRequestBufferSM.onRequestThreadPaused();
4202 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004203 }
4204 // Stop waiting for now and let thread management happen
4205 return NULL;
4206 }
4207 }
4208
4209 if (nextRequest == NULL) {
4210 // Don't have a repeating request already in hand, so queue
4211 // must have an entry now.
4212 RequestList::iterator firstRequest =
4213 mRequestQueue.begin();
4214 nextRequest = *firstRequest;
4215 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004216 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4217 sp<NotificationListener> listener = mListener.promote();
4218 if (listener != NULL) {
4219 listener->notifyRequestQueueEmpty();
4220 }
4221 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004222 }
4223
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004224 // In case we've been unpaused by setPaused clearing mDoPause, need to
4225 // update internal pause state (capture/setRepeatingRequest unpause
4226 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004227 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004228 if (mPaused) {
4229 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4230 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4231 if (statusTracker != 0) {
4232 statusTracker->markComponentActive(mStatusId);
4233 }
4234 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004235 mPaused = false;
4236
4237 // Check if we've reconfigured since last time, and reset the preview
4238 // request if so. Can't use 'NULL request == repeat' across configure calls.
4239 if (mReconfigured) {
4240 mPrevRequest.clear();
4241 mReconfigured = false;
4242 }
4243
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004244 if (nextRequest != NULL) {
4245 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004246 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4247 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004248
4249 // Since RequestThread::clear() removes buffers from the input stream,
4250 // get the right buffer here before unlocking mRequestLock
4251 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004252 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4253 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004254 if (res != OK) {
4255 // Can't get input buffer from gralloc queue - this could be due to
4256 // disconnected queue or other producer misbehavior, so not a fatal
4257 // error
4258 ALOGE("%s: Can't get input buffer, skipping request:"
4259 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004260
4261 sp<NotificationListener> listener = mListener.promote();
4262 if (listener != NULL) {
4263 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004264 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004265 nextRequest->mResultExtras);
4266 }
4267 return NULL;
4268 }
4269 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004270 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004271
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 return nextRequest;
4273}
4274
4275bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004276 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004277 status_t res;
4278 Mutex::Autolock l(mPauseLock);
4279 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004280 if (mPaused == false) {
4281 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004282 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004283 if (mNotifyPipelineDrain) {
4284 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4285 mNotifyPipelineDrain = false;
4286 mStreamIdsToBeDrained.clear();
4287 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004288 // Let the tracker know
4289 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4290 if (statusTracker != 0) {
4291 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4292 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004293 sp<Camera3Device> parent = mParent.promote();
4294 if (parent != nullptr) {
4295 parent->mRequestBufferSM.onRequestThreadPaused();
4296 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004298
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004300 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 return true;
4302 }
4303 }
4304 // We don't set mPaused to false here, because waitForNextRequest needs
4305 // to further manage the paused state in case of starvation.
4306 return false;
4307}
4308
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004309void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004310 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004311 // With work to do, mark thread as unpaused.
4312 // If paused by request (setPaused), don't resume, to avoid
4313 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004314 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004315 Mutex::Autolock p(mPauseLock);
4316 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004317 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4318 if (mPaused) {
4319 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4320 if (statusTracker != 0) {
4321 statusTracker->markComponentActive(mStatusId);
4322 }
4323 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004324 mPaused = false;
4325 }
4326}
4327
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004328void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4329 sp<Camera3Device> parent = mParent.promote();
4330 if (parent != NULL) {
4331 va_list args;
4332 va_start(args, fmt);
4333
4334 parent->setErrorStateV(fmt, args);
4335
4336 va_end(args);
4337 }
4338}
4339
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004340status_t Camera3Device::RequestThread::insertTriggers(
4341 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004342 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004343 Mutex::Autolock al(mTriggerMutex);
4344
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004345 sp<Camera3Device> parent = mParent.promote();
4346 if (parent == NULL) {
4347 CLOGE("RequestThread: Parent is gone");
4348 return DEAD_OBJECT;
4349 }
4350
Emilian Peevaebbe412018-01-15 13:53:24 +00004351 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004352 size_t count = mTriggerMap.size();
4353
4354 for (size_t i = 0; i < count; ++i) {
4355 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004356 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004357
4358 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4359 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4360 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004361 if (isAeTrigger) {
4362 request->mResultExtras.precaptureTriggerId = triggerId;
4363 mCurrentPreCaptureTriggerId = triggerId;
4364 } else {
4365 request->mResultExtras.afTriggerId = triggerId;
4366 mCurrentAfTriggerId = triggerId;
4367 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004368 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004369 }
4370
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004371 camera_metadata_entry entry = metadata.find(tag);
4372
4373 if (entry.count > 0) {
4374 /**
4375 * Already has an entry for this trigger in the request.
4376 * Rewrite it with our requested trigger value.
4377 */
4378 RequestTrigger oldTrigger = trigger;
4379
4380 oldTrigger.entryValue = entry.data.u8[0];
4381
4382 mTriggerReplacedMap.add(tag, oldTrigger);
4383 } else {
4384 /**
4385 * More typical, no trigger entry, so we just add it
4386 */
4387 mTriggerRemovedMap.add(tag, trigger);
4388 }
4389
4390 status_t res;
4391
4392 switch (trigger.getTagType()) {
4393 case TYPE_BYTE: {
4394 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4395 res = metadata.update(tag,
4396 &entryValue,
4397 /*count*/1);
4398 break;
4399 }
4400 case TYPE_INT32:
4401 res = metadata.update(tag,
4402 &trigger.entryValue,
4403 /*count*/1);
4404 break;
4405 default:
4406 ALOGE("%s: Type not supported: 0x%x",
4407 __FUNCTION__,
4408 trigger.getTagType());
4409 return INVALID_OPERATION;
4410 }
4411
4412 if (res != OK) {
4413 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4414 ", value %d", __FUNCTION__, trigger.getTagName(),
4415 trigger.entryValue);
4416 return res;
4417 }
4418
4419 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4420 trigger.getTagName(),
4421 trigger.entryValue);
4422 }
4423
4424 mTriggerMap.clear();
4425
4426 return count;
4427}
4428
4429status_t Camera3Device::RequestThread::removeTriggers(
4430 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004431 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004432 Mutex::Autolock al(mTriggerMutex);
4433
Emilian Peevaebbe412018-01-15 13:53:24 +00004434 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004435
4436 /**
4437 * Replace all old entries with their old values.
4438 */
4439 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4440 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4441
4442 status_t res;
4443
4444 uint32_t tag = trigger.metadataTag;
4445 switch (trigger.getTagType()) {
4446 case TYPE_BYTE: {
4447 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4448 res = metadata.update(tag,
4449 &entryValue,
4450 /*count*/1);
4451 break;
4452 }
4453 case TYPE_INT32:
4454 res = metadata.update(tag,
4455 &trigger.entryValue,
4456 /*count*/1);
4457 break;
4458 default:
4459 ALOGE("%s: Type not supported: 0x%x",
4460 __FUNCTION__,
4461 trigger.getTagType());
4462 return INVALID_OPERATION;
4463 }
4464
4465 if (res != OK) {
4466 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4467 ", trigger value %d", __FUNCTION__,
4468 trigger.getTagName(), trigger.entryValue);
4469 return res;
4470 }
4471 }
4472 mTriggerReplacedMap.clear();
4473
4474 /**
4475 * Remove all new entries.
4476 */
4477 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4478 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4479 status_t res = metadata.erase(trigger.metadataTag);
4480
4481 if (res != OK) {
4482 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4483 ", trigger value %d", __FUNCTION__,
4484 trigger.getTagName(), trigger.entryValue);
4485 return res;
4486 }
4487 }
4488 mTriggerRemovedMap.clear();
4489
4490 return OK;
4491}
4492
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004493status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004494 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004495 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004496 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004497 status_t res;
4498
Emilian Peevaebbe412018-01-15 13:53:24 +00004499 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004500
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004501 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004502 // exists
4503 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4504 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4505 if (afTrigger.count > 0 &&
4506 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4507 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004508 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004509 if (res != OK) return res;
4510 }
4511
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004512 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004513 // if none already exists
4514 camera_metadata_entry pcTrigger =
4515 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4516 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4517 if (pcTrigger.count > 0 &&
4518 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4519 pcId.count == 0) {
4520 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004521 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004522 if (res != OK) return res;
4523 }
4524
4525 return OK;
4526}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004527
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004528bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4529 const sp<CaptureRequest> &request) {
4530 ATRACE_CALL();
4531
4532 if (request->mRotateAndCropAuto) {
4533 Mutex::Autolock l(mTriggerMutex);
4534 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4535
4536 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4537 if (rotateAndCropEntry.count > 0) {
4538 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4539 return false;
4540 } else {
4541 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4542 return true;
4543 }
4544 } else {
4545 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4546 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4547 &rotateAndCrop_u8, 1);
4548 return true;
4549 }
4550 }
4551 return false;
4552}
4553
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004554bool Camera3Device::RequestThread::overrideTestPattern(
4555 const sp<CaptureRequest> &request) {
4556 ATRACE_CALL();
4557
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004558 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004559
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004560 Mutex::Autolock l(mTriggerMutex);
4561
4562 bool changed = false;
4563
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004564 // For a multi-camera, the physical cameras support the same set of
4565 // test pattern modes as the logical camera.
4566 for (auto& settings : request->mSettingsList) {
4567 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004568
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004569 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4570 int32_t testPatternData[4] = {
4571 settings.mOriginalTestPatternData[0],
4572 settings.mOriginalTestPatternData[1],
4573 settings.mOriginalTestPatternData[2],
4574 settings.mOriginalTestPatternData[3]
4575 };
4576 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4577 testPatternMode = mCameraMute;
4578 testPatternData[0] = 0;
4579 testPatternData[1] = 0;
4580 testPatternData[2] = 0;
4581 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004582 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004583
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004584 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4585 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4586 if (testPatternEntry.count > 0) {
4587 if (testPatternEntry.data.i32[0] != testPatternMode) {
4588 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004589 changed = true;
4590 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004591 } else if (supportTestPatternModeKey) {
4592 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4593 &testPatternMode, 1);
4594 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004595 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004596
4597 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4598 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4599 if (testPatternColor.count >= 4) {
4600 for (size_t i = 0; i < 4; i++) {
4601 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4602 testPatternColor.data.i32[i] = testPatternData[i];
4603 changed = true;
4604 }
4605 }
4606 } else if (supportTestPatternDataKey) {
4607 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4608 testPatternData, 4);
4609 changed = true;
4610 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004611 }
4612
4613 return changed;
4614}
4615
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004616status_t Camera3Device::RequestThread::setHalInterface(
4617 sp<HalInterface> newHalInterface) {
4618 if (newHalInterface.get() == nullptr) {
4619 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4620 return DEAD_OBJECT;
4621 }
4622
4623 mInterface = newHalInterface;
4624
4625 return OK;
4626}
4627
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004628/**
4629 * PreparerThread inner class methods
4630 */
4631
4632Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004633 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004634 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004635}
4636
4637Camera3Device::PreparerThread::~PreparerThread() {
4638 Thread::requestExitAndWait();
4639 if (mCurrentStream != nullptr) {
4640 mCurrentStream->cancelPrepare();
4641 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4642 mCurrentStream.clear();
4643 }
4644 clear();
4645}
4646
Ruben Brunkc78ac262015-08-13 17:58:46 -07004647status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004648 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004649 status_t res;
4650
4651 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004652 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004653
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004654 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004655 if (res == OK) {
4656 // No preparation needed, fire listener right off
4657 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004658 if (listener != NULL) {
4659 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004660 }
4661 return OK;
4662 } else if (res != NOT_ENOUGH_DATA) {
4663 return res;
4664 }
4665
4666 // Need to prepare, start up thread if necessary
4667 if (!mActive) {
4668 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4669 // isn't running
4670 Thread::requestExitAndWait();
4671 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4672 if (res != OK) {
4673 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004674 if (listener != NULL) {
4675 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004676 }
4677 return res;
4678 }
4679 mCancelNow = false;
4680 mActive = true;
4681 ALOGV("%s: Preparer stream started", __FUNCTION__);
4682 }
4683
4684 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004685 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004686 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4687
4688 return OK;
4689}
4690
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004691void Camera3Device::PreparerThread::pause() {
4692 ATRACE_CALL();
4693
4694 Mutex::Autolock l(mLock);
4695
4696 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4697 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4698 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4699 int currentMaxCount = mCurrentMaxCount;
4700 mPendingStreams.clear();
4701 mCancelNow = true;
4702 while (mActive) {
4703 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4704 if (res == TIMED_OUT) {
4705 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4706 return;
4707 } else if (res != OK) {
4708 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4709 return;
4710 }
4711 }
4712
4713 //Check whether the prepare thread was able to complete the current
4714 //stream. In case work is still pending emplace it along with the rest
4715 //of the streams in the pending list.
4716 if (currentStream != nullptr) {
4717 if (!mCurrentPrepareComplete) {
4718 pendingStreams.emplace(currentMaxCount, currentStream);
4719 }
4720 }
4721
4722 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4723 for (const auto& it : mPendingStreams) {
4724 it.second->cancelPrepare();
4725 }
4726}
4727
4728status_t Camera3Device::PreparerThread::resume() {
4729 ATRACE_CALL();
4730 status_t res;
4731
4732 Mutex::Autolock l(mLock);
4733 sp<NotificationListener> listener = mListener.promote();
4734
4735 if (mActive) {
4736 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4737 return NO_INIT;
4738 }
4739
4740 auto it = mPendingStreams.begin();
4741 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004742 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004743 if (res == OK) {
4744 if (listener != NULL) {
4745 listener->notifyPrepared(it->second->getId());
4746 }
4747 it = mPendingStreams.erase(it);
4748 } else if (res != NOT_ENOUGH_DATA) {
4749 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4750 res, strerror(-res));
4751 it = mPendingStreams.erase(it);
4752 } else {
4753 it++;
4754 }
4755 }
4756
4757 if (mPendingStreams.empty()) {
4758 return OK;
4759 }
4760
4761 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4762 if (res != OK) {
4763 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4764 __FUNCTION__, res, strerror(-res));
4765 return res;
4766 }
4767 mCancelNow = false;
4768 mActive = true;
4769 ALOGV("%s: Preparer stream started", __FUNCTION__);
4770
4771 return OK;
4772}
4773
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004774status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004775 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776 Mutex::Autolock l(mLock);
4777
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004778 for (const auto& it : mPendingStreams) {
4779 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004780 }
4781 mPendingStreams.clear();
4782 mCancelNow = true;
4783
4784 return OK;
4785}
4786
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004787void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004788 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004789 Mutex::Autolock l(mLock);
4790 mListener = listener;
4791}
4792
4793bool Camera3Device::PreparerThread::threadLoop() {
4794 status_t res;
4795 {
4796 Mutex::Autolock l(mLock);
4797 if (mCurrentStream == nullptr) {
4798 // End thread if done with work
4799 if (mPendingStreams.empty()) {
4800 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4801 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4802 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4803 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004804 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004805 return false;
4806 }
4807
4808 // Get next stream to prepare
4809 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004810 mCurrentStream = it->second;
4811 mCurrentMaxCount = it->first;
4812 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004813 mPendingStreams.erase(it);
4814 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4815 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4816 } else if (mCancelNow) {
4817 mCurrentStream->cancelPrepare();
4818 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4819 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4820 mCurrentStream.clear();
4821 mCancelNow = false;
4822 return true;
4823 }
4824 }
4825
4826 res = mCurrentStream->prepareNextBuffer();
4827 if (res == NOT_ENOUGH_DATA) return true;
4828 if (res != OK) {
4829 // Something bad happened; try to recover by cancelling prepare and
4830 // signalling listener anyway
4831 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4832 mCurrentStream->getId(), res, strerror(-res));
4833 mCurrentStream->cancelPrepare();
4834 }
4835
4836 // This stream has finished, notify listener
4837 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004838 sp<NotificationListener> listener = mListener.promote();
4839 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004840 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4841 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004842 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004843 }
4844
4845 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4846 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004847 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004848
4849 return true;
4850}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004851
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004852status_t Camera3Device::RequestBufferStateMachine::initialize(
4853 sp<camera3::StatusTracker> statusTracker) {
4854 if (statusTracker == nullptr) {
4855 ALOGE("%s: statusTracker is null", __FUNCTION__);
4856 return BAD_VALUE;
4857 }
4858
4859 std::lock_guard<std::mutex> lock(mLock);
4860 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004861 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004862 return OK;
4863}
4864
4865bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4866 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004867 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004868 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004869 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004870 return true;
4871 }
4872 return false;
4873}
4874
4875void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4876 std::lock_guard<std::mutex> lock(mLock);
4877 if (!mRequestBufferOngoing) {
4878 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4879 return;
4880 }
4881 mRequestBufferOngoing = false;
4882 if (mStatus == RB_STATUS_PENDING_STOP) {
4883 checkSwitchToStopLocked();
4884 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004885 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004886}
4887
4888void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4889 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004890 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004891 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004892 return;
4893}
4894
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004895void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004896 std::lock_guard<std::mutex> lock(mLock);
4897 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004898 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4899 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004900 mInflightMapEmpty = false;
4901 if (mStatus == RB_STATUS_STOPPED) {
4902 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004903 }
4904 return;
4905}
4906
4907void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4908 std::lock_guard<std::mutex> lock(mLock);
4909 mRequestThreadPaused = true;
4910 if (mStatus == RB_STATUS_PENDING_STOP) {
4911 checkSwitchToStopLocked();
4912 }
4913 return;
4914}
4915
4916void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4917 std::lock_guard<std::mutex> lock(mLock);
4918 mInflightMapEmpty = true;
4919 if (mStatus == RB_STATUS_PENDING_STOP) {
4920 checkSwitchToStopLocked();
4921 }
4922 return;
4923}
4924
4925void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4926 std::lock_guard<std::mutex> lock(mLock);
4927 if (!checkSwitchToStopLocked()) {
4928 mStatus = RB_STATUS_PENDING_STOP;
4929 }
4930 return;
4931}
4932
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004933bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4934 std::lock_guard<std::mutex> lock(mLock);
4935 if (mRequestBufferOngoing) {
4936 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4937 __FUNCTION__);
4938 return false;
4939 }
4940 mSwitchedToOffline = true;
4941 mInflightMapEmpty = true;
4942 mRequestThreadPaused = true;
4943 mStatus = RB_STATUS_STOPPED;
4944 return true;
4945}
4946
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004947void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4948 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4949 if (statusTracker != nullptr) {
4950 if (active) {
4951 statusTracker->markComponentActive(mRequestBufferStatusId);
4952 } else {
4953 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4954 }
4955 }
4956}
4957
4958bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4959 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4960 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004961 return true;
4962 }
4963 return false;
4964}
4965
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004966bool Camera3Device::startRequestBuffer() {
4967 return mRequestBufferSM.startRequestBuffer();
4968}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004969
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004970void Camera3Device::endRequestBuffer() {
4971 mRequestBufferSM.endRequestBuffer();
4972}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004973
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004974nsecs_t Camera3Device::getWaitDuration() {
4975 return kBaseGetBufferWait + getExpectedInFlightDuration();
4976}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004977
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004978void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4979 mInterface->getInflightBufferKeys(out);
4980}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004981
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004982void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4983 mInterface->getInflightRequestBufferKeys(out);
4984}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004985
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004986std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
4987 std::vector<sp<Camera3StreamInterface>> ret;
4988 bool hasInputStream = mInputStream != nullptr;
4989 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
4990 if (hasInputStream) {
4991 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07004992 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004993 for (size_t i = 0; i < mOutputStreams.size(); i++) {
4994 ret.push_back(mOutputStreams[i]);
4995 }
4996 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
4997 ret.push_back(mDeletedStreams[i]);
4998 }
4999 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005000}
5001
Emilian Peevcc0b7952020-01-07 13:54:47 -08005002void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5003 ATRACE_CALL();
5004
5005 if (offlineStreamIds == nullptr) {
5006 return;
5007 }
5008
5009 Mutex::Autolock il(mInterfaceLock);
5010
5011 auto streamIds = mOutputStreams.getStreamIds();
5012 bool hasInputStream = mInputStream != nullptr;
5013 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5014 offlineStreamIds->push_back(mInputStream->getId());
5015 }
5016
5017 for (const auto & streamId : streamIds) {
5018 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5019 // Streams that use the camera buffer manager are currently not supported in
5020 // offline mode
5021 if (stream->getOfflineProcessingSupport() &&
5022 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5023 offlineStreamIds->push_back(streamId);
5024 }
5025 }
5026}
5027
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005028status_t Camera3Device::setRotateAndCropAutoBehavior(
5029 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5030 ATRACE_CALL();
5031 Mutex::Autolock il(mInterfaceLock);
5032 Mutex::Autolock l(mLock);
5033 if (mRequestThread == nullptr) {
5034 return INVALID_OPERATION;
5035 }
5036 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5037}
5038
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005039bool Camera3Device::supportsCameraMute() {
5040 Mutex::Autolock il(mInterfaceLock);
5041 Mutex::Autolock l(mLock);
5042
5043 return mSupportCameraMute;
5044}
5045
5046status_t Camera3Device::setCameraMute(bool enabled) {
5047 ATRACE_CALL();
5048 Mutex::Autolock il(mInterfaceLock);
5049 Mutex::Autolock l(mLock);
5050
5051 if (mRequestThread == nullptr || !mSupportCameraMute) {
5052 return INVALID_OPERATION;
5053 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005054 int32_t muteMode =
5055 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5056 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5057 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5058 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005059}
5060
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005061status_t Camera3Device::injectCamera(const String8& injectedCamId,
5062 sp<CameraProviderManager> manager) {
5063 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5064 ATRACE_CALL();
5065 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005066 // When the camera device is active, injectCamera() and stopInjection() will call
5067 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5068 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5069 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5070 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5071 // waitUntilStateThenRelock().
5072 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005073
5074 status_t res = NO_ERROR;
5075 if (mInjectionMethods->isInjecting()) {
5076 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5077 return OK;
5078 } else {
5079 res = mInjectionMethods->stopInjection();
5080 if (res != OK) {
5081 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5082 __FUNCTION__, res);
5083 return res;
5084 }
5085 }
5086 }
5087
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005088 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005089 if (res != OK) {
5090 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5091 __FUNCTION__, res);
5092 return res;
5093 }
5094
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005095 // When the second display of android is cast to the remote device, and the opened camera is
5096 // also cast to the second display, in this case, because the camera has configured the streams
5097 // at this time, we can directly call injectCamera() to replace the internal camera with
5098 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005099 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5100 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5101
5102 camera3::camera_stream_configuration injectionConfig;
5103 std::vector<uint32_t> injectionBufferSizes;
5104 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5105 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5106 || injectionBufferSizes.size() <= 0) {
5107 ALOGE("Failed to inject camera due to abandoned configuration! "
5108 "mOperatingMode: %d injectionConfig.num_streams: %d "
5109 "injectionBufferSizes.size(): %zu", mOperatingMode,
5110 injectionConfig.num_streams, injectionBufferSizes.size());
5111 return DEAD_OBJECT;
5112 }
5113
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005114 res = mInjectionMethods->injectCamera(
5115 injectionConfig, injectionBufferSizes);
5116 if (res != OK) {
5117 ALOGE("Can't finish inject camera process!");
5118 return res;
5119 }
5120 }
5121
5122 return OK;
5123}
5124
5125status_t Camera3Device::stopInjection() {
5126 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5127 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005128 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005129 return mInjectionMethods->stopInjection();
5130}
5131
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005132}; // namespace android