blob: 4794bfc66ad17a467334f0f35713239fd665282c [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010080 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
81 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082{
83 ATRACE_CALL();
84 camera3_callback_ops::notify = &sNotify;
85 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093 disconnect();
94}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
124 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Yifan Hongf79b5542017-04-11 14:44:25 -0700129 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700130 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
131 [&queue](const auto& descriptor) {
132 queue = std::make_shared<RequestMetadataQueue>(descriptor);
133 if (!queue->isValid() || queue->availableToWrite() <= 0) {
134 ALOGE("HAL returns empty request metadata fmq, not use it");
135 queue = nullptr;
136 // don't use the queue onwards.
137 }
138 });
139 if (!requestQueueRet.isOk()) {
140 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
141 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700142 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700144
145 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700146 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700147 [&resQueue](const auto& descriptor) {
148 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
149 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700150 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700151 resQueue = nullptr;
152 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700153 }
154 });
155 if (!resultQueueRet.isOk()) {
156 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
157 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700158 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700160 IF_ALOGV() {
161 session->interfaceChain([](
162 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
163 ALOGV("Session interface chain:");
164 for (auto iface : interfaceChain) {
165 ALOGV(" %s", iface.c_str());
166 }
167 });
168 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700169
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700170 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000171 std::string providerType;
172 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000173 mTagMonitor.initialize(mVendorTagId);
174 if (!monitorTags.isEmpty()) {
175 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
176 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800177
178 return initializeCommonLocked();
179}
180
181status_t Camera3Device::initializeCommonLocked() {
182
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700183 /** Start up status tracker thread */
184 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800185 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700186 if (res != OK) {
187 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
188 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800189 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700190 mStatusTracker.clear();
191 return res;
192 }
193
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700194 /** Register in-flight map to the status tracker */
195 mInFlightStatusId = mStatusTracker->addComponent();
196
Zhijun He125684a2015-12-26 15:07:30 -0800197 /** Create buffer manager */
198 mBufferManager = new Camera3BufferManager();
199
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000200 Vector<int32_t> sessionParamKeys;
201 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
202 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
203 if (sessionKeysEntry.count > 0) {
204 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
205 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700206 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000207 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800208 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800209 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700210 SET_ERR_L("Unable to start request queue thread: %s (%d)",
211 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800212 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800213 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800214 return res;
215 }
216
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700217 mPreparerThread = new PreparerThread();
218
Ruben Brunk183f0562015-08-12 12:55:02 -0700219 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800220 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700221 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700222 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700223 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800224
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800225 // Measure the clock domain offset between camera and video/hw_composer
226 camera_metadata_entry timestampSource =
227 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
228 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
229 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
230 mTimestampOffset = getMonoToBoottimeOffset();
231 }
232
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700233 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100234 camera_metadata_entry partialResultsCount =
235 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
236 if (partialResultsCount.count > 0) {
237 mNumPartialResults = partialResultsCount.data.i32[0];
238 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700239 }
240
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700241 camera_metadata_entry configs =
242 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
243 for (uint32_t i = 0; i < configs.count; i += 4) {
244 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
245 configs.data.i32[i + 3] ==
246 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
247 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
248 configs.data.i32[i + 2]));
249 }
250 }
251
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700252 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
253 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
254 if (res != OK) {
255 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
256 return res;
257 }
258 }
259
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800260 return OK;
261}
262
263status_t Camera3Device::disconnect() {
264 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 Mutex::Autolock il(mInterfaceLock);
Emilian Peev26d975d2018-07-05 14:52:57 +0100266 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800267
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700268 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800269
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700270 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700271 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700272 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 {
274 Mutex::Autolock l(mLock);
275 if (mStatus == STATUS_UNINITIALIZED) return res;
276
277 if (mStatus == STATUS_ACTIVE ||
278 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
279 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700280 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700282 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700283 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700284 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700285 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700286 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
287 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700288 // Continue to close device even in case of error
289 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700290 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800291 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800292
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700293 if (mStatus == STATUS_ERROR) {
294 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296
297 if (mStatusTracker != NULL) {
298 mStatusTracker->requestExit();
299 }
300
301 if (mRequestThread != NULL) {
302 mRequestThread->requestExit();
303 }
304
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700305 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
306 for (size_t i = 0; i < mOutputStreams.size(); i++) {
307 streams.push_back(mOutputStreams[i]);
308 }
309 if (mInputStream != nullptr) {
310 streams.push_back(mInputStream);
311 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 }
313
314 // Joining done without holding mLock, otherwise deadlocks may ensue
315 // as the threads try to access parent state
316 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
317 // HAL may be in a bad state, so waiting for request thread
318 // (which may be stuck in the HAL processCaptureRequest call)
319 // could be dangerous.
320 mRequestThread->join();
321 }
322
323 if (mStatusTracker != NULL) {
324 mStatusTracker->join();
325 }
326
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800327 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 {
329 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800330 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800332 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800334
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700335 // Call close without internal mutex held, as the HAL close may need to
336 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800337 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700338
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 flushInflightRequests();
340
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700341 {
342 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800343 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700344 mOutputStreams.clear();
345 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700346 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700347 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700348 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700349 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800350
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700351 for (auto& weakStream : streams) {
352 sp<Camera3StreamInterface> stream = weakStream.promote();
353 if (stream != nullptr) {
354 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
355 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
356 }
357 }
358
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700359 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700360 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800361}
362
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363// For dumping/debugging only -
364// try to acquire a lock a few times, eventually give up to proceed with
365// debug/dump operations
366bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
367 bool gotLock = false;
368 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
369 if (lock.tryLock() == NO_ERROR) {
370 gotLock = true;
371 break;
372 } else {
373 usleep(kDumpSleepDuration);
374 }
375 }
376 return gotLock;
377}
378
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700379Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
380 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100381 const int STREAM_CONFIGURATION_SIZE = 4;
382 const int STREAM_FORMAT_OFFSET = 0;
383 const int STREAM_WIDTH_OFFSET = 1;
384 const int STREAM_HEIGHT_OFFSET = 2;
385 const int STREAM_IS_INPUT_OFFSET = 3;
386 camera_metadata_ro_entry_t availableStreamConfigs =
387 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
388 if (availableStreamConfigs.count == 0 ||
389 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
390 return Size(0, 0);
391 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700392
Emilian Peev08dd2452017-04-06 16:55:14 +0100393 // Get max jpeg size (area-wise).
394 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
395 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
396 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
397 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
398 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
399 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
400 && format == HAL_PIXEL_FORMAT_BLOB &&
401 (width * height > maxJpegWidth * maxJpegHeight)) {
402 maxJpegWidth = width;
403 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700404 }
405 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100406
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700407 return Size(maxJpegWidth, maxJpegHeight);
408}
409
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800410nsecs_t Camera3Device::getMonoToBoottimeOffset() {
411 // try three times to get the clock offset, choose the one
412 // with the minimum gap in measurements.
413 const int tries = 3;
414 nsecs_t bestGap, measured;
415 for (int i = 0; i < tries; ++i) {
416 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
417 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
418 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
419 const nsecs_t gap = tmono2 - tmono;
420 if (i == 0 || gap < bestGap) {
421 bestGap = gap;
422 measured = tbase - ((tmono + tmono2) >> 1);
423 }
424 }
425 return measured;
426}
427
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800428hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
429 int frameworkFormat) {
430 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
431}
432
433DataspaceFlags Camera3Device::mapToHidlDataspace(
434 android_dataspace dataSpace) {
435 return dataSpace;
436}
437
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700438BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100439 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700440 return usage;
441}
442
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800443StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
444 switch (rotation) {
445 case CAMERA3_STREAM_ROTATION_0:
446 return StreamRotation::ROTATION_0;
447 case CAMERA3_STREAM_ROTATION_90:
448 return StreamRotation::ROTATION_90;
449 case CAMERA3_STREAM_ROTATION_180:
450 return StreamRotation::ROTATION_180;
451 case CAMERA3_STREAM_ROTATION_270:
452 return StreamRotation::ROTATION_270;
453 }
454 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
455 return StreamRotation::ROTATION_0;
456}
457
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800458status_t Camera3Device::mapToStreamConfigurationMode(
459 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
460 if (mode == nullptr) return BAD_VALUE;
461 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
462 switch(operationMode) {
463 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
464 *mode = StreamConfigurationMode::NORMAL_MODE;
465 break;
466 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
467 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
468 break;
469 default:
470 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
471 return BAD_VALUE;
472 }
473 } else {
474 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800475 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800476 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800477}
478
479camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
480 switch (status) {
481 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
482 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
483 }
484 return CAMERA3_BUFFER_STATUS_ERROR;
485}
486
487int Camera3Device::mapToFrameworkFormat(
488 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
489 return static_cast<uint32_t>(pixelFormat);
490}
491
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700492android_dataspace Camera3Device::mapToFrameworkDataspace(
493 DataspaceFlags dataSpace) {
494 return static_cast<android_dataspace>(dataSpace);
495}
496
Emilian Peev050f5dc2017-05-18 14:43:56 +0100497uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700498 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700499 return usage;
500}
501
Emilian Peev050f5dc2017-05-18 14:43:56 +0100502uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700503 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700504 return usage;
505}
506
Zhijun Hef7da0962014-04-24 13:27:56 -0700507ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700508 // Get max jpeg size (area-wise).
509 Size maxJpegResolution = getMaxJpegResolution();
510 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
512 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700513 return BAD_VALUE;
514 }
515
Zhijun Hef7da0962014-04-24 13:27:56 -0700516 // Get max jpeg buffer size
517 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700518 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
519 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800520 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
521 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700522 return BAD_VALUE;
523 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700524 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800525 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700526
527 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700528 float scaleFactor = ((float) (width * height)) /
529 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800530 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
531 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700532 if (jpegBufferSize > maxJpegBufferSize) {
533 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700534 }
535
536 return jpegBufferSize;
537}
538
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700539ssize_t Camera3Device::getPointCloudBufferSize() const {
540 const int FLOATS_PER_POINT=4;
541 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
542 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800543 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
544 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700545 return BAD_VALUE;
546 }
547 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
548 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
549 return maxBytesForPointCloud;
550}
551
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800552ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800553 const int PER_CONFIGURATION_SIZE = 3;
554 const int WIDTH_OFFSET = 0;
555 const int HEIGHT_OFFSET = 1;
556 const int SIZE_OFFSET = 2;
557 camera_metadata_ro_entry rawOpaqueSizes =
558 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800559 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800560 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800561 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
562 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800563 return BAD_VALUE;
564 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700565
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800566 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
567 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
568 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
569 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
570 }
571 }
572
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800573 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
574 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800575 return BAD_VALUE;
576}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700577
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800578status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
579 ATRACE_CALL();
580 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700581
582 // Try to lock, but continue in case of failure (to avoid blocking in
583 // deadlocks)
584 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
585 bool gotLock = tryLockSpinRightRound(mLock);
586
587 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800588 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
589 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700590 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
592 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700593
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800594 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700595
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800596 String16 templatesOption("-t");
597 int n = args.size();
598 for (int i = 0; i < n; i++) {
599 if (args[i] == templatesOption) {
600 dumpTemplates = true;
601 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000602 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700603 if (i + 1 < n) {
604 String8 monitorTags = String8(args[i + 1]);
605 if (monitorTags == "off") {
606 mTagMonitor.disableMonitoring();
607 } else {
608 mTagMonitor.parseTagsToMonitor(monitorTags);
609 }
610 } else {
611 mTagMonitor.disableMonitoring();
612 }
613 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800614 }
615
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800616 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800617
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800618 const char *status =
619 mStatus == STATUS_ERROR ? "ERROR" :
620 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700621 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
622 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800623 mStatus == STATUS_ACTIVE ? "ACTIVE" :
624 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800626 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700627 if (mStatus == STATUS_ERROR) {
628 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
629 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800630 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800631 const char *mode =
632 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
633 mOperatingMode == static_cast<int>(
634 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
635 "CUSTOM";
636 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800637
638 if (mInputStream != NULL) {
639 write(fd, lines.string(), lines.size());
640 mInputStream->dump(fd, args);
641 } else {
642 lines.appendFormat(" No input stream.\n");
643 write(fd, lines.string(), lines.size());
644 }
645 for (size_t i = 0; i < mOutputStreams.size(); i++) {
646 mOutputStreams[i]->dump(fd,args);
647 }
648
Zhijun He431503c2016-03-07 17:30:16 -0800649 if (mBufferManager != NULL) {
650 lines = String8(" Camera3 Buffer Manager:\n");
651 write(fd, lines.string(), lines.size());
652 mBufferManager->dump(fd, args);
653 }
Zhijun He125684a2015-12-26 15:07:30 -0800654
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700655 lines = String8(" In-flight requests:\n");
656 if (mInFlightMap.size() == 0) {
657 lines.append(" None\n");
658 } else {
659 for (size_t i = 0; i < mInFlightMap.size(); i++) {
660 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700661 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700662 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800663 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700664 r.numBuffersLeft);
665 }
666 }
667 write(fd, lines.string(), lines.size());
668
Shuzhen Wang686f6442017-06-20 16:16:04 -0700669 if (mRequestThread != NULL) {
670 mRequestThread->dumpCaptureRequestLatency(fd,
671 " ProcessCaptureRequest latency histogram:");
672 }
673
Igor Murashkin1e479c02013-09-06 16:55:14 -0700674 {
675 lines = String8(" Last request sent:\n");
676 write(fd, lines.string(), lines.size());
677
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700678 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700679 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
680 }
681
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800682 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800683 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800684 "TEMPLATE_PREVIEW",
685 "TEMPLATE_STILL_CAPTURE",
686 "TEMPLATE_VIDEO_RECORD",
687 "TEMPLATE_VIDEO_SNAPSHOT",
688 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800689 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800690 };
691
692 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800693 camera_metadata_t *templateRequest = nullptr;
694 mInterface->constructDefaultRequestSettings(
695 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800696 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800697 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800698 lines.append(" Not supported\n");
699 write(fd, lines.string(), lines.size());
700 } else {
701 write(fd, lines.string(), lines.size());
702 dump_indented_camera_metadata(templateRequest,
703 fd, /*verbosity*/2, /*indentation*/8);
704 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800705 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800706 }
707 }
708
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700709 mTagMonitor.dumpMonitoredMetadata(fd);
710
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800712 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800713 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800716
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700717 if (gotLock) mLock.unlock();
718 if (gotInterfaceLock) mInterfaceLock.unlock();
719
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800720 return OK;
721}
722
723const CameraMetadata& Camera3Device::info() const {
724 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800725 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
726 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700727 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 mStatus == STATUS_ERROR ?
729 "when in error state" : "before init");
730 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800731 return mDeviceInfo;
732}
733
Jianing Wei90e59c92014-03-12 18:29:36 -0700734status_t Camera3Device::checkStatusOkToCaptureLocked() {
735 switch (mStatus) {
736 case STATUS_ERROR:
737 CLOGE("Device has encountered a serious error");
738 return INVALID_OPERATION;
739 case STATUS_UNINITIALIZED:
740 CLOGE("Device not initialized");
741 return INVALID_OPERATION;
742 case STATUS_UNCONFIGURED:
743 case STATUS_CONFIGURED:
744 case STATUS_ACTIVE:
745 // OK
746 break;
747 default:
748 SET_ERR_L("Unexpected status: %d", mStatus);
749 return INVALID_OPERATION;
750 }
751 return OK;
752}
753
754status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000755 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 const std::list<const SurfaceMap> &surfaceMaps,
757 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700758 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700759 if (requestList == NULL) {
760 CLOGE("requestList cannot be NULL.");
761 return BAD_VALUE;
762 }
763
Jianing Weicb0652e2014-03-12 18:29:36 -0700764 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000765 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700766 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
767 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
768 ++metadataIt, ++surfaceMapIt) {
769 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700770 if (newRequest == 0) {
771 CLOGE("Can't create capture request");
772 return BAD_VALUE;
773 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700774
Shuzhen Wang9d066012016-09-30 11:30:20 -0700775 newRequest->mRepeating = repeating;
776
Jianing Weicb0652e2014-03-12 18:29:36 -0700777 // Setup burst Id and request Id
778 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000779 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
780 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700781 CLOGE("RequestID entry exists; but must not be empty in metadata");
782 return BAD_VALUE;
783 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000784 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
785 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700786 } else {
787 CLOGE("RequestID does not exist in metadata");
788 return BAD_VALUE;
789 }
790
Jianing Wei90e59c92014-03-12 18:29:36 -0700791 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700792
793 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700794 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700795 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
796 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
797 return BAD_VALUE;
798 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700799
800 // Setup batch size if this is a high speed video recording request.
801 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
802 auto firstRequest = requestList->begin();
803 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
804 if (outputStream->isVideoStream()) {
805 (*firstRequest)->mBatchSize = requestList->size();
806 break;
807 }
808 }
809 }
810
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 return OK;
812}
813
Jianing Weicb0652e2014-03-12 18:29:36 -0700814status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800815 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800816
Emilian Peevaebbe412018-01-15 13:53:24 +0000817 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700818 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000819 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820
Emilian Peevaebbe412018-01-15 13:53:24 +0000821 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822}
823
Emilian Peevaebbe412018-01-15 13:53:24 +0000824void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700825 std::list<const SurfaceMap>& surfaceMaps,
826 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000827 PhysicalCameraSettingsList requestList;
828 requestList.push_back({std::string(getId().string()), request});
829 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830
831 SurfaceMap surfaceMap;
832 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
833 // With no surface list passed in, stream and surface will have 1-to-1
834 // mapping. So the surface index is 0 for each stream in the surfaceMap.
835 for (size_t i = 0; i < streams.count; i++) {
836 surfaceMap[streams.data.i32[i]].push_back(0);
837 }
838 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800839}
840
Jianing Wei90e59c92014-03-12 18:29:36 -0700841status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000842 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700843 const std::list<const SurfaceMap> &surfaceMaps,
844 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700845 /*out*/
846 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700847 ATRACE_CALL();
848 Mutex::Autolock il(mInterfaceLock);
849 Mutex::Autolock l(mLock);
850
851 status_t res = checkStatusOkToCaptureLocked();
852 if (res != OK) {
853 // error logged by previous call
854 return res;
855 }
856
857 RequestList requestList;
858
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
860 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700861 if (res != OK) {
862 // error logged by previous call
863 return res;
864 }
865
866 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700867 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700869 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 }
871
872 if (res == OK) {
873 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
874 if (res != OK) {
875 SET_ERR_L("Can't transition to active in %f seconds!",
876 kActiveTimeout/1e9);
877 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800878 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700879 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700880 } else {
881 CLOGE("Cannot queue request. Impossible.");
882 return BAD_VALUE;
883 }
884
885 return res;
886}
887
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800888hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800889 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800890 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700891 // Ideally we should grab mLock, but that can lead to deadlock, and
892 // it's not super important to get up to date value of mStatus for this
893 // warning print, hence skipping the lock here
894 if (mStatus == STATUS_ERROR) {
895 // Per API contract, HAL should act as closed after device error
896 // But mStatus can be set to error by framework as well, so just log
897 // a warning here.
898 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700899 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700900
901 if (mProcessCaptureResultLock.tryLock() != OK) {
902 // This should never happen; it indicates a wrong client implementation
903 // that doesn't follow the contract. But, we can be tolerant here.
904 ALOGE("%s: callback overlapped! waiting 1s...",
905 __FUNCTION__);
906 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
907 ALOGE("%s: cannot acquire lock in 1s, dropping results",
908 __FUNCTION__);
909 // really don't know what to do, so bail out.
910 return hardware::Void();
911 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800912 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700913 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800914 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700915 }
916 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800917 return hardware::Void();
918}
919
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800920// Only one processCaptureResult should be called at a time, so
921// the locks won't block. The locks are present here simply to enforce this.
922hardware::Return<void> Camera3Device::processCaptureResult(
923 const hardware::hidl_vec<
924 hardware::camera::device::V3_2::CaptureResult>& results) {
925 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
926
927 // Ideally we should grab mLock, but that can lead to deadlock, and
928 // it's not super important to get up to date value of mStatus for this
929 // warning print, hence skipping the lock here
930 if (mStatus == STATUS_ERROR) {
931 // Per API contract, HAL should act as closed after device error
932 // But mStatus can be set to error by framework as well, so just log
933 // a warning here.
934 ALOGW("%s: received capture result in error state.", __FUNCTION__);
935 }
936
937 if (mProcessCaptureResultLock.tryLock() != OK) {
938 // This should never happen; it indicates a wrong client implementation
939 // that doesn't follow the contract. But, we can be tolerant here.
940 ALOGE("%s: callback overlapped! waiting 1s...",
941 __FUNCTION__);
942 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
943 ALOGE("%s: cannot acquire lock in 1s, dropping results",
944 __FUNCTION__);
945 // really don't know what to do, so bail out.
946 return hardware::Void();
947 }
948 }
949 for (const auto& result : results) {
950 processOneCaptureResultLocked(result, noPhysMetadata);
951 }
952 mProcessCaptureResultLock.unlock();
953 return hardware::Void();
954}
955
956status_t Camera3Device::readOneCameraMetadataLocked(
957 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
958 const hardware::camera::device::V3_2::CameraMetadata& result) {
959 if (fmqResultSize > 0) {
960 resultMetadata.resize(fmqResultSize);
961 if (mResultMetadataQueue == nullptr) {
962 return NO_MEMORY; // logged in initialize()
963 }
964 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
965 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
966 __FUNCTION__, fmqResultSize);
967 return INVALID_OPERATION;
968 }
969 } else {
970 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
971 result.size());
972 }
973
974 if (resultMetadata.size() != 0) {
975 status_t res;
976 const camera_metadata_t* metadata =
977 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
978 size_t expected_metadata_size = resultMetadata.size();
979 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
980 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
981 __FUNCTION__, strerror(-res), res);
982 return INVALID_OPERATION;
983 }
984 }
985
986 return OK;
987}
988
Yifan Honga640c5a2017-04-12 16:30:31 -0700989void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800990 const hardware::camera::device::V3_2::CaptureResult& result,
991 const hardware::hidl_vec<
992 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800993 camera3_capture_result r;
994 status_t res;
995 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700996
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800997 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -0700998 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800999 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1000 if (res != OK) {
1001 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1002 __FUNCTION__, result.frameNumber);
1003 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001004 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001005 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001006
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001007 // Read and validate physical camera metadata
1008 size_t physResultCount = physicalCameraMetadatas.size();
1009 std::vector<const char*> physCamIds(physResultCount);
1010 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1011 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1012 physResultMetadata.resize(physResultCount);
1013 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1014 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1015 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1016 if (res != OK) {
1017 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1018 __FUNCTION__, result.frameNumber,
1019 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001020 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001021 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001022 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1023 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1024 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001025 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001026 r.num_physcam_metadata = physResultCount;
1027 r.physcam_ids = physCamIds.data();
1028 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001029
1030 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1031 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1032 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1033 auto& bDst = outputBuffers[i];
1034 const StreamBuffer &bSrc = result.outputBuffers[i];
1035
1036 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001037 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001038 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1039 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001040 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001041 }
1042 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1043
1044 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001045 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001046 if (res != OK) {
1047 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1048 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001050 }
1051 bDst.buffer = buffer;
1052 bDst.status = mapHidlBufferStatus(bSrc.status);
1053 bDst.acquire_fence = -1;
1054 if (bSrc.releaseFence == nullptr) {
1055 bDst.release_fence = -1;
1056 } else if (bSrc.releaseFence->numFds == 1) {
1057 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1058 } else {
1059 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1060 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001061 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001062 }
1063 }
1064 r.num_output_buffers = outputBuffers.size();
1065 r.output_buffers = outputBuffers.data();
1066
1067 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001068 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001069 r.input_buffer = nullptr;
1070 } else {
1071 if (mInputStream->getId() != result.inputBuffer.streamId) {
1072 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1073 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001074 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001075 }
1076 inputBuffer.stream = mInputStream->asHalStream();
1077 buffer_handle_t *buffer;
1078 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1079 &buffer);
1080 if (res != OK) {
1081 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1082 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001083 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001084 }
1085 inputBuffer.buffer = buffer;
1086 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1087 inputBuffer.acquire_fence = -1;
1088 if (result.inputBuffer.releaseFence == nullptr) {
1089 inputBuffer.release_fence = -1;
1090 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1091 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1092 } else {
1093 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1094 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001095 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001096 }
1097 r.input_buffer = &inputBuffer;
1098 }
1099
1100 r.partial_result = result.partialResult;
1101
1102 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001103}
1104
1105hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001106 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001107 // Ideally we should grab mLock, but that can lead to deadlock, and
1108 // it's not super important to get up to date value of mStatus for this
1109 // warning print, hence skipping the lock here
1110 if (mStatus == STATUS_ERROR) {
1111 // Per API contract, HAL should act as closed after device error
1112 // But mStatus can be set to error by framework as well, so just log
1113 // a warning here.
1114 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001115 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001116
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001117 for (const auto& msg : msgs) {
1118 notify(msg);
1119 }
1120 return hardware::Void();
1121}
1122
1123void Camera3Device::notify(
1124 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1125
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001126 camera3_notify_msg m;
1127 switch (msg.type) {
1128 case MsgType::ERROR:
1129 m.type = CAMERA3_MSG_ERROR;
1130 m.message.error.frame_number = msg.msg.error.frameNumber;
1131 if (msg.msg.error.errorStreamId >= 0) {
1132 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001133 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001134 ALOGE("%s: Frame %d: Invalid error stream id %d",
1135 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001136 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001137 }
1138 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1139 } else {
1140 m.message.error.error_stream = nullptr;
1141 }
1142 switch (msg.msg.error.errorCode) {
1143 case ErrorCode::ERROR_DEVICE:
1144 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1145 break;
1146 case ErrorCode::ERROR_REQUEST:
1147 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1148 break;
1149 case ErrorCode::ERROR_RESULT:
1150 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1151 break;
1152 case ErrorCode::ERROR_BUFFER:
1153 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1154 break;
1155 }
1156 break;
1157 case MsgType::SHUTTER:
1158 m.type = CAMERA3_MSG_SHUTTER;
1159 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1160 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1161 break;
1162 }
1163 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001164}
1165
Emilian Peevaebbe412018-01-15 13:53:24 +00001166status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001167 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001168 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001169 ATRACE_CALL();
1170
Emilian Peevaebbe412018-01-15 13:53:24 +00001171 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001172}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001173
Jianing Weicb0652e2014-03-12 18:29:36 -07001174status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1175 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Emilian Peevaebbe412018-01-15 13:53:24 +00001178 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001179 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001180 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001184}
1185
Emilian Peevaebbe412018-01-15 13:53:24 +00001186status_t Camera3Device::setStreamingRequestList(
1187 const List<const PhysicalCameraSettingsList> &requestsList,
1188 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001189 ATRACE_CALL();
1190
Emilian Peevaebbe412018-01-15 13:53:24 +00001191 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001192}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193
1194sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 status_t res;
1197
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001198 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001199 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1200 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001201 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1202 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001203 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001205 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001207 } else if (mStatus == STATUS_UNCONFIGURED) {
1208 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001209 CLOGE("No streams configured");
1210 return NULL;
1211 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 }
1213
Shuzhen Wang0129d522016-10-30 22:43:41 -07001214 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001216}
1217
Jianing Weicb0652e2014-03-12 18:29:36 -07001218status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001222
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 switch (mStatus) {
1224 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001225 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 return INVALID_OPERATION;
1227 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001228 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001230 case STATUS_UNCONFIGURED:
1231 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 case STATUS_ACTIVE:
1233 // OK
1234 break;
1235 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001236 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 return INVALID_OPERATION;
1238 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001239 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001240
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001241 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001242}
1243
1244status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1245 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001248 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249}
1250
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001251status_t Camera3Device::createInputStream(
1252 uint32_t width, uint32_t height, int format, int *id) {
1253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001255 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001256 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001257 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1258 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001259
1260 status_t res;
1261 bool wasActive = false;
1262
1263 switch (mStatus) {
1264 case STATUS_ERROR:
1265 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1266 return INVALID_OPERATION;
1267 case STATUS_UNINITIALIZED:
1268 ALOGE("%s: Device not initialized", __FUNCTION__);
1269 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 case STATUS_UNCONFIGURED:
1271 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001272 // OK
1273 break;
1274 case STATUS_ACTIVE:
1275 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001276 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001277 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001279 return res;
1280 }
1281 wasActive = true;
1282 break;
1283 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285 return INVALID_OPERATION;
1286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288
1289 if (mInputStream != 0) {
1290 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1291 return INVALID_OPERATION;
1292 }
1293
1294 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1295 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001296 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001297
1298 mInputStream = newStream;
1299
1300 *id = mNextStreamId++;
1301
1302 // Continue captures if active at start
1303 if (wasActive) {
1304 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001305 // Reuse current operating mode and session parameters for new stream config
1306 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001307 if (res != OK) {
1308 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1309 __FUNCTION__, mNextStreamId, strerror(-res), res);
1310 return res;
1311 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 }
1314
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001315 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316 return OK;
1317}
1318
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001319status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001320 uint32_t width, uint32_t height, int format,
1321 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001322 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001323 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001324 ATRACE_CALL();
1325
1326 if (consumer == nullptr) {
1327 ALOGE("%s: consumer must not be null", __FUNCTION__);
1328 return BAD_VALUE;
1329 }
1330
1331 std::vector<sp<Surface>> consumers;
1332 consumers.push_back(consumer);
1333
1334 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001335 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1336 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001337}
1338
1339status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1340 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1341 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001342 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001343 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001345
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001346 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001347 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001349 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001350 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1351 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1352 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001353
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 status_t res;
1355 bool wasActive = false;
1356
1357 switch (mStatus) {
1358 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001359 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001360 return INVALID_OPERATION;
1361 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001362 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001364 case STATUS_UNCONFIGURED:
1365 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 // OK
1367 break;
1368 case STATUS_ACTIVE:
1369 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001370 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001372 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 return res;
1374 }
1375 wasActive = true;
1376 break;
1377 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001378 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379 return INVALID_OPERATION;
1380 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001381 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382
1383 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001384
Shuzhen Wang0129d522016-10-30 22:43:41 -07001385 if (consumers.size() == 0 && !hasDeferredConsumer) {
1386 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1387 return BAD_VALUE;
1388 }
Zhijun He5d677d12016-05-29 16:52:39 -07001389
Shuzhen Wang0129d522016-10-30 22:43:41 -07001390 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001391 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1392 return BAD_VALUE;
1393 }
1394
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001396 ssize_t blobBufferSize;
1397 if (dataSpace != HAL_DATASPACE_DEPTH) {
1398 blobBufferSize = getJpegBufferSize(width, height);
1399 if (blobBufferSize <= 0) {
1400 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1401 return BAD_VALUE;
1402 }
1403 } else {
1404 blobBufferSize = getPointCloudBufferSize();
1405 if (blobBufferSize <= 0) {
1406 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1407 return BAD_VALUE;
1408 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001409 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001410 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001411 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001412 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001413 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1414 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1415 if (rawOpaqueBufferSize <= 0) {
1416 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1417 return BAD_VALUE;
1418 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001419 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001420 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001421 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001422 } else if (isShared) {
1423 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1424 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001425 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001426 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001427 newStream = new Camera3OutputStream(mNextStreamId,
1428 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001429 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001431 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001432 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001433 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 }
Emilian Peev40ead602017-09-26 15:46:36 +01001435
1436 size_t consumerCount = consumers.size();
1437 for (size_t i = 0; i < consumerCount; i++) {
1438 int id = newStream->getSurfaceId(consumers[i]);
1439 if (id < 0) {
1440 SET_ERR_L("Invalid surface id");
1441 return BAD_VALUE;
1442 }
1443 if (surfaceIds != nullptr) {
1444 surfaceIds->push_back(id);
1445 }
1446 }
1447
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449
Emilian Peev08dd2452017-04-06 16:55:14 +01001450 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 res = mOutputStreams.add(mNextStreamId, newStream);
1453 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 return res;
1456 }
1457
1458 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001459 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460
1461 // Continue captures if active at start
1462 if (wasActive) {
1463 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001464 // Reuse current operating mode and session parameters for new stream config
1465 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001467 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1468 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return res;
1470 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001471 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475}
1476
Emilian Peev710c1422017-08-30 11:19:38 +01001477status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001479 if (nullptr == streamInfo) {
1480 return BAD_VALUE;
1481 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 switch (mStatus) {
1486 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return INVALID_OPERATION;
1489 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
1493 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 case STATUS_ACTIVE:
1495 // OK
1496 break;
1497 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 }
1501
1502 ssize_t idx = mOutputStreams.indexOfKey(id);
1503 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return idx;
1506 }
1507
Emilian Peev710c1422017-08-30 11:19:38 +01001508 streamInfo->width = mOutputStreams[idx]->getWidth();
1509 streamInfo->height = mOutputStreams[idx]->getHeight();
1510 streamInfo->format = mOutputStreams[idx]->getFormat();
1511 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1512 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1513 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001514 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1515 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001517}
1518
1519status_t Camera3Device::setStreamTransform(int id,
1520 int transform) {
1521 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 switch (mStatus) {
1526 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001530 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 case STATUS_UNCONFIGURED:
1533 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 case STATUS_ACTIVE:
1535 // OK
1536 break;
1537 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 }
1541
1542 ssize_t idx = mOutputStreams.indexOfKey(id);
1543 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001544 CLOGE("Stream %d does not exist",
1545 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 return BAD_VALUE;
1547 }
1548
1549 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001550}
1551
1552status_t Camera3Device::deleteStream(int id) {
1553 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001554 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 Mutex::Autolock l(mLock);
1556 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001558 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001559
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 // CameraDevice semantics require device to already be idle before
1561 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001563 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001564 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 }
1566
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001567 if (mStatus == STATUS_ERROR) {
1568 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1569 __FUNCTION__, mId.string());
1570 return -EBUSY;
1571 }
1572
Igor Murashkin2fba5842013-04-22 14:03:54 -07001573 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001574 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 if (mInputStream != NULL && id == mInputStream->getId()) {
1576 deletedStream = mInputStream;
1577 mInputStream.clear();
1578 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001579 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001580 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 return BAD_VALUE;
1582 }
Zhijun He5f446352014-01-22 09:49:33 -08001583 }
1584
1585 // Delete output stream or the output part of a bi-directional stream.
1586 if (outputStreamIdx != NAME_NOT_FOUND) {
1587 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 mOutputStreams.removeItem(id);
1589 }
1590
1591 // Free up the stream endpoint so that it can be used by some other stream
1592 res = deletedStream->disconnect();
1593 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001594 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 // fall through since we want to still list the stream as deleted.
1596 }
1597 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001598 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599
1600 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001601}
1602
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001603status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001604 ATRACE_CALL();
1605 ALOGV("%s: E", __FUNCTION__);
1606
1607 Mutex::Autolock il(mInterfaceLock);
1608 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001609
Emilian Peev811d2952018-05-25 11:08:40 +01001610 // In case the client doesn't include any session parameter, try a
1611 // speculative configuration using the values from the last cached
1612 // default request.
1613 if (sessionParams.isEmpty() &&
1614 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1615 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1616 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1617 mLastTemplateId);
1618 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1619 operatingMode);
1620 }
1621
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001622 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1623}
1624
1625status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1626 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001627 //Filter out any incoming session parameters
1628 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001629 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1630 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001631 CameraMetadata filteredParams(availableSessionKeys.count);
1632 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1633 filteredParams.getAndLock());
1634 set_camera_metadata_vendor_id(meta, mVendorTagId);
1635 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001636 if (availableSessionKeys.count > 0) {
1637 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1638 camera_metadata_ro_entry entry = params.find(
1639 availableSessionKeys.data.i32[i]);
1640 if (entry.count > 0) {
1641 filteredParams.update(entry);
1642 }
1643 }
1644 }
1645
1646 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001647}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001649status_t Camera3Device::getInputBufferProducer(
1650 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001651 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001652 Mutex::Autolock il(mInterfaceLock);
1653 Mutex::Autolock l(mLock);
1654
1655 if (producer == NULL) {
1656 return BAD_VALUE;
1657 } else if (mInputStream == NULL) {
1658 return INVALID_OPERATION;
1659 }
1660
1661 return mInputStream->getInputBufferProducer(producer);
1662}
1663
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664status_t Camera3Device::createDefaultRequest(int templateId,
1665 CameraMetadata *request) {
1666 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001667 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001668
1669 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1670 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1671 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1672 return BAD_VALUE;
1673 }
1674
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001676
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001677 {
1678 Mutex::Autolock l(mLock);
1679 switch (mStatus) {
1680 case STATUS_ERROR:
1681 CLOGE("Device has encountered a serious error");
1682 return INVALID_OPERATION;
1683 case STATUS_UNINITIALIZED:
1684 CLOGE("Device is not initialized!");
1685 return INVALID_OPERATION;
1686 case STATUS_UNCONFIGURED:
1687 case STATUS_CONFIGURED:
1688 case STATUS_ACTIVE:
1689 // OK
1690 break;
1691 default:
1692 SET_ERR_L("Unexpected status: %d", mStatus);
1693 return INVALID_OPERATION;
1694 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001695
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001696 if (!mRequestTemplateCache[templateId].isEmpty()) {
1697 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001698 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001699 return OK;
1700 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001701 }
1702
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001703 camera_metadata_t *rawRequest;
1704 status_t res = mInterface->constructDefaultRequestSettings(
1705 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001706
1707 {
1708 Mutex::Autolock l(mLock);
1709 if (res == BAD_VALUE) {
1710 ALOGI("%s: template %d is not supported on this camera device",
1711 __FUNCTION__, templateId);
1712 return res;
1713 } else if (res != OK) {
1714 CLOGE("Unable to construct request template %d: %s (%d)",
1715 templateId, strerror(-res), res);
1716 return res;
1717 }
1718
1719 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1720 mRequestTemplateCache[templateId].acquire(rawRequest);
1721
1722 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001723 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001724 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001725 return OK;
1726}
1727
1728status_t Camera3Device::waitUntilDrained() {
1729 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001730 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001731 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001734 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001735}
1736
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001737status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001738 switch (mStatus) {
1739 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001740 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001741 ALOGV("%s: Already idle", __FUNCTION__);
1742 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001743 case STATUS_CONFIGURED:
1744 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745 case STATUS_ERROR:
1746 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001747 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748 break;
1749 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001750 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 return INVALID_OPERATION;
1752 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001753 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1754 maxExpectedDuration);
1755 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001756 if (res != OK) {
1757 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1758 res);
1759 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 return res;
1761}
1762
Ruben Brunk183f0562015-08-12 12:55:02 -07001763
1764void Camera3Device::internalUpdateStatusLocked(Status status) {
1765 mStatus = status;
1766 mRecentStatusUpdates.add(mStatus);
1767 mStatusChanged.broadcast();
1768}
1769
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001770void Camera3Device::pauseStateNotify(bool enable) {
1771 Mutex::Autolock il(mInterfaceLock);
1772 Mutex::Autolock l(mLock);
1773
1774 mPauseStateNotify = enable;
1775}
1776
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001777// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001778status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001779 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001781 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1782 maxExpectedDuration);
1783 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001784 if (res != OK) {
1785 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001786 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001787 }
1788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 return res;
1790}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001792// Resume after internalPauseAndWaitLocked
1793status_t Camera3Device::internalResumeLocked() {
1794 status_t res;
1795
1796 mRequestThread->setPaused(false);
1797
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001798 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1799 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1801 if (res != OK) {
1802 SET_ERR_L("Can't transition to active in %f seconds!",
1803 kActiveTimeout/1e9);
1804 }
1805 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001806 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001807}
1808
Ruben Brunk183f0562015-08-12 12:55:02 -07001809status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001811
1812 size_t startIndex = 0;
1813 if (mStatusWaiters == 0) {
1814 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1815 // this status list
1816 mRecentStatusUpdates.clear();
1817 } else {
1818 // If other threads are waiting on updates to this status list, set the position of the
1819 // first element that this list will check rather than clearing the list.
1820 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 }
1822
Ruben Brunk183f0562015-08-12 12:55:02 -07001823 mStatusWaiters++;
1824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 bool stateSeen = false;
1826 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001827 if (active == (mStatus == STATUS_ACTIVE)) {
1828 // Desired state is current
1829 break;
1830 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831
1832 res = mStatusChanged.waitRelative(mLock, timeout);
1833 if (res != OK) break;
1834
Ruben Brunk183f0562015-08-12 12:55:02 -07001835 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1836 // transitions.
1837 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1838 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1839 __FUNCTION__);
1840
1841 // Encountered desired state since we began waiting
1842 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1844 stateSeen = true;
1845 break;
1846 }
1847 }
1848 } while (!stateSeen);
1849
Ruben Brunk183f0562015-08-12 12:55:02 -07001850 mStatusWaiters--;
1851
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852 return res;
1853}
1854
1855
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001856status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001857 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001858 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001859
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001860 if (listener != NULL && mListener != NULL) {
1861 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1862 }
1863 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001864 mRequestThread->setNotificationListener(listener);
1865 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001866
1867 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001868}
1869
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001870bool Camera3Device::willNotify3A() {
1871 return false;
1872}
1873
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001875 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001876 status_t res;
1877 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001878
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001879 while (mResultQueue.empty()) {
1880 res = mResultSignal.waitRelative(mOutputLock, timeout);
1881 if (res == TIMED_OUT) {
1882 return res;
1883 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001884 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1885 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001886 return res;
1887 }
1888 }
1889 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001890}
1891
Jianing Weicb0652e2014-03-12 18:29:36 -07001892status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001894 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001896 if (mResultQueue.empty()) {
1897 return NOT_ENOUGH_DATA;
1898 }
1899
Jianing Weicb0652e2014-03-12 18:29:36 -07001900 if (frame == NULL) {
1901 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1902 return BAD_VALUE;
1903 }
1904
1905 CaptureResult &result = *(mResultQueue.begin());
1906 frame->mResultExtras = result.mResultExtras;
1907 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001908 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001909 mResultQueue.erase(mResultQueue.begin());
1910
1911 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001912}
1913
1914status_t Camera3Device::triggerAutofocus(uint32_t id) {
1915 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001916 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001917
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001918 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1919 // Mix-in this trigger into the next request and only the next request.
1920 RequestTrigger trigger[] = {
1921 {
1922 ANDROID_CONTROL_AF_TRIGGER,
1923 ANDROID_CONTROL_AF_TRIGGER_START
1924 },
1925 {
1926 ANDROID_CONTROL_AF_TRIGGER_ID,
1927 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001928 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001929 };
1930
1931 return mRequestThread->queueTrigger(trigger,
1932 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001933}
1934
1935status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1936 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001937 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001938
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001939 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1940 // Mix-in this trigger into the next request and only the next request.
1941 RequestTrigger trigger[] = {
1942 {
1943 ANDROID_CONTROL_AF_TRIGGER,
1944 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1945 },
1946 {
1947 ANDROID_CONTROL_AF_TRIGGER_ID,
1948 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001949 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001950 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001952 return mRequestThread->queueTrigger(trigger,
1953 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954}
1955
1956status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1957 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001958 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001959
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001960 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1961 // Mix-in this trigger into the next request and only the next request.
1962 RequestTrigger trigger[] = {
1963 {
1964 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1965 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1966 },
1967 {
1968 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1969 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001970 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001971 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001973 return mRequestThread->queueTrigger(trigger,
1974 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001975}
1976
Jianing Weicb0652e2014-03-12 18:29:36 -07001977status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001978 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001979 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001980 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001981
Zhijun He7ef20392014-04-21 16:04:17 -07001982 {
1983 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001984 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001985 }
1986
Emilian Peev08dd2452017-04-06 16:55:14 +01001987 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001988}
1989
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001990status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001991 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1992}
1993
1994status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001995 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001996 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001997 Mutex::Autolock il(mInterfaceLock);
1998 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001999
2000 sp<Camera3StreamInterface> stream;
2001 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2002 if (outputStreamIdx == NAME_NOT_FOUND) {
2003 CLOGE("Stream %d does not exist", streamId);
2004 return BAD_VALUE;
2005 }
2006
2007 stream = mOutputStreams.editValueAt(outputStreamIdx);
2008
2009 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002010 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002011 return BAD_VALUE;
2012 }
2013
2014 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002015 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002016 return BAD_VALUE;
2017 }
2018
Ruben Brunkc78ac262015-08-13 17:58:46 -07002019 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002020}
2021
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002022status_t Camera3Device::tearDown(int streamId) {
2023 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002024 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
2027
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002028 sp<Camera3StreamInterface> stream;
2029 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2030 if (outputStreamIdx == NAME_NOT_FOUND) {
2031 CLOGE("Stream %d does not exist", streamId);
2032 return BAD_VALUE;
2033 }
2034
2035 stream = mOutputStreams.editValueAt(outputStreamIdx);
2036
2037 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2038 CLOGE("Stream %d is a target of a in-progress request", streamId);
2039 return BAD_VALUE;
2040 }
2041
2042 return stream->tearDown();
2043}
2044
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002045status_t Camera3Device::addBufferListenerForStream(int streamId,
2046 wp<Camera3StreamBufferListener> listener) {
2047 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002048 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
2052 sp<Camera3StreamInterface> stream;
2053 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2054 if (outputStreamIdx == NAME_NOT_FOUND) {
2055 CLOGE("Stream %d does not exist", streamId);
2056 return BAD_VALUE;
2057 }
2058
2059 stream = mOutputStreams.editValueAt(outputStreamIdx);
2060 stream->addBufferListener(listener);
2061
2062 return OK;
2063}
2064
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066 * Methods called by subclasses
2067 */
2068
2069void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002070 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002071 {
2072 // Need mLock to safely update state and synchronize to current
2073 // state of methods in flight.
2074 Mutex::Autolock l(mLock);
2075 // We can get various system-idle notices from the status tracker
2076 // while starting up. Only care about them if we've actually sent
2077 // in some requests recently.
2078 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2079 return;
2080 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002081 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2082 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002083 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002084
2085 // Skip notifying listener if we're doing some user-transparent
2086 // state changes
2087 if (mPauseStateNotify) return;
2088 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002089
2090 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002091 {
2092 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002093 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002094 }
2095 if (idle && listener != NULL) {
2096 listener->notifyIdle();
2097 }
2098}
2099
Shuzhen Wang758c2152017-01-10 18:26:18 -08002100status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002101 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002102 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002103 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2104 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002105
2106 if (surfaceIds == nullptr) {
2107 return BAD_VALUE;
2108 }
2109
Zhijun He5d677d12016-05-29 16:52:39 -07002110 Mutex::Autolock il(mInterfaceLock);
2111 Mutex::Autolock l(mLock);
2112
Shuzhen Wang758c2152017-01-10 18:26:18 -08002113 if (consumers.size() == 0) {
2114 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002115 return BAD_VALUE;
2116 }
2117
2118 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2119 if (idx == NAME_NOT_FOUND) {
2120 CLOGE("Stream %d is unknown", streamId);
2121 return idx;
2122 }
2123 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002124 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002125 if (res != OK) {
2126 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2127 return res;
2128 }
2129
Emilian Peev40ead602017-09-26 15:46:36 +01002130 for (auto &consumer : consumers) {
2131 int id = stream->getSurfaceId(consumer);
2132 if (id < 0) {
2133 CLOGE("Invalid surface id!");
2134 return BAD_VALUE;
2135 }
2136 surfaceIds->push_back(id);
2137 }
2138
Shuzhen Wang0129d522016-10-30 22:43:41 -07002139 if (stream->isConsumerConfigurationDeferred()) {
2140 if (!stream->isConfiguring()) {
2141 CLOGE("Stream %d was already fully configured.", streamId);
2142 return INVALID_OPERATION;
2143 }
Zhijun He5d677d12016-05-29 16:52:39 -07002144
Shuzhen Wang0129d522016-10-30 22:43:41 -07002145 res = stream->finishConfiguration();
2146 if (res != OK) {
2147 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2148 stream->getId(), strerror(-res), res);
2149 return res;
2150 }
Zhijun He5d677d12016-05-29 16:52:39 -07002151 }
2152
2153 return OK;
2154}
2155
Emilian Peev40ead602017-09-26 15:46:36 +01002156status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2157 const std::vector<OutputStreamInfo> &outputInfo,
2158 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2159 Mutex::Autolock il(mInterfaceLock);
2160 Mutex::Autolock l(mLock);
2161
2162 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2163 if (idx == NAME_NOT_FOUND) {
2164 CLOGE("Stream %d is unknown", streamId);
2165 return idx;
2166 }
2167
2168 for (const auto &it : removedSurfaceIds) {
2169 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2170 CLOGE("Shared surface still part of a pending request!");
2171 return -EBUSY;
2172 }
2173 }
2174
2175 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2176 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2177 if (res != OK) {
2178 CLOGE("Stream %d failed to update stream (error %d %s) ",
2179 streamId, res, strerror(-res));
2180 if (res == UNKNOWN_ERROR) {
2181 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2182 __FUNCTION__);
2183 }
2184 return res;
2185 }
2186
2187 return res;
2188}
2189
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002190status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2191 Mutex::Autolock il(mInterfaceLock);
2192 Mutex::Autolock l(mLock);
2193
2194 int idx = mOutputStreams.indexOfKey(streamId);
2195 if (idx == NAME_NOT_FOUND) {
2196 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2197 return BAD_VALUE;
2198 }
2199
2200 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2201 return stream->dropBuffers(dropping);
2202}
2203
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 * Camera3Device private methods
2206 */
2207
2208sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002209 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 ATRACE_CALL();
2211 status_t res;
2212
2213 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002214 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002215
2216 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002217 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002218 if (inputStreams.count > 0) {
2219 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002220 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002221 CLOGE("Request references unknown input stream %d",
2222 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 return NULL;
2224 }
2225 // Lazy completion of stream configuration (allocation/registration)
2226 // on first use
2227 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002228 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002229 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002230 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002232 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002233 return NULL;
2234 }
2235 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002236 // Check if stream is being prepared
2237 if (mInputStream->isPreparing()) {
2238 CLOGE("Request references an input stream that's being prepared!");
2239 return NULL;
2240 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241
2242 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002243 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002244 }
2245
2246 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002247 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002248 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002249 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002250 return NULL;
2251 }
2252
2253 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002254 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002256 CLOGE("Request references unknown stream %d",
2257 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 return NULL;
2259 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002260 sp<Camera3OutputStreamInterface> stream =
2261 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262
Zhijun He5d677d12016-05-29 16:52:39 -07002263 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002264 auto iter = surfaceMap.find(streams.data.i32[i]);
2265 if (iter != surfaceMap.end()) {
2266 const std::vector<size_t>& surfaces = iter->second;
2267 for (const auto& surface : surfaces) {
2268 if (stream->isConsumerConfigurationDeferred(surface)) {
2269 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2270 "due to deferred consumer", stream->getId(), surface);
2271 return NULL;
2272 }
2273 }
2274 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002275 }
2276
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002277 // Lazy completion of stream configuration (allocation/registration)
2278 // on first use
2279 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002280 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002281 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002282 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2283 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 return NULL;
2285 }
2286 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002287 // Check if stream is being prepared
2288 if (stream->isPreparing()) {
2289 CLOGE("Request references an output stream that's being prepared!");
2290 return NULL;
2291 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292
2293 newRequest->mOutputStreams.push(stream);
2294 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002295 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002296 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297
2298 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002299}
2300
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002301bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2302 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2303 Size size = mSupportedOpaqueInputSizes[i];
2304 if (size.width == width && size.height == height) {
2305 return true;
2306 }
2307 }
2308
2309 return false;
2310}
2311
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002312void Camera3Device::cancelStreamsConfigurationLocked() {
2313 int res = OK;
2314 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2315 res = mInputStream->cancelConfiguration();
2316 if (res != OK) {
2317 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2318 mInputStream->getId(), strerror(-res), res);
2319 }
2320 }
2321
2322 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2323 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2324 if (outputStream->isConfiguring()) {
2325 res = outputStream->cancelConfiguration();
2326 if (res != OK) {
2327 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2328 outputStream->getId(), strerror(-res), res);
2329 }
2330 }
2331 }
2332
2333 // Return state to that at start of call, so that future configures
2334 // properly clean things up
2335 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2336 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002337
2338 res = mPreparerThread->resume();
2339 if (res != OK) {
2340 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2341 }
2342}
2343
2344bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2345 ATRACE_CALL();
2346 bool ret = false;
2347
2348 Mutex::Autolock il(mInterfaceLock);
2349 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2350
2351 Mutex::Autolock l(mLock);
2352 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2353 if (rc == NO_ERROR) {
2354 mNeedConfig = true;
2355 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2356 if (rc == NO_ERROR) {
2357 ret = true;
2358 mPauseStateNotify = false;
2359 //Moving to active state while holding 'mLock' is important.
2360 //There could be pending calls to 'create-/deleteStream' which
2361 //will trigger another stream configuration while the already
2362 //present streams end up with outstanding buffers that will
2363 //not get drained.
2364 internalUpdateStatusLocked(STATUS_ACTIVE);
2365 } else {
2366 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2367 __FUNCTION__, rc);
2368 }
2369 } else {
2370 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2371 }
2372
2373 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002374}
2375
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002376status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002377 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 ATRACE_CALL();
2379 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002381 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002382 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 return INVALID_OPERATION;
2384 }
2385
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002386 if (operatingMode < 0) {
2387 CLOGE("Invalid operating mode: %d", operatingMode);
2388 return BAD_VALUE;
2389 }
2390
2391 bool isConstrainedHighSpeed =
2392 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2393 operatingMode;
2394
2395 if (mOperatingMode != operatingMode) {
2396 mNeedConfig = true;
2397 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2398 mOperatingMode = operatingMode;
2399 }
2400
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002401 if (!mNeedConfig) {
2402 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2403 return OK;
2404 }
2405
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002406 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2407 // adding a dummy stream instead.
2408 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2409 if (mOutputStreams.size() == 0) {
2410 addDummyStreamLocked();
2411 } else {
2412 tryRemoveDummyStreamLocked();
2413 }
2414
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002415 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002416 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002418 mPreparerThread->pause();
2419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002421 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2423
2424 Vector<camera3_stream_t*> streams;
2425 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002426 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002427
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428
2429 if (mInputStream != NULL) {
2430 camera3_stream_t *inputStream;
2431 inputStream = mInputStream->startConfiguration();
2432 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002433 CLOGE("Can't start input stream configuration");
2434 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002435 return INVALID_OPERATION;
2436 }
2437 streams.add(inputStream);
2438 }
2439
2440 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002441
2442 // Don't configure bidi streams twice, nor add them twice to the list
2443 if (mOutputStreams[i].get() ==
2444 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2445
2446 config.num_streams--;
2447 continue;
2448 }
2449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002450 camera3_stream_t *outputStream;
2451 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2452 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002453 CLOGE("Can't start output stream configuration");
2454 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455 return INVALID_OPERATION;
2456 }
2457 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002458
2459 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2460 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002461 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2462 // always occupy the initial entry.
2463 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002464 getJpegBufferSize(outputStream->width, outputStream->height));
2465 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466 }
2467
2468 config.streams = streams.editArray();
2469
2470 // Do the HAL configuration; will potentially touch stream
2471 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002472
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002473 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002474 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002475 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002477 if (res == BAD_VALUE) {
2478 // HAL rejected this set of streams as unsupported, clean up config
2479 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002480 CLOGE("Set of requested inputs/outputs not supported by HAL");
2481 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002482 return BAD_VALUE;
2483 } else if (res != OK) {
2484 // Some other kind of error from configure_streams - this is not
2485 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002486 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2487 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002488 return res;
2489 }
2490
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002491 // Finish all stream configuration immediately.
2492 // TODO: Try to relax this later back to lazy completion, which should be
2493 // faster
2494
Igor Murashkin073f8572013-05-02 14:59:28 -07002495 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002496 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002497 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002498 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002499 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002500 cancelStreamsConfigurationLocked();
2501 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002502 }
2503 }
2504
2505 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002506 sp<Camera3OutputStreamInterface> outputStream =
2507 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002508 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002509 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002510 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002511 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002512 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002513 cancelStreamsConfigurationLocked();
2514 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002515 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002516 }
2517 }
2518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002519 // Request thread needs to know to avoid using repeat-last-settings protocol
2520 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002521 if (notifyRequestThread) {
2522 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2523 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524
Zhijun He90f7c372016-08-16 16:19:43 -07002525 char value[PROPERTY_VALUE_MAX];
2526 property_get("camera.fifo.disable", value, "0");
2527 int32_t disableFifo = atoi(value);
2528 if (disableFifo != 1) {
2529 // Boost priority of request thread to SCHED_FIFO.
2530 pid_t requestThreadTid = mRequestThread->getTid();
2531 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002532 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002533 if (res != OK) {
2534 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2535 strerror(-res), res);
2536 } else {
2537 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2538 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002539 }
2540
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002541 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002542 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2543 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2544 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2545 sessionParams.unlock(newSessionParams);
2546 mSessionParams.unlock(currentSessionParams);
2547 if (updateSessionParams) {
2548 mSessionParams = sessionParams;
2549 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002550
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002551 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552
Ruben Brunk183f0562015-08-12 12:55:02 -07002553 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2554 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002556 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002557
Zhijun He0a210512014-07-24 13:45:15 -07002558 // tear down the deleted streams after configure streams.
2559 mDeletedStreams.clear();
2560
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002561 auto rc = mPreparerThread->resume();
2562 if (rc != OK) {
2563 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2564 return rc;
2565 }
2566
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002567 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002568}
2569
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002570status_t Camera3Device::addDummyStreamLocked() {
2571 ATRACE_CALL();
2572 status_t res;
2573
2574 if (mDummyStreamId != NO_STREAM) {
2575 // Should never be adding a second dummy stream when one is already
2576 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002577 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2578 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002579 return INVALID_OPERATION;
2580 }
2581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002582 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002583
2584 sp<Camera3OutputStreamInterface> dummyStream =
2585 new Camera3DummyStream(mNextStreamId);
2586
2587 res = mOutputStreams.add(mNextStreamId, dummyStream);
2588 if (res < 0) {
2589 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2590 return res;
2591 }
2592
2593 mDummyStreamId = mNextStreamId;
2594 mNextStreamId++;
2595
2596 return OK;
2597}
2598
2599status_t Camera3Device::tryRemoveDummyStreamLocked() {
2600 ATRACE_CALL();
2601 status_t res;
2602
2603 if (mDummyStreamId == NO_STREAM) return OK;
2604 if (mOutputStreams.size() == 1) return OK;
2605
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002606 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002607
2608 // Ok, have a dummy stream and there's at least one other output stream,
2609 // so remove the dummy
2610
2611 sp<Camera3StreamInterface> deletedStream;
2612 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2613 if (outputStreamIdx == NAME_NOT_FOUND) {
2614 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2615 return INVALID_OPERATION;
2616 }
2617
2618 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2619 mOutputStreams.removeItemsAt(outputStreamIdx);
2620
2621 // Free up the stream endpoint so that it can be used by some other stream
2622 res = deletedStream->disconnect();
2623 if (res != OK) {
2624 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2625 // fall through since we want to still list the stream as deleted.
2626 }
2627 mDeletedStreams.add(deletedStream);
2628 mDummyStreamId = NO_STREAM;
2629
2630 return res;
2631}
2632
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002633void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002634 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002635 Mutex::Autolock l(mLock);
2636 va_list args;
2637 va_start(args, fmt);
2638
2639 setErrorStateLockedV(fmt, args);
2640
2641 va_end(args);
2642}
2643
2644void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002645 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002646 Mutex::Autolock l(mLock);
2647 setErrorStateLockedV(fmt, args);
2648}
2649
2650void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2651 va_list args;
2652 va_start(args, fmt);
2653
2654 setErrorStateLockedV(fmt, args);
2655
2656 va_end(args);
2657}
2658
2659void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002660 // Print out all error messages to log
2661 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002662 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002663
2664 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002665 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002666
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002667 mErrorCause = errorCause;
2668
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002669 if (mRequestThread != nullptr) {
2670 mRequestThread->setPaused(true);
2671 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002672 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002673
2674 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002675 sp<NotificationListener> listener = mListener.promote();
2676 if (listener != NULL) {
2677 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002678 CaptureResultExtras());
2679 }
2680
2681 // Save stack trace. View by dumping it later.
2682 CameraTraces::saveTrace();
2683 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002684}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002685
2686/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002687 * In-flight request management
2688 */
2689
Jianing Weicb0652e2014-03-12 18:29:36 -07002690status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002691 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002692 bool hasAppCallback, nsecs_t maxExpectedDuration,
2693 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002694 ATRACE_CALL();
2695 Mutex::Autolock l(mInFlightLock);
2696
2697 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002698 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002699 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002700 if (res < 0) return res;
2701
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002702 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002703 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2704 // avoid a deadlock during reprocess requests.
2705 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002706 if (mStatusTracker != nullptr) {
2707 mStatusTracker->markComponentActive(mInFlightStatusId);
2708 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002709 }
2710
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002711 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002712 return OK;
2713}
2714
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002715void Camera3Device::returnOutputBuffers(
2716 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2717 nsecs_t timestamp) {
2718 for (size_t i = 0; i < numBuffers; i++)
2719 {
2720 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2721 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2722 // Note: stream may be deallocated at this point, if this buffer was
2723 // the last reference to it.
2724 if (res != OK) {
2725 ALOGE("Can't return buffer to its stream: %s (%d)",
2726 strerror(-res), res);
2727 }
2728 }
2729}
2730
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002731void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002732 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002733 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002734 mInFlightMap.removeItemsAt(idx, 1);
2735
2736 // Indicate idle inFlightMap to the status tracker
2737 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002738 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2739 // avoid a deadlock during reprocess requests.
2740 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002741 if (mStatusTracker != nullptr) {
2742 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2743 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002744 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002745 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002746}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002747
2748void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2749
2750 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2751 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2752
2753 nsecs_t sensorTimestamp = request.sensorTimestamp;
2754 nsecs_t shutterTimestamp = request.shutterTimestamp;
2755
2756 // Check if it's okay to remove the request from InFlightMap:
2757 // In the case of a successful request:
2758 // all input and output buffers, all result metadata, shutter callback
2759 // arrived.
2760 // In the case of a unsuccessful request:
2761 // all input and output buffers arrived.
2762 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002763 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002764 (request.haveResultMetadata && shutterTimestamp != 0))) {
2765 ATRACE_ASYNC_END("frame capture", frameNumber);
2766
Shuzhen Wang403044a2017-02-26 23:29:04 -08002767 // Sanity check - if sensor timestamp matches shutter timestamp in the
2768 // case of request having callback.
2769 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002770 sensorTimestamp != shutterTimestamp) {
2771 SET_ERR("sensor timestamp (%" PRId64
2772 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2773 sensorTimestamp, frameNumber, shutterTimestamp);
2774 }
2775
2776 // for an unsuccessful request, it may have pending output buffers to
2777 // return.
2778 assert(request.requestStatus != OK ||
2779 request.pendingOutputBuffers.size() == 0);
2780 returnOutputBuffers(request.pendingOutputBuffers.array(),
2781 request.pendingOutputBuffers.size(), 0);
2782
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002783 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002784 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2785 }
2786
2787 // Sanity check - if we have too many in-flight frames, something has
2788 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002789 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002791 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2792 kInFlightWarnLimitHighSpeed) {
2793 CLOGE("In-flight list too large for high speed configuration: %zu",
2794 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002795 }
2796}
2797
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002798void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002799 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002800 { // First return buffers cached in mInFlightMap
2801 Mutex::Autolock l(mInFlightLock);
2802 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2803 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2804 returnOutputBuffers(request.pendingOutputBuffers.array(),
2805 request.pendingOutputBuffers.size(), 0);
2806 }
2807 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002808 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002809 }
2810
2811 // Then return all inflight buffers not returned by HAL
2812 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2813 mInterface->getInflightBufferKeys(&inflightKeys);
2814
2815 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2816 for (auto& pair : inflightKeys) {
2817 int32_t frameNumber = pair.first;
2818 int32_t streamId = pair.second;
2819 buffer_handle_t* buffer;
2820 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2821 if (res != OK) {
2822 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2823 __FUNCTION__, frameNumber, streamId);
2824 continue;
2825 }
2826
2827 camera3_stream_buffer_t streamBuffer;
2828 streamBuffer.buffer = buffer;
2829 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2830 streamBuffer.acquire_fence = -1;
2831 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002832
2833 // First check if the buffer belongs to deleted stream
2834 bool streamDeleted = false;
2835 for (auto& stream : mDeletedStreams) {
2836 if (streamId == stream->getId()) {
2837 streamDeleted = true;
2838 // Return buffer to deleted stream
2839 camera3_stream* halStream = stream->asHalStream();
2840 streamBuffer.stream = halStream;
2841 switch (halStream->stream_type) {
2842 case CAMERA3_STREAM_OUTPUT:
2843 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2844 if (res != OK) {
2845 ALOGE("%s: Can't return output buffer for frame %d to"
2846 " stream %d: %s (%d)", __FUNCTION__,
2847 frameNumber, streamId, strerror(-res), res);
2848 }
2849 break;
2850 case CAMERA3_STREAM_INPUT:
2851 res = stream->returnInputBuffer(streamBuffer);
2852 if (res != OK) {
2853 ALOGE("%s: Can't return input buffer for frame %d to"
2854 " stream %d: %s (%d)", __FUNCTION__,
2855 frameNumber, streamId, strerror(-res), res);
2856 }
2857 break;
2858 default: // Bi-direcitonal stream is deprecated
2859 ALOGE("%s: stream %d has unknown stream type %d",
2860 __FUNCTION__, streamId, halStream->stream_type);
2861 break;
2862 }
2863 break;
2864 }
2865 }
2866 if (streamDeleted) {
2867 continue;
2868 }
2869
2870 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002871 if (streamId == inputStreamId) {
2872 streamBuffer.stream = mInputStream->asHalStream();
2873 res = mInputStream->returnInputBuffer(streamBuffer);
2874 if (res != OK) {
2875 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002876 " stream %d: %s (%d)", __FUNCTION__,
2877 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002878 }
2879 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002880 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2881 if (idx == NAME_NOT_FOUND) {
2882 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2883 continue;
2884 }
2885 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002886 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2887 }
2888 }
2889}
2890
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002891void Camera3Device::insertResultLocked(CaptureResult *result,
2892 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002893 if (result == nullptr) return;
2894
Emilian Peev71c73a22017-03-21 16:35:51 +00002895 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2896 result->mMetadata.getAndLock());
2897 set_camera_metadata_vendor_id(meta, mVendorTagId);
2898 result->mMetadata.unlock(meta);
2899
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002900 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2901 (int32_t*)&frameNumber, 1) != OK) {
2902 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2903 return;
2904 }
2905
2906 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2907 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2908 return;
2909 }
2910
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002911 // Valid result, insert into queue
2912 List<CaptureResult>::iterator queuedResult =
2913 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2914 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2915 ", burstId = %" PRId32, __FUNCTION__,
2916 queuedResult->mResultExtras.requestId,
2917 queuedResult->mResultExtras.frameNumber,
2918 queuedResult->mResultExtras.burstId);
2919
2920 mResultSignal.signal();
2921}
2922
2923
2924void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002925 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002927 Mutex::Autolock l(mOutputLock);
2928
2929 CaptureResult captureResult;
2930 captureResult.mResultExtras = resultExtras;
2931 captureResult.mMetadata = partialResult;
2932
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002933 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002934}
2935
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002936
2937void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2938 CaptureResultExtras &resultExtras,
2939 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002940 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002941 bool reprocess,
2942 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002943 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002944 if (pendingMetadata.isEmpty())
2945 return;
2946
2947 Mutex::Autolock l(mOutputLock);
2948
2949 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002950 if (reprocess) {
2951 if (frameNumber < mNextReprocessResultFrameNumber) {
2952 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002953 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002954 frameNumber, mNextReprocessResultFrameNumber);
2955 return;
2956 }
2957 mNextReprocessResultFrameNumber = frameNumber + 1;
2958 } else {
2959 if (frameNumber < mNextResultFrameNumber) {
2960 SET_ERR("Out-of-order capture result metadata submitted! "
2961 "(got frame number %d, expecting %d)",
2962 frameNumber, mNextResultFrameNumber);
2963 return;
2964 }
2965 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002966 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002967
2968 CaptureResult captureResult;
2969 captureResult.mResultExtras = resultExtras;
2970 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002971 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002972
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002973 // Append any previous partials to form a complete result
2974 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2975 captureResult.mMetadata.append(collectedPartialResult);
2976 }
2977
2978 captureResult.mMetadata.sort();
2979
2980 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002981 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2982 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002983 SET_ERR("No timestamp provided by HAL for frame %d!",
2984 frameNumber);
2985 return;
2986 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002987 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
2988 camera_metadata_entry timestamp =
2989 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2990 if (timestamp.count == 0) {
2991 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
2992 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
2993 return;
2994 }
2995 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002996
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07002997 // Fix up some result metadata to account for HAL-level distortion correction
2998 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
2999 if (res != OK) {
3000 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3001 frameNumber, strerror(res), res);
3002 return;
3003 }
3004
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003005 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3006 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3007
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003008 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003009}
3010
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003011/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003012 * Camera HAL device callback methods
3013 */
3014
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003015void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003016 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003017
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003018 status_t res;
3019
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003020 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003021 if (result->result == NULL && result->num_output_buffers == 0 &&
3022 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023 SET_ERR("No result data provided by HAL for frame %d",
3024 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003025 return;
3026 }
Zhijun He204e3292014-07-14 17:09:23 -07003027
Zhijun He204e3292014-07-14 17:09:23 -07003028 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003029 result->result != NULL &&
3030 result->partial_result != 1) {
3031 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3032 " if partial result is not supported",
3033 frameNumber, result->partial_result);
3034 return;
3035 }
3036
3037 bool isPartialResult = false;
3038 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003039 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003040
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003041 // Get shutter timestamp and resultExtras from list of in-flight requests,
3042 // where it was added by the shutter notification for this frame. If the
3043 // shutter timestamp isn't received yet, append the output buffers to the
3044 // in-flight request and they will be returned when the shutter timestamp
3045 // arrives. Update the in-flight status and remove the in-flight entry if
3046 // all result data and shutter timestamp have been received.
3047 nsecs_t shutterTimestamp = 0;
3048
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003049 {
3050 Mutex::Autolock l(mInFlightLock);
3051 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3052 if (idx == NAME_NOT_FOUND) {
3053 SET_ERR("Unknown frame number for capture result: %d",
3054 frameNumber);
3055 return;
3056 }
3057 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003058 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3059 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003060 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003061 __FUNCTION__, request.resultExtras.requestId,
3062 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003063 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003064 // Always update the partial count to the latest one if it's not 0
3065 // (buffers only). When framework aggregates adjacent partial results
3066 // into one, the latest partial count will be used.
3067 if (result->partial_result != 0)
3068 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003069
3070 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003071 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003072 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3073 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3074 " the range of [1, %d] when metadata is included in the result",
3075 frameNumber, result->partial_result, mNumPartialResults);
3076 return;
3077 }
3078 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003079 if (isPartialResult && result->num_physcam_metadata) {
3080 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3081 " physical camera result", frameNumber);
3082 return;
3083 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003084 if (isPartialResult) {
3085 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003086 }
3087
Shuzhen Wang4a472662017-02-26 23:29:04 -08003088 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003089 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003090 sendPartialCaptureResult(result->result, request.resultExtras,
3091 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003092 }
3093 }
3094
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003095 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003096 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003097
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003098 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003099 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003100 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3101 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3102 request.physicalCameraIds.size(), result->num_physcam_metadata);
3103 return;
3104 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003105 if (request.haveResultMetadata) {
3106 SET_ERR("Called multiple times with metadata for frame %d",
3107 frameNumber);
3108 return;
3109 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003110 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3111 String8 physicalId(result->physcam_ids[i]);
3112 std::set<String8>::iterator cameraIdIter =
3113 request.physicalCameraIds.find(physicalId);
3114 if (cameraIdIter != request.physicalCameraIds.end()) {
3115 request.physicalCameraIds.erase(cameraIdIter);
3116 } else {
3117 SET_ERR("Total result for frame %d has already returned for camera %s",
3118 frameNumber, physicalId.c_str());
3119 return;
3120 }
3121 }
Zhijun He204e3292014-07-14 17:09:23 -07003122 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003123 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003124 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003125 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003126 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003127 request.haveResultMetadata = true;
3128 }
3129
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003130 uint32_t numBuffersReturned = result->num_output_buffers;
3131 if (result->input_buffer != NULL) {
3132 if (hasInputBufferInRequest) {
3133 numBuffersReturned += 1;
3134 } else {
3135 ALOGW("%s: Input buffer should be NULL if there is no input"
3136 " buffer sent in the request",
3137 __FUNCTION__);
3138 }
3139 }
3140 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003141 if (request.numBuffersLeft < 0) {
3142 SET_ERR("Too many buffers returned for frame %d",
3143 frameNumber);
3144 return;
3145 }
3146
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003147 camera_metadata_ro_entry_t entry;
3148 res = find_camera_metadata_ro_entry(result->result,
3149 ANDROID_SENSOR_TIMESTAMP, &entry);
3150 if (res == OK && entry.count == 1) {
3151 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003152 }
3153
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003154 // If shutter event isn't received yet, append the output buffers to
3155 // the in-flight request. Otherwise, return the output buffers to
3156 // streams.
3157 if (shutterTimestamp == 0) {
3158 request.pendingOutputBuffers.appendArray(result->output_buffers,
3159 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003160 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003161 returnOutputBuffers(result->output_buffers,
3162 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003163 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003164
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003165 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003166 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3167 CameraMetadata physicalMetadata;
3168 physicalMetadata.append(result->physcam_metadata[i]);
3169 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3170 physicalMetadata});
3171 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003172 if (shutterTimestamp == 0) {
3173 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003174 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003175 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003176 CameraMetadata metadata;
3177 metadata = result->result;
3178 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003179 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003180 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003181 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003182 }
3183
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003184 removeInFlightRequestIfReadyLocked(idx);
3185 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003186
Zhijun Hef0d962a2014-06-30 10:24:11 -07003187 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003188 if (hasInputBufferInRequest) {
3189 Camera3Stream *stream =
3190 Camera3Stream::cast(result->input_buffer->stream);
3191 res = stream->returnInputBuffer(*(result->input_buffer));
3192 // Note: stream may be deallocated at this point, if this buffer was the
3193 // last reference to it.
3194 if (res != OK) {
3195 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3196 " its stream:%s (%d)", __FUNCTION__,
3197 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003198 }
3199 } else {
3200 ALOGW("%s: Input buffer should be NULL if there is no input"
3201 " buffer sent in the request, skipping input buffer return.",
3202 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003203 }
3204 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003205}
3206
3207void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003208 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003209 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003210 {
3211 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003212 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003213 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003214
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003215 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003216 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003217 return;
3218 }
3219
3220 switch (msg->type) {
3221 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003222 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003223 break;
3224 }
3225 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003226 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003227 break;
3228 }
3229 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003230 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003231 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003232 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003233}
3234
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003235void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003236 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003237 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003238 // Map camera HAL error codes to ICameraDeviceCallback error codes
3239 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003240 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003241 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003242 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003243 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003244 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003245 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003246 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003247 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003248 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003249 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003250 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003251 };
3252
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003253 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003254 ((msg.error_code >= 0) &&
3255 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3256 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003257 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003258
3259 int streamId = 0;
3260 if (msg.error_stream != NULL) {
3261 Camera3Stream *stream =
3262 Camera3Stream::cast(msg.error_stream);
3263 streamId = stream->getId();
3264 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003265 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3266 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003267 streamId, msg.error_code);
3268
3269 CaptureResultExtras resultExtras;
3270 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003271 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003272 // SET_ERR calls notifyError
3273 SET_ERR("Camera HAL reported serious device error");
3274 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003275 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3276 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3277 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003278 {
3279 Mutex::Autolock l(mInFlightLock);
3280 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3281 if (idx >= 0) {
3282 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3283 r.requestStatus = msg.error_code;
3284 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003285 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3286 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3287 errorCode) {
3288 r.skipResultMetadata = true;
3289 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003290 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3291 errorCode) {
3292 // In case of missing result check whether the buffers
3293 // returned. If they returned, then remove inflight
3294 // request.
3295 removeInFlightRequestIfReadyLocked(idx);
3296 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003297 } else {
3298 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003299 ALOGE("Camera %s: %s: cannot find in-flight request on "
3300 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003301 resultExtras.frameNumber);
3302 }
3303 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003304 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003305 if (listener != NULL) {
3306 listener->notifyError(errorCode, resultExtras);
3307 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003308 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003309 }
3310 break;
3311 default:
3312 // SET_ERR calls notifyError
3313 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3314 break;
3315 }
3316}
3317
3318void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003319 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003320 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003321 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003322
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003323 // Set timestamp for the request in the in-flight tracking
3324 // and get the request ID to send upstream
3325 {
3326 Mutex::Autolock l(mInFlightLock);
3327 idx = mInFlightMap.indexOfKey(msg.frame_number);
3328 if (idx >= 0) {
3329 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003330
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003331 // Verify ordering of shutter notifications
3332 {
3333 Mutex::Autolock l(mOutputLock);
3334 // TODO: need to track errors for tighter bounds on expected frame number.
3335 if (r.hasInputBuffer) {
3336 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3337 SET_ERR("Shutter notification out-of-order. Expected "
3338 "notification for frame %d, got frame %d",
3339 mNextReprocessShutterFrameNumber, msg.frame_number);
3340 return;
3341 }
3342 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3343 } else {
3344 if (msg.frame_number < mNextShutterFrameNumber) {
3345 SET_ERR("Shutter notification out-of-order. Expected "
3346 "notification for frame %d, got frame %d",
3347 mNextShutterFrameNumber, msg.frame_number);
3348 return;
3349 }
3350 mNextShutterFrameNumber = msg.frame_number + 1;
3351 }
3352 }
3353
Shuzhen Wang4a472662017-02-26 23:29:04 -08003354 r.shutterTimestamp = msg.timestamp;
3355 if (r.hasCallback) {
3356 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003357 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003358 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003359 // Call listener, if any
3360 if (listener != NULL) {
3361 listener->notifyShutter(r.resultExtras, msg.timestamp);
3362 }
3363 // send pending result and buffers
3364 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3365 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003366 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003367 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003368 returnOutputBuffers(r.pendingOutputBuffers.array(),
3369 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3370 r.pendingOutputBuffers.clear();
3371
3372 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003373 }
3374 }
3375 if (idx < 0) {
3376 SET_ERR("Shutter notification for non-existent frame number %d",
3377 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003378 }
3379}
3380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003381CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003382 ALOGV("%s", __FUNCTION__);
3383
Igor Murashkin1e479c02013-09-06 16:55:14 -07003384 CameraMetadata retVal;
3385
3386 if (mRequestThread != NULL) {
3387 retVal = mRequestThread->getLatestRequest();
3388 }
3389
Igor Murashkin1e479c02013-09-06 16:55:14 -07003390 return retVal;
3391}
3392
Jianing Weicb0652e2014-03-12 18:29:36 -07003393
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003394void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3395 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3396 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3397}
3398
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003399/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003400 * HalInterface inner class methods
3401 */
3402
Yifan Hongf79b5542017-04-11 14:44:25 -07003403Camera3Device::HalInterface::HalInterface(
3404 sp<ICameraDeviceSession> &session,
3405 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003406 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003407 mRequestMetadataQueue(queue) {
3408 // Check with hardware service manager if we can downcast these interfaces
3409 // Somewhat expensive, so cache the results at startup
3410 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3411 if (castResult_3_4.isOk()) {
3412 mHidlSession_3_4 = castResult_3_4;
3413 }
3414 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3415 if (castResult_3_3.isOk()) {
3416 mHidlSession_3_3 = castResult_3_3;
3417 }
3418}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003419
Emilian Peev31abd0a2017-05-11 18:37:46 +01003420Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003421
3422Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003423 mHidlSession(other.mHidlSession),
3424 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003425
3426bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003427 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003428}
3429
3430void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003431 mHidlSession_3_4.clear();
3432 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003433 mHidlSession.clear();
3434}
3435
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003436bool Camera3Device::HalInterface::supportBatchRequest() {
3437 return mHidlSession != nullptr;
3438}
3439
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003440status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3441 camera3_request_template_t templateId,
3442 /*out*/ camera_metadata_t **requestTemplate) {
3443 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3444 if (!valid()) return INVALID_OPERATION;
3445 status_t res = OK;
3446
Emilian Peev31abd0a2017-05-11 18:37:46 +01003447 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003448
3449 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003451 status = s;
3452 if (status == common::V1_0::Status::OK) {
3453 const camera_metadata *r =
3454 reinterpret_cast<const camera_metadata_t*>(request.data());
3455 size_t expectedSize = request.size();
3456 int ret = validate_camera_metadata_structure(r, &expectedSize);
3457 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3458 *requestTemplate = clone_camera_metadata(r);
3459 if (*requestTemplate == nullptr) {
3460 ALOGE("%s: Unable to clone camera metadata received from HAL",
3461 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003462 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003463 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003464 } else {
3465 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3466 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003467 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003468 }
3469 };
3470 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003471 RequestTemplate id;
3472 switch (templateId) {
3473 case CAMERA3_TEMPLATE_PREVIEW:
3474 id = RequestTemplate::PREVIEW;
3475 break;
3476 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3477 id = RequestTemplate::STILL_CAPTURE;
3478 break;
3479 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3480 id = RequestTemplate::VIDEO_RECORD;
3481 break;
3482 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3483 id = RequestTemplate::VIDEO_SNAPSHOT;
3484 break;
3485 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3486 id = RequestTemplate::ZERO_SHUTTER_LAG;
3487 break;
3488 case CAMERA3_TEMPLATE_MANUAL:
3489 id = RequestTemplate::MANUAL;
3490 break;
3491 default:
3492 // Unknown template ID, or this HAL is too old to support it
3493 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003494 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003495 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003496
Emilian Peev31abd0a2017-05-11 18:37:46 +01003497 if (!err.isOk()) {
3498 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3499 res = DEAD_OBJECT;
3500 } else {
3501 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003502 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003503
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003504 return res;
3505}
3506
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003507status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003508 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003509 ATRACE_NAME("CameraHal::configureStreams");
3510 if (!valid()) return INVALID_OPERATION;
3511 status_t res = OK;
3512
Emilian Peev31abd0a2017-05-11 18:37:46 +01003513 // Convert stream config to HIDL
3514 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003515 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3516 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3517 requestedConfiguration3_2.streams.resize(config->num_streams);
3518 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003520 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3521 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003522 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003523
Emilian Peev31abd0a2017-05-11 18:37:46 +01003524 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3525 cam3stream->setBufferFreedListener(this);
3526 int streamId = cam3stream->getId();
3527 StreamType streamType;
3528 switch (src->stream_type) {
3529 case CAMERA3_STREAM_OUTPUT:
3530 streamType = StreamType::OUTPUT;
3531 break;
3532 case CAMERA3_STREAM_INPUT:
3533 streamType = StreamType::INPUT;
3534 break;
3535 default:
3536 ALOGE("%s: Stream %d: Unsupported stream type %d",
3537 __FUNCTION__, streamId, config->streams[i]->stream_type);
3538 return BAD_VALUE;
3539 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003540 dst3_2.id = streamId;
3541 dst3_2.streamType = streamType;
3542 dst3_2.width = src->width;
3543 dst3_2.height = src->height;
3544 dst3_2.format = mapToPixelFormat(src->format);
3545 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3546 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3547 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3548 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003549 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003550 if (src->physical_camera_id != nullptr) {
3551 dst3_4.physicalCameraId = src->physical_camera_id;
3552 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553
3554 activeStreams.insert(streamId);
3555 // Create Buffer ID map if necessary
3556 if (mBufferIdMaps.count(streamId) == 0) {
3557 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3558 }
3559 }
3560 // remove BufferIdMap for deleted streams
3561 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3562 int streamId = it->first;
3563 bool active = activeStreams.count(streamId) > 0;
3564 if (!active) {
3565 it = mBufferIdMaps.erase(it);
3566 } else {
3567 ++it;
3568 }
3569 }
3570
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003571 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003572 res = mapToStreamConfigurationMode(
3573 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003574 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003575 if (res != OK) {
3576 return res;
3577 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003578 requestedConfiguration3_2.operationMode = operationMode;
3579 requestedConfiguration3_4.operationMode = operationMode;
3580 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003581 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3582 get_camera_metadata_size(sessionParams));
3583
Emilian Peev31abd0a2017-05-11 18:37:46 +01003584 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003585 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003586 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003587
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003588 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003589 if (mHidlSession_3_4 != nullptr) {
3590 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003591 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003592 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003593 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003594 [&status, &finalConfiguration3_4]
3595 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3596 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003597 status = s;
3598 });
3599 if (!err.isOk()) {
3600 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3601 return DEAD_OBJECT;
3602 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003603 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3604 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3605 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3606 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003607 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003608 // We do; use v3.3 for the call
3609 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003610 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003611 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003612 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003613 finalConfiguration = halConfiguration;
3614 status = s;
3615 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003616 if (!err.isOk()) {
3617 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3618 return DEAD_OBJECT;
3619 }
3620 } else {
3621 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3622 ALOGV("%s: v3.2 device found", __FUNCTION__);
3623 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003624 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003625 [&status, &finalConfiguration_3_2]
3626 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3627 finalConfiguration_3_2 = halConfiguration;
3628 status = s;
3629 });
3630 if (!err.isOk()) {
3631 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3632 return DEAD_OBJECT;
3633 }
3634 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3635 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3636 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3637 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003638 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003639 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003640 }
3641
3642 if (status != common::V1_0::Status::OK ) {
3643 return CameraProviderManager::mapToStatusT(status);
3644 }
3645
3646 // And convert output stream configuration from HIDL
3647
3648 for (size_t i = 0; i < config->num_streams; i++) {
3649 camera3_stream_t *dst = config->streams[i];
3650 int streamId = Camera3Stream::cast(dst)->getId();
3651
3652 // Start scan at i, with the assumption that the stream order matches
3653 size_t realIdx = i;
3654 bool found = false;
3655 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003656 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003657 found = true;
3658 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003659 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003660 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3661 }
3662 if (!found) {
3663 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3664 __FUNCTION__, streamId);
3665 return INVALID_OPERATION;
3666 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003667 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003668
Emilian Peev710c1422017-08-30 11:19:38 +01003669 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3670 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003671 dstStream->setDataSpaceOverride(false);
3672 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3673 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3674
Emilian Peev31abd0a2017-05-11 18:37:46 +01003675 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3676 if (dst->format != overrideFormat) {
3677 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3678 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003679 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003680 if (dst->data_space != overrideDataSpace) {
3681 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3682 streamId, dst->format);
3683 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003684 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003685 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003686 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3687
Emilian Peev31abd0a2017-05-11 18:37:46 +01003688 // Override allowed with IMPLEMENTATION_DEFINED
3689 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003690 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003691 }
3692
Emilian Peev31abd0a2017-05-11 18:37:46 +01003693 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003694 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003695 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003696 __FUNCTION__, streamId);
3697 return INVALID_OPERATION;
3698 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003699 dstStream->setUsage(
3700 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003701 } else {
3702 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003703 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003704 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3705 __FUNCTION__, streamId);
3706 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003707 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003708 dstStream->setUsage(
3709 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003710 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003711 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003712 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003713
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003714 return res;
3715}
3716
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003717void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3718 /*out*/device::V3_2::CaptureRequest* captureRequest,
3719 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003720 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003721 if (captureRequest == nullptr || handlesCreated == nullptr) {
3722 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3723 __FUNCTION__, captureRequest, handlesCreated);
3724 return;
3725 }
3726
3727 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003728
3729 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003730
3731 {
3732 std::lock_guard<std::mutex> lock(mInflightLock);
3733 if (request->input_buffer != nullptr) {
3734 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3735 buffer_handle_t buf = *(request->input_buffer->buffer);
3736 auto pair = getBufferId(buf, streamId);
3737 bool isNewBuffer = pair.first;
3738 uint64_t bufferId = pair.second;
3739 captureRequest->inputBuffer.streamId = streamId;
3740 captureRequest->inputBuffer.bufferId = bufferId;
3741 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3742 captureRequest->inputBuffer.status = BufferStatus::OK;
3743 native_handle_t *acquireFence = nullptr;
3744 if (request->input_buffer->acquire_fence != -1) {
3745 acquireFence = native_handle_create(1,0);
3746 acquireFence->data[0] = request->input_buffer->acquire_fence;
3747 handlesCreated->push_back(acquireFence);
3748 }
3749 captureRequest->inputBuffer.acquireFence = acquireFence;
3750 captureRequest->inputBuffer.releaseFence = nullptr;
3751
3752 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3753 request->input_buffer->buffer,
3754 request->input_buffer->acquire_fence);
3755 } else {
3756 captureRequest->inputBuffer.streamId = -1;
3757 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3758 }
3759
3760 captureRequest->outputBuffers.resize(request->num_output_buffers);
3761 for (size_t i = 0; i < request->num_output_buffers; i++) {
3762 const camera3_stream_buffer_t *src = request->output_buffers + i;
3763 StreamBuffer &dst = captureRequest->outputBuffers[i];
3764 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3765 buffer_handle_t buf = *(src->buffer);
3766 auto pair = getBufferId(buf, streamId);
3767 bool isNewBuffer = pair.first;
3768 dst.streamId = streamId;
3769 dst.bufferId = pair.second;
3770 dst.buffer = isNewBuffer ? buf : nullptr;
3771 dst.status = BufferStatus::OK;
3772 native_handle_t *acquireFence = nullptr;
3773 if (src->acquire_fence != -1) {
3774 acquireFence = native_handle_create(1,0);
3775 acquireFence->data[0] = src->acquire_fence;
3776 handlesCreated->push_back(acquireFence);
3777 }
3778 dst.acquireFence = acquireFence;
3779 dst.releaseFence = nullptr;
3780
3781 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3782 src->buffer, src->acquire_fence);
3783 }
3784 }
3785}
3786
3787status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3788 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3789 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3790 if (!valid()) return INVALID_OPERATION;
3791
Emilian Peevaebbe412018-01-15 13:53:24 +00003792 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3793 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3794 if (castResult_3_4.isOk()) {
3795 hidlSession_3_4 = castResult_3_4;
3796 }
3797
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003798 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003799 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003800 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003801 if (hidlSession_3_4 != nullptr) {
3802 captureRequests_3_4.resize(batchSize);
3803 } else {
3804 captureRequests.resize(batchSize);
3805 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003806 std::vector<native_handle_t*> handlesCreated;
3807
3808 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003809 if (hidlSession_3_4 != nullptr) {
3810 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3811 /*out*/&handlesCreated);
3812 } else {
3813 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3814 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003815 }
3816
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003817 std::vector<device::V3_2::BufferCache> cachesToRemove;
3818 {
3819 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3820 for (auto& pair : mFreedBuffers) {
3821 // The stream might have been removed since onBufferFreed
3822 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3823 cachesToRemove.push_back({pair.first, pair.second});
3824 }
3825 }
3826 mFreedBuffers.clear();
3827 }
3828
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003829 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3830 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003831
3832 // Write metadata to FMQ.
3833 for (size_t i = 0; i < batchSize; i++) {
3834 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003835 device::V3_2::CaptureRequest* captureRequest;
3836 if (hidlSession_3_4 != nullptr) {
3837 captureRequest = &captureRequests_3_4[i].v3_2;
3838 } else {
3839 captureRequest = &captureRequests[i];
3840 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003841
3842 if (request->settings != nullptr) {
3843 size_t settingsSize = get_camera_metadata_size(request->settings);
3844 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3845 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3846 captureRequest->settings.resize(0);
3847 captureRequest->fmqSettingsSize = settingsSize;
3848 } else {
3849 if (mRequestMetadataQueue != nullptr) {
3850 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3851 }
3852 captureRequest->settings.setToExternal(
3853 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3854 get_camera_metadata_size(request->settings));
3855 captureRequest->fmqSettingsSize = 0u;
3856 }
3857 } else {
3858 // A null request settings maps to a size-0 CameraMetadata
3859 captureRequest->settings.resize(0);
3860 captureRequest->fmqSettingsSize = 0u;
3861 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003862
3863 if (hidlSession_3_4 != nullptr) {
3864 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3865 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003866 if (request->physcam_settings != nullptr) {
3867 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3868 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3869 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3870 settingsSize)) {
3871 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3872 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3873 settingsSize;
3874 } else {
3875 if (mRequestMetadataQueue != nullptr) {
3876 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3877 }
3878 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3879 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3880 request->physcam_settings[j])),
3881 get_camera_metadata_size(request->physcam_settings[j]));
3882 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003883 }
Emilian Peev00420d22018-02-05 21:33:13 +00003884 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003885 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003886 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003887 }
3888 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3889 request->physcam_id[j];
3890 }
3891 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003892 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003893
3894 hardware::details::return_status err;
3895 if (hidlSession_3_4 != nullptr) {
3896 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003897 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3898 status = s;
3899 *numRequestProcessed = n;
3900 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003901 } else {
3902 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3903 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3904 status = s;
3905 *numRequestProcessed = n;
3906 });
3907 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003908 if (!err.isOk()) {
3909 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3910 return DEAD_OBJECT;
3911 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003912 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3913 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3914 __FUNCTION__, *numRequestProcessed, batchSize);
3915 status = common::V1_0::Status::INTERNAL_ERROR;
3916 }
3917
3918 for (auto& handle : handlesCreated) {
3919 native_handle_delete(handle);
3920 }
3921 return CameraProviderManager::mapToStatusT(status);
3922}
3923
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003924status_t Camera3Device::HalInterface::processCaptureRequest(
3925 camera3_capture_request_t *request) {
3926 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003927 if (!valid()) return INVALID_OPERATION;
3928 status_t res = OK;
3929
Emilian Peev31abd0a2017-05-11 18:37:46 +01003930 uint32_t numRequestProcessed = 0;
3931 std::vector<camera3_capture_request_t*> requests(1);
3932 requests[0] = request;
3933 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3934
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003935 return res;
3936}
3937
3938status_t Camera3Device::HalInterface::flush() {
3939 ATRACE_NAME("CameraHal::flush");
3940 if (!valid()) return INVALID_OPERATION;
3941 status_t res = OK;
3942
Emilian Peev31abd0a2017-05-11 18:37:46 +01003943 auto err = mHidlSession->flush();
3944 if (!err.isOk()) {
3945 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3946 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003947 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003948 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003949 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003950
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003951 return res;
3952}
3953
Emilian Peev31abd0a2017-05-11 18:37:46 +01003954status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003955 ATRACE_NAME("CameraHal::dump");
3956 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003957
Emilian Peev31abd0a2017-05-11 18:37:46 +01003958 // Handled by CameraProviderManager::dump
3959
3960 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003961}
3962
3963status_t Camera3Device::HalInterface::close() {
3964 ATRACE_NAME("CameraHal::close()");
3965 if (!valid()) return INVALID_OPERATION;
3966 status_t res = OK;
3967
Emilian Peev31abd0a2017-05-11 18:37:46 +01003968 auto err = mHidlSession->close();
3969 // Interface will be dead shortly anyway, so don't log errors
3970 if (!err.isOk()) {
3971 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003973
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974 return res;
3975}
3976
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003977void Camera3Device::HalInterface::getInflightBufferKeys(
3978 std::vector<std::pair<int32_t, int32_t>>* out) {
3979 std::lock_guard<std::mutex> lock(mInflightLock);
3980 out->clear();
3981 out->reserve(mInflightBufferMap.size());
3982 for (auto& pair : mInflightBufferMap) {
3983 uint64_t key = pair.first;
3984 int32_t streamId = key & 0xFFFFFFFF;
3985 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3986 out->push_back(std::make_pair(frameNumber, streamId));
3987 }
3988 return;
3989}
3990
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003992 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003993 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003994 auto pair = std::make_pair(buffer, acquireFence);
3995 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996 return OK;
3997}
3998
3999status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004000 int32_t frameNumber, int32_t streamId,
4001 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 std::lock_guard<std::mutex> lock(mInflightLock);
4003
4004 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4005 auto it = mInflightBufferMap.find(key);
4006 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004007 auto pair = it->second;
4008 *buffer = pair.first;
4009 int acquireFence = pair.second;
4010 if (acquireFence > 0) {
4011 ::close(acquireFence);
4012 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004013 mInflightBufferMap.erase(it);
4014 return OK;
4015}
4016
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004017std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4018 const buffer_handle_t& buf, int streamId) {
4019 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4020
4021 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4022 auto it = bIdMap.find(buf);
4023 if (it == bIdMap.end()) {
4024 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004025 ALOGV("stream %d now have %zu buffer caches, buf %p",
4026 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004027 return std::make_pair(true, mNextBufferId - 1);
4028 } else {
4029 return std::make_pair(false, it->second);
4030 }
4031}
4032
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004033void Camera3Device::HalInterface::onBufferFreed(
4034 int streamId, const native_handle_t* handle) {
4035 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4036 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4037 auto mapIt = mBufferIdMaps.find(streamId);
4038 if (mapIt == mBufferIdMaps.end()) {
4039 // streamId might be from a deleted stream here
4040 ALOGI("%s: stream %d has been removed",
4041 __FUNCTION__, streamId);
4042 return;
4043 }
4044 BufferIdMap& bIdMap = mapIt->second;
4045 auto it = bIdMap.find(handle);
4046 if (it == bIdMap.end()) {
4047 ALOGW("%s: cannot find buffer %p in stream %d",
4048 __FUNCTION__, handle, streamId);
4049 return;
4050 } else {
4051 bufferId = it->second;
4052 bIdMap.erase(it);
4053 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4054 __FUNCTION__, streamId, bIdMap.size(), handle);
4055 }
4056 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4057}
4058
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004059/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004060 * RequestThread inner class methods
4061 */
4062
4063Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004064 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004065 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004066 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004067 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004068 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004069 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004070 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004071 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004072 mReconfigured(false),
4073 mDoPause(false),
4074 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004075 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004076 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004077 mCurrentAfTriggerId(0),
4078 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004079 mRepeatingLastFrameNumber(
4080 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004081 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004082 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004083 mRequestLatency(kRequestLatencyBinSize),
4084 mSessionParamKeys(sessionParamKeys),
4085 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004086 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004087}
4088
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004089Camera3Device::RequestThread::~RequestThread() {}
4090
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004091void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004092 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004093 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004094 Mutex::Autolock l(mRequestLock);
4095 mListener = listener;
4096}
4097
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004098void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4099 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004100 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004101 Mutex::Autolock l(mRequestLock);
4102 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004103 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004104 // Prepare video stream for high speed recording.
4105 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004106 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004107}
4108
Jianing Wei90e59c92014-03-12 18:29:36 -07004109status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004110 List<sp<CaptureRequest> > &requests,
4111 /*out*/
4112 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004113 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004114 Mutex::Autolock l(mRequestLock);
4115 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4116 ++it) {
4117 mRequestQueue.push_back(*it);
4118 }
4119
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004120 if (lastFrameNumber != NULL) {
4121 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4122 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4123 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4124 *lastFrameNumber);
4125 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004126
Jianing Wei90e59c92014-03-12 18:29:36 -07004127 unpauseForNewRequests();
4128
4129 return OK;
4130}
4131
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004132
4133status_t Camera3Device::RequestThread::queueTrigger(
4134 RequestTrigger trigger[],
4135 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004136 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004137 Mutex::Autolock l(mTriggerMutex);
4138 status_t ret;
4139
4140 for (size_t i = 0; i < count; ++i) {
4141 ret = queueTriggerLocked(trigger[i]);
4142
4143 if (ret != OK) {
4144 return ret;
4145 }
4146 }
4147
4148 return OK;
4149}
4150
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004151const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4152 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004153 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004154 if (d != nullptr) return d->mId;
4155 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004156}
4157
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004158status_t Camera3Device::RequestThread::queueTriggerLocked(
4159 RequestTrigger trigger) {
4160
4161 uint32_t tag = trigger.metadataTag;
4162 ssize_t index = mTriggerMap.indexOfKey(tag);
4163
4164 switch (trigger.getTagType()) {
4165 case TYPE_BYTE:
4166 // fall-through
4167 case TYPE_INT32:
4168 break;
4169 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004170 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4171 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004172 return INVALID_OPERATION;
4173 }
4174
4175 /**
4176 * Collect only the latest trigger, since we only have 1 field
4177 * in the request settings per trigger tag, and can't send more than 1
4178 * trigger per request.
4179 */
4180 if (index != NAME_NOT_FOUND) {
4181 mTriggerMap.editValueAt(index) = trigger;
4182 } else {
4183 mTriggerMap.add(tag, trigger);
4184 }
4185
4186 return OK;
4187}
4188
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004189status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004190 const RequestList &requests,
4191 /*out*/
4192 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004193 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004194 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004195 if (lastFrameNumber != NULL) {
4196 *lastFrameNumber = mRepeatingLastFrameNumber;
4197 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004198 mRepeatingRequests.clear();
4199 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4200 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004201
4202 unpauseForNewRequests();
4203
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004204 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 return OK;
4206}
4207
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004208bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004209 if (mRepeatingRequests.empty()) {
4210 return false;
4211 }
4212 int32_t requestId = requestIn->mResultExtras.requestId;
4213 const RequestList &repeatRequests = mRepeatingRequests;
4214 // All repeating requests are guaranteed to have same id so only check first quest
4215 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4216 return (firstRequest->mResultExtras.requestId == requestId);
4217}
4218
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004219status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004220 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004221 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004222 return clearRepeatingRequestsLocked(lastFrameNumber);
4223
4224}
4225
4226status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004227 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004228 if (lastFrameNumber != NULL) {
4229 *lastFrameNumber = mRepeatingLastFrameNumber;
4230 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004231 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004232 return OK;
4233}
4234
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004235status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004236 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004237 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004238 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004239 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004240
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004241 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004242
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004243 // Send errors for all requests pending in the request queue, including
4244 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004245 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004246 if (listener != NULL) {
4247 for (RequestList::iterator it = mRequestQueue.begin();
4248 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004249 // Abort the input buffers for reprocess requests.
4250 if ((*it)->mInputStream != NULL) {
4251 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004252 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4253 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004254 if (res != OK) {
4255 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4256 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4257 } else {
4258 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4259 if (res != OK) {
4260 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4261 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4262 }
4263 }
4264 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004265 // Set the frame number this request would have had, if it
4266 // had been submitted; this frame number will not be reused.
4267 // The requestId and burstId fields were set when the request was
4268 // submitted originally (in convertMetadataListToRequestListLocked)
4269 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004270 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004271 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004272 }
4273 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004274 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004275
4276 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004277 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004278 if (lastFrameNumber != NULL) {
4279 *lastFrameNumber = mRepeatingLastFrameNumber;
4280 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004281 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004282 return OK;
4283}
4284
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004285status_t Camera3Device::RequestThread::flush() {
4286 ATRACE_CALL();
4287 Mutex::Autolock l(mFlushLock);
4288
Emilian Peev08dd2452017-04-06 16:55:14 +01004289 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004290}
4291
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004292void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004293 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294 Mutex::Autolock l(mPauseLock);
4295 mDoPause = paused;
4296 mDoPauseSignal.signal();
4297}
4298
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004299status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4300 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004301 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004302 Mutex::Autolock l(mLatestRequestMutex);
4303 status_t res;
4304 while (mLatestRequestId != requestId) {
4305 nsecs_t startTime = systemTime();
4306
4307 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4308 if (res != OK) return res;
4309
4310 timeout -= (systemTime() - startTime);
4311 }
4312
4313 return OK;
4314}
4315
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004316void Camera3Device::RequestThread::requestExit() {
4317 // Call parent to set up shutdown
4318 Thread::requestExit();
4319 // The exit from any possible waits
4320 mDoPauseSignal.signal();
4321 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004322
4323 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4324 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004325}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004326
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004327void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004328 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004329 bool surfaceAbandoned = false;
4330 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004331 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004332 {
4333 Mutex::Autolock l(mRequestLock);
4334 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4335 // repeating requests.
4336 for (const auto& request : mRepeatingRequests) {
4337 for (const auto& s : request->mOutputStreams) {
4338 if (s->isAbandoned()) {
4339 surfaceAbandoned = true;
4340 clearRepeatingRequestsLocked(&lastFrameNumber);
4341 break;
4342 }
4343 }
4344 if (surfaceAbandoned) {
4345 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004346 }
4347 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004348 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004349 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004350
4351 if (listener != NULL && surfaceAbandoned) {
4352 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004353 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004354}
4355
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004356bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004357 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004358 status_t res;
4359 size_t batchSize = mNextRequests.size();
4360 std::vector<camera3_capture_request_t*> requests(batchSize);
4361 uint32_t numRequestProcessed = 0;
4362 for (size_t i = 0; i < batchSize; i++) {
4363 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004364 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004365 }
4366
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004367 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4368
4369 bool triggerRemoveFailed = false;
4370 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4371 for (size_t i = 0; i < numRequestProcessed; i++) {
4372 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4373 nextRequest.submitted = true;
4374
4375
4376 // Update the latest request sent to HAL
4377 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4378 Mutex::Autolock al(mLatestRequestMutex);
4379
4380 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4381 mLatestRequest.acquire(cloned);
4382
4383 sp<Camera3Device> parent = mParent.promote();
4384 if (parent != NULL) {
4385 parent->monitorMetadata(TagMonitor::REQUEST,
4386 nextRequest.halRequest.frame_number,
4387 0, mLatestRequest);
4388 }
4389 }
4390
4391 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004392 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4393 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004394 }
4395
Emilian Peevaebbe412018-01-15 13:53:24 +00004396 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4397
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004398 if (!triggerRemoveFailed) {
4399 // Remove any previously queued triggers (after unlock)
4400 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4401 if (removeTriggerRes != OK) {
4402 triggerRemoveFailed = true;
4403 triggerFailedRequest = nextRequest;
4404 }
4405 }
4406 }
4407
4408 if (triggerRemoveFailed) {
4409 SET_ERR("RequestThread: Unable to remove triggers "
4410 "(capture request %d, HAL device: %s (%d)",
4411 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4412 cleanUpFailedRequests(/*sendRequestError*/ false);
4413 return false;
4414 }
4415
4416 if (res != OK) {
4417 // Should only get a failure here for malformed requests or device-level
4418 // errors, so consider all errors fatal. Bad metadata failures should
4419 // come through notify.
4420 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4421 mNextRequests[numRequestProcessed].halRequest.frame_number,
4422 strerror(-res), res);
4423 cleanUpFailedRequests(/*sendRequestError*/ false);
4424 return false;
4425 }
4426 return true;
4427}
4428
4429bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4430 status_t res;
4431
4432 for (auto& nextRequest : mNextRequests) {
4433 // Submit request and block until ready for next one
4434 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4435 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4436
4437 if (res != OK) {
4438 // Should only get a failure here for malformed requests or device-level
4439 // errors, so consider all errors fatal. Bad metadata failures should
4440 // come through notify.
4441 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4442 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4443 res);
4444 cleanUpFailedRequests(/*sendRequestError*/ false);
4445 return false;
4446 }
4447
4448 // Mark that the request has be submitted successfully.
4449 nextRequest.submitted = true;
4450
4451 // Update the latest request sent to HAL
4452 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4453 Mutex::Autolock al(mLatestRequestMutex);
4454
4455 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4456 mLatestRequest.acquire(cloned);
4457
4458 sp<Camera3Device> parent = mParent.promote();
4459 if (parent != NULL) {
4460 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4461 0, mLatestRequest);
4462 }
4463 }
4464
4465 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004466 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4467 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004468 }
4469
Emilian Peevaebbe412018-01-15 13:53:24 +00004470 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4471
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004472 // Remove any previously queued triggers (after unlock)
4473 res = removeTriggers(mPrevRequest);
4474 if (res != OK) {
4475 SET_ERR("RequestThread: Unable to remove triggers "
4476 "(capture request %d, HAL device: %s (%d)",
4477 nextRequest.halRequest.frame_number, strerror(-res), res);
4478 cleanUpFailedRequests(/*sendRequestError*/ false);
4479 return false;
4480 }
4481 }
4482 return true;
4483}
4484
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004485nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4486 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4487 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4488 find_camera_metadata_ro_entry(request,
4489 ANDROID_CONTROL_AE_MODE,
4490 &e);
4491 if (e.count == 0) return maxExpectedDuration;
4492
4493 switch (e.data.u8[0]) {
4494 case ANDROID_CONTROL_AE_MODE_OFF:
4495 find_camera_metadata_ro_entry(request,
4496 ANDROID_SENSOR_EXPOSURE_TIME,
4497 &e);
4498 if (e.count > 0) {
4499 maxExpectedDuration = e.data.i64[0];
4500 }
4501 find_camera_metadata_ro_entry(request,
4502 ANDROID_SENSOR_FRAME_DURATION,
4503 &e);
4504 if (e.count > 0) {
4505 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4506 }
4507 break;
4508 default:
4509 find_camera_metadata_ro_entry(request,
4510 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4511 &e);
4512 if (e.count > 1) {
4513 maxExpectedDuration = 1e9 / e.data.u8[0];
4514 }
4515 break;
4516 }
4517
4518 return maxExpectedDuration;
4519}
4520
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004521bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4522 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4523 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4524 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4525 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4526 return true;
4527 }
4528
4529 return false;
4530}
4531
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004532bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4533 ATRACE_CALL();
4534 bool updatesDetected = false;
4535
4536 for (auto tag : mSessionParamKeys) {
4537 camera_metadata_ro_entry entry = settings.find(tag);
4538 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4539
4540 if (entry.count > 0) {
4541 bool isDifferent = false;
4542 if (lastEntry.count > 0) {
4543 // Have a last value, compare to see if changed
4544 if (lastEntry.type == entry.type &&
4545 lastEntry.count == entry.count) {
4546 // Same type and count, compare values
4547 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4548 size_t entryBytes = bytesPerValue * lastEntry.count;
4549 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4550 if (cmp != 0) {
4551 isDifferent = true;
4552 }
4553 } else {
4554 // Count or type has changed
4555 isDifferent = true;
4556 }
4557 } else {
4558 // No last entry, so always consider to be different
4559 isDifferent = true;
4560 }
4561
4562 if (isDifferent) {
4563 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004564 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4565 updatesDetected = true;
4566 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004567 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004568 }
4569 } else if (lastEntry.count > 0) {
4570 // Value has been removed
4571 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4572 mLatestSessionParams.erase(tag);
4573 updatesDetected = true;
4574 }
4575 }
4576
4577 return updatesDetected;
4578}
4579
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004580bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004581 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004582 status_t res;
4583
4584 // Handle paused state.
4585 if (waitIfPaused()) {
4586 return true;
4587 }
4588
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004589 // Wait for the next batch of requests.
4590 waitForNextRequestBatch();
4591 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004592 return true;
4593 }
4594
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004595 // Get the latest request ID, if any
4596 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004597 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004598 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004599 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004600 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004601 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004602 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4603 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004604 }
4605
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004606 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4607 // or a single request from streaming or burst. In either case the first element
4608 // should contain the latest camera settings that we need to check for any session
4609 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004610 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004611 res = OK;
4612
4613 //Input stream buffers are already acquired at this point so an input stream
4614 //will not be able to move to idle state unless we force it.
4615 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4616 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4617 if (res != OK) {
4618 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4619 cleanUpFailedRequests(/*sendRequestError*/ false);
4620 return false;
4621 }
4622 }
4623
4624 if (res == OK) {
4625 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4626 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004627 sp<Camera3Device> parent = mParent.promote();
4628 if (parent != nullptr) {
4629 parent->pauseStateNotify(true);
4630 }
4631
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004632 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4633
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004634 if (parent != nullptr) {
4635 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4636 }
4637
4638 statusTracker->markComponentActive(mStatusId);
4639 setPaused(false);
4640 }
4641
4642 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4643 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4644 if (res != OK) {
4645 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4646 cleanUpFailedRequests(/*sendRequestError*/ false);
4647 return false;
4648 }
4649 }
4650 }
4651 }
4652
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004653 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004654 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004655 if (res == TIMED_OUT) {
4656 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004657 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004658 // Check if any stream is abandoned.
4659 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004660 return true;
4661 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004662 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004663 return false;
4664 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004665
Zhijun Hecc27e112013-10-03 16:12:43 -07004666 // Inform waitUntilRequestProcessed thread of a new request ID
4667 {
4668 Mutex::Autolock al(mLatestRequestMutex);
4669
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004670 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004671 mLatestRequestSignal.signal();
4672 }
4673
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004674 // Submit a batch of requests to HAL.
4675 // Use flush lock only when submitting multilple requests in a batch.
4676 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4677 // which may take a long time to finish so synchronizing flush() and
4678 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4679 // For now, only synchronize for high speed recording and we should figure something out for
4680 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004681 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004682
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004683 if (useFlushLock) {
4684 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004685 }
4686
Zhijun Hef0645c12016-08-02 00:58:11 -07004687 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004688 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004689
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004690 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004691 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004692 if (mInterface->supportBatchRequest()) {
4693 submitRequestSuccess = sendRequestsBatch();
4694 } else {
4695 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004696 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004697 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4698 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004699
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004700 if (useFlushLock) {
4701 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004702 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004703
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004704 // Unset as current request
4705 {
4706 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004707 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004708 }
4709
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004710 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004711}
4712
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004713status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004714 ATRACE_CALL();
4715
Shuzhen Wang4a472662017-02-26 23:29:04 -08004716 for (size_t i = 0; i < mNextRequests.size(); i++) {
4717 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004718 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4719 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4720 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4721
4722 // Prepare a request to HAL
4723 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4724
4725 // Insert any queued triggers (before metadata is locked)
4726 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004727 if (res < 0) {
4728 SET_ERR("RequestThread: Unable to insert triggers "
4729 "(capture request %d, HAL device: %s (%d)",
4730 halRequest->frame_number, strerror(-res), res);
4731 return INVALID_OPERATION;
4732 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004733
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 int triggerCount = res;
4735 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4736 mPrevTriggers = triggerCount;
4737
4738 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004739 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4740 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004741 /**
4742 * HAL workaround:
4743 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4744 */
4745 res = addDummyTriggerIds(captureRequest);
4746 if (res != OK) {
4747 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4748 "(capture request %d, HAL device: %s (%d)",
4749 halRequest->frame_number, strerror(-res), res);
4750 return INVALID_OPERATION;
4751 }
4752
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004753 {
4754 // Correct metadata regions for distortion correction if enabled
4755 sp<Camera3Device> parent = mParent.promote();
4756 if (parent != nullptr) {
4757 res = parent->mDistortionMapper.correctCaptureRequest(
4758 &(captureRequest->mSettingsList.begin()->metadata));
4759 if (res != OK) {
4760 SET_ERR("RequestThread: Unable to correct capture requests "
4761 "for lens distortion for request %d: %s (%d)",
4762 halRequest->frame_number, strerror(-res), res);
4763 return INVALID_OPERATION;
4764 }
4765 }
4766 }
4767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004768 /**
4769 * The request should be presorted so accesses in HAL
4770 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4771 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004772 captureRequest->mSettingsList.begin()->metadata.sort();
4773 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004774 mPrevRequest = captureRequest;
4775 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4776
4777 IF_ALOGV() {
4778 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4779 find_camera_metadata_ro_entry(
4780 halRequest->settings,
4781 ANDROID_CONTROL_AF_TRIGGER,
4782 &e
4783 );
4784 if (e.count > 0) {
4785 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4786 __FUNCTION__,
4787 halRequest->frame_number,
4788 e.data.u8[0]);
4789 }
4790 }
4791 } else {
4792 // leave request.settings NULL to indicate 'reuse latest given'
4793 ALOGVV("%s: Request settings are REUSED",
4794 __FUNCTION__);
4795 }
4796
Emilian Peevaebbe412018-01-15 13:53:24 +00004797 if (captureRequest->mSettingsList.size() > 1) {
4798 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4799 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004800 if (newRequest) {
4801 halRequest->physcam_settings =
4802 new const camera_metadata* [halRequest->num_physcam_settings];
4803 } else {
4804 halRequest->physcam_settings = nullptr;
4805 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004806 auto it = ++captureRequest->mSettingsList.begin();
4807 size_t i = 0;
4808 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4809 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004810 if (newRequest) {
4811 it->metadata.sort();
4812 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4813 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004814 }
4815 }
4816
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004817 uint32_t totalNumBuffers = 0;
4818
4819 // Fill in buffers
4820 if (captureRequest->mInputStream != NULL) {
4821 halRequest->input_buffer = &captureRequest->mInputBuffer;
4822 totalNumBuffers += 1;
4823 } else {
4824 halRequest->input_buffer = NULL;
4825 }
4826
4827 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4828 captureRequest->mOutputStreams.size());
4829 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004830 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004831 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4832 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004833
4834 // Prepare video buffers for high speed recording on the first video request.
4835 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4836 // Only try to prepare video stream on the first video request.
4837 mPrepareVideoStream = false;
4838
4839 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4840 while (res == NOT_ENOUGH_DATA) {
4841 res = outputStream->prepareNextBuffer();
4842 }
4843 if (res != OK) {
4844 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4845 __FUNCTION__, strerror(-res), res);
4846 outputStream->cancelPrepare();
4847 }
4848 }
4849
Shuzhen Wang4a472662017-02-26 23:29:04 -08004850 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4851 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004852 if (res != OK) {
4853 // Can't get output buffer from gralloc queue - this could be due to
4854 // abandoned queue or other consumer misbehavior, so not a fatal
4855 // error
4856 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4857 " %s (%d)", strerror(-res), res);
4858
4859 return TIMED_OUT;
4860 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004861
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004862 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4863
4864 if (!physicalCameraId.isEmpty()) {
4865 // Physical stream isn't supported for input request.
4866 if (halRequest->input_buffer) {
4867 CLOGE("Physical stream is not supported for input request");
4868 return INVALID_OPERATION;
4869 }
4870 requestedPhysicalCameras.insert(physicalCameraId);
4871 }
4872 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004873 }
4874 totalNumBuffers += halRequest->num_output_buffers;
4875
4876 // Log request in the in-flight queue
4877 sp<Camera3Device> parent = mParent.promote();
4878 if (parent == NULL) {
4879 // Should not happen, and nowhere to send errors to, so just log it
4880 CLOGE("RequestThread: Parent is gone");
4881 return INVALID_OPERATION;
4882 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004883
4884 // If this request list is for constrained high speed recording (not
4885 // preview), and the current request is not the last one in the batch,
4886 // do not send callback to the app.
4887 bool hasCallback = true;
4888 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4889 hasCallback = false;
4890 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004891 res = parent->registerInFlight(halRequest->frame_number,
4892 totalNumBuffers, captureRequest->mResultExtras,
4893 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004894 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004895 calculateMaxExpectedDuration(halRequest->settings),
4896 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004897 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4898 ", burstId = %" PRId32 ".",
4899 __FUNCTION__,
4900 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4901 captureRequest->mResultExtras.burstId);
4902 if (res != OK) {
4903 SET_ERR("RequestThread: Unable to register new in-flight request:"
4904 " %s (%d)", strerror(-res), res);
4905 return INVALID_OPERATION;
4906 }
4907 }
4908
4909 return OK;
4910}
4911
Igor Murashkin1e479c02013-09-06 16:55:14 -07004912CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004913 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004914 Mutex::Autolock al(mLatestRequestMutex);
4915
4916 ALOGV("RequestThread::%s", __FUNCTION__);
4917
4918 return mLatestRequest;
4919}
4920
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004921bool Camera3Device::RequestThread::isStreamPending(
4922 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004923 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004924 Mutex::Autolock l(mRequestLock);
4925
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004926 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004927 if (!nextRequest.submitted) {
4928 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4929 if (stream == s) return true;
4930 }
4931 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004932 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004933 }
4934
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004935 for (const auto& request : mRequestQueue) {
4936 for (const auto& s : request->mOutputStreams) {
4937 if (stream == s) return true;
4938 }
4939 if (stream == request->mInputStream) return true;
4940 }
4941
4942 for (const auto& request : mRepeatingRequests) {
4943 for (const auto& s : request->mOutputStreams) {
4944 if (stream == s) return true;
4945 }
4946 if (stream == request->mInputStream) return true;
4947 }
4948
4949 return false;
4950}
Jianing Weicb0652e2014-03-12 18:29:36 -07004951
Emilian Peev40ead602017-09-26 15:46:36 +01004952bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4953 ATRACE_CALL();
4954 Mutex::Autolock l(mRequestLock);
4955
4956 for (const auto& nextRequest : mNextRequests) {
4957 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4958 if (s.first == streamId) {
4959 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4960 if (it != s.second.end()) {
4961 return true;
4962 }
4963 }
4964 }
4965 }
4966
4967 for (const auto& request : mRequestQueue) {
4968 for (const auto& s : request->mOutputSurfaces) {
4969 if (s.first == streamId) {
4970 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4971 if (it != s.second.end()) {
4972 return true;
4973 }
4974 }
4975 }
4976 }
4977
4978 for (const auto& request : mRepeatingRequests) {
4979 for (const auto& s : request->mOutputSurfaces) {
4980 if (s.first == streamId) {
4981 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4982 if (it != s.second.end()) {
4983 return true;
4984 }
4985 }
4986 }
4987 }
4988
4989 return false;
4990}
4991
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004992nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004993 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004994 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004995 return mExpectedInflightDuration > kMinInflightDuration ?
4996 mExpectedInflightDuration : kMinInflightDuration;
4997}
4998
Emilian Peevaebbe412018-01-15 13:53:24 +00004999void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5000 camera3_capture_request_t *halRequest) {
5001 if ((request == nullptr) || (halRequest == nullptr)) {
5002 ALOGE("%s: Invalid request!", __FUNCTION__);
5003 return;
5004 }
5005
5006 if (halRequest->num_physcam_settings > 0) {
5007 if (halRequest->physcam_id != nullptr) {
5008 delete [] halRequest->physcam_id;
5009 halRequest->physcam_id = nullptr;
5010 }
5011 if (halRequest->physcam_settings != nullptr) {
5012 auto it = ++(request->mSettingsList.begin());
5013 size_t i = 0;
5014 for (; it != request->mSettingsList.end(); it++, i++) {
5015 it->metadata.unlock(halRequest->physcam_settings[i]);
5016 }
5017 delete [] halRequest->physcam_settings;
5018 halRequest->physcam_settings = nullptr;
5019 }
5020 }
5021}
5022
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005023void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5024 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005025 return;
5026 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005027
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005028 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005029 // Skip the ones that have been submitted successfully.
5030 if (nextRequest.submitted) {
5031 continue;
5032 }
5033
5034 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5035 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5036 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5037
5038 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005039 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005040 }
5041
Emilian Peevaebbe412018-01-15 13:53:24 +00005042 cleanupPhysicalSettings(captureRequest, halRequest);
5043
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005044 if (captureRequest->mInputStream != NULL) {
5045 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5046 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5047 }
5048
5049 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005050 //Buffers that failed processing could still have
5051 //valid acquire fence.
5052 int acquireFence = (*outputBuffers)[i].acquire_fence;
5053 if (0 <= acquireFence) {
5054 close(acquireFence);
5055 outputBuffers->editItemAt(i).acquire_fence = -1;
5056 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005057 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5058 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5059 }
5060
5061 if (sendRequestError) {
5062 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005063 sp<NotificationListener> listener = mListener.promote();
5064 if (listener != NULL) {
5065 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005066 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005067 captureRequest->mResultExtras);
5068 }
5069 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005070
5071 // Remove yet-to-be submitted inflight request from inflightMap
5072 {
5073 sp<Camera3Device> parent = mParent.promote();
5074 if (parent != NULL) {
5075 Mutex::Autolock l(parent->mInFlightLock);
5076 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5077 if (idx >= 0) {
5078 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5079 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5080 parent->removeInFlightMapEntryLocked(idx);
5081 }
5082 }
5083 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005084 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005085
5086 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005087 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005088}
5089
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005090void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005091 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005092 // Optimized a bit for the simple steady-state case (single repeating
5093 // request), to avoid putting that request in the queue temporarily.
5094 Mutex::Autolock l(mRequestLock);
5095
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005096 assert(mNextRequests.empty());
5097
5098 NextRequest nextRequest;
5099 nextRequest.captureRequest = waitForNextRequestLocked();
5100 if (nextRequest.captureRequest == nullptr) {
5101 return;
5102 }
5103
5104 nextRequest.halRequest = camera3_capture_request_t();
5105 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005106 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005107
5108 // Wait for additional requests
5109 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5110
5111 for (size_t i = 1; i < batchSize; i++) {
5112 NextRequest additionalRequest;
5113 additionalRequest.captureRequest = waitForNextRequestLocked();
5114 if (additionalRequest.captureRequest == nullptr) {
5115 break;
5116 }
5117
5118 additionalRequest.halRequest = camera3_capture_request_t();
5119 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005120 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121 }
5122
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005123 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005124 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005125 mNextRequests.size(), batchSize);
5126 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005127 }
5128
5129 return;
5130}
5131
5132sp<Camera3Device::CaptureRequest>
5133 Camera3Device::RequestThread::waitForNextRequestLocked() {
5134 status_t res;
5135 sp<CaptureRequest> nextRequest;
5136
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005137 while (mRequestQueue.empty()) {
5138 if (!mRepeatingRequests.empty()) {
5139 // Always atomically enqueue all requests in a repeating request
5140 // list. Guarantees a complete in-sequence set of captures to
5141 // application.
5142 const RequestList &requests = mRepeatingRequests;
5143 RequestList::const_iterator firstRequest =
5144 requests.begin();
5145 nextRequest = *firstRequest;
5146 mRequestQueue.insert(mRequestQueue.end(),
5147 ++firstRequest,
5148 requests.end());
5149 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005150
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005151 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005152
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005153 break;
5154 }
5155
5156 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5157
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005158 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5159 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005160 Mutex::Autolock pl(mPauseLock);
5161 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005162 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005163 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005164 // Let the tracker know
5165 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5166 if (statusTracker != 0) {
5167 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5168 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005169 }
5170 // Stop waiting for now and let thread management happen
5171 return NULL;
5172 }
5173 }
5174
5175 if (nextRequest == NULL) {
5176 // Don't have a repeating request already in hand, so queue
5177 // must have an entry now.
5178 RequestList::iterator firstRequest =
5179 mRequestQueue.begin();
5180 nextRequest = *firstRequest;
5181 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005182 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5183 sp<NotificationListener> listener = mListener.promote();
5184 if (listener != NULL) {
5185 listener->notifyRequestQueueEmpty();
5186 }
5187 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005188 }
5189
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005190 // In case we've been unpaused by setPaused clearing mDoPause, need to
5191 // update internal pause state (capture/setRepeatingRequest unpause
5192 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005193 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005194 if (mPaused) {
5195 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5196 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5197 if (statusTracker != 0) {
5198 statusTracker->markComponentActive(mStatusId);
5199 }
5200 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005201 mPaused = false;
5202
5203 // Check if we've reconfigured since last time, and reset the preview
5204 // request if so. Can't use 'NULL request == repeat' across configure calls.
5205 if (mReconfigured) {
5206 mPrevRequest.clear();
5207 mReconfigured = false;
5208 }
5209
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005210 if (nextRequest != NULL) {
5211 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005212 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5213 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005214
5215 // Since RequestThread::clear() removes buffers from the input stream,
5216 // get the right buffer here before unlocking mRequestLock
5217 if (nextRequest->mInputStream != NULL) {
5218 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5219 if (res != OK) {
5220 // Can't get input buffer from gralloc queue - this could be due to
5221 // disconnected queue or other producer misbehavior, so not a fatal
5222 // error
5223 ALOGE("%s: Can't get input buffer, skipping request:"
5224 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005225
5226 sp<NotificationListener> listener = mListener.promote();
5227 if (listener != NULL) {
5228 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005229 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005230 nextRequest->mResultExtras);
5231 }
5232 return NULL;
5233 }
5234 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005235 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005236
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005237 return nextRequest;
5238}
5239
5240bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005241 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005242 status_t res;
5243 Mutex::Autolock l(mPauseLock);
5244 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005245 if (mPaused == false) {
5246 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005247 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5248 // Let the tracker know
5249 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5250 if (statusTracker != 0) {
5251 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5252 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005253 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005255 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005256 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005257 return true;
5258 }
5259 }
5260 // We don't set mPaused to false here, because waitForNextRequest needs
5261 // to further manage the paused state in case of starvation.
5262 return false;
5263}
5264
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005265void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005266 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005267 // With work to do, mark thread as unpaused.
5268 // If paused by request (setPaused), don't resume, to avoid
5269 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005270 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005271 Mutex::Autolock p(mPauseLock);
5272 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005273 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5274 if (mPaused) {
5275 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5276 if (statusTracker != 0) {
5277 statusTracker->markComponentActive(mStatusId);
5278 }
5279 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005280 mPaused = false;
5281 }
5282}
5283
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005284void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5285 sp<Camera3Device> parent = mParent.promote();
5286 if (parent != NULL) {
5287 va_list args;
5288 va_start(args, fmt);
5289
5290 parent->setErrorStateV(fmt, args);
5291
5292 va_end(args);
5293 }
5294}
5295
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005296status_t Camera3Device::RequestThread::insertTriggers(
5297 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005298 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005299 Mutex::Autolock al(mTriggerMutex);
5300
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005301 sp<Camera3Device> parent = mParent.promote();
5302 if (parent == NULL) {
5303 CLOGE("RequestThread: Parent is gone");
5304 return DEAD_OBJECT;
5305 }
5306
Emilian Peevaebbe412018-01-15 13:53:24 +00005307 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005308 size_t count = mTriggerMap.size();
5309
5310 for (size_t i = 0; i < count; ++i) {
5311 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005312 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005313
5314 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5315 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5316 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005317 if (isAeTrigger) {
5318 request->mResultExtras.precaptureTriggerId = triggerId;
5319 mCurrentPreCaptureTriggerId = triggerId;
5320 } else {
5321 request->mResultExtras.afTriggerId = triggerId;
5322 mCurrentAfTriggerId = triggerId;
5323 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005324 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005325 }
5326
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005327 camera_metadata_entry entry = metadata.find(tag);
5328
5329 if (entry.count > 0) {
5330 /**
5331 * Already has an entry for this trigger in the request.
5332 * Rewrite it with our requested trigger value.
5333 */
5334 RequestTrigger oldTrigger = trigger;
5335
5336 oldTrigger.entryValue = entry.data.u8[0];
5337
5338 mTriggerReplacedMap.add(tag, oldTrigger);
5339 } else {
5340 /**
5341 * More typical, no trigger entry, so we just add it
5342 */
5343 mTriggerRemovedMap.add(tag, trigger);
5344 }
5345
5346 status_t res;
5347
5348 switch (trigger.getTagType()) {
5349 case TYPE_BYTE: {
5350 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5351 res = metadata.update(tag,
5352 &entryValue,
5353 /*count*/1);
5354 break;
5355 }
5356 case TYPE_INT32:
5357 res = metadata.update(tag,
5358 &trigger.entryValue,
5359 /*count*/1);
5360 break;
5361 default:
5362 ALOGE("%s: Type not supported: 0x%x",
5363 __FUNCTION__,
5364 trigger.getTagType());
5365 return INVALID_OPERATION;
5366 }
5367
5368 if (res != OK) {
5369 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5370 ", value %d", __FUNCTION__, trigger.getTagName(),
5371 trigger.entryValue);
5372 return res;
5373 }
5374
5375 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5376 trigger.getTagName(),
5377 trigger.entryValue);
5378 }
5379
5380 mTriggerMap.clear();
5381
5382 return count;
5383}
5384
5385status_t Camera3Device::RequestThread::removeTriggers(
5386 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005387 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005388 Mutex::Autolock al(mTriggerMutex);
5389
Emilian Peevaebbe412018-01-15 13:53:24 +00005390 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005391
5392 /**
5393 * Replace all old entries with their old values.
5394 */
5395 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5396 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5397
5398 status_t res;
5399
5400 uint32_t tag = trigger.metadataTag;
5401 switch (trigger.getTagType()) {
5402 case TYPE_BYTE: {
5403 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5404 res = metadata.update(tag,
5405 &entryValue,
5406 /*count*/1);
5407 break;
5408 }
5409 case TYPE_INT32:
5410 res = metadata.update(tag,
5411 &trigger.entryValue,
5412 /*count*/1);
5413 break;
5414 default:
5415 ALOGE("%s: Type not supported: 0x%x",
5416 __FUNCTION__,
5417 trigger.getTagType());
5418 return INVALID_OPERATION;
5419 }
5420
5421 if (res != OK) {
5422 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5423 ", trigger value %d", __FUNCTION__,
5424 trigger.getTagName(), trigger.entryValue);
5425 return res;
5426 }
5427 }
5428 mTriggerReplacedMap.clear();
5429
5430 /**
5431 * Remove all new entries.
5432 */
5433 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5434 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5435 status_t res = metadata.erase(trigger.metadataTag);
5436
5437 if (res != OK) {
5438 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5439 ", trigger value %d", __FUNCTION__,
5440 trigger.getTagName(), trigger.entryValue);
5441 return res;
5442 }
5443 }
5444 mTriggerRemovedMap.clear();
5445
5446 return OK;
5447}
5448
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005449status_t Camera3Device::RequestThread::addDummyTriggerIds(
5450 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005451 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005452 static const int32_t dummyTriggerId = 1;
5453 status_t res;
5454
Emilian Peevaebbe412018-01-15 13:53:24 +00005455 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005456
5457 // If AF trigger is active, insert a dummy AF trigger ID if none already
5458 // exists
5459 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5460 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5461 if (afTrigger.count > 0 &&
5462 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5463 afId.count == 0) {
5464 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5465 if (res != OK) return res;
5466 }
5467
5468 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5469 // if none already exists
5470 camera_metadata_entry pcTrigger =
5471 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5472 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5473 if (pcTrigger.count > 0 &&
5474 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5475 pcId.count == 0) {
5476 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5477 &dummyTriggerId, 1);
5478 if (res != OK) return res;
5479 }
5480
5481 return OK;
5482}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005483
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005484/**
5485 * PreparerThread inner class methods
5486 */
5487
5488Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005489 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005490 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005491}
5492
5493Camera3Device::PreparerThread::~PreparerThread() {
5494 Thread::requestExitAndWait();
5495 if (mCurrentStream != nullptr) {
5496 mCurrentStream->cancelPrepare();
5497 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5498 mCurrentStream.clear();
5499 }
5500 clear();
5501}
5502
Ruben Brunkc78ac262015-08-13 17:58:46 -07005503status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005504 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005505 status_t res;
5506
5507 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005508 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005509
Ruben Brunkc78ac262015-08-13 17:58:46 -07005510 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005511 if (res == OK) {
5512 // No preparation needed, fire listener right off
5513 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005514 if (listener != NULL) {
5515 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005516 }
5517 return OK;
5518 } else if (res != NOT_ENOUGH_DATA) {
5519 return res;
5520 }
5521
5522 // Need to prepare, start up thread if necessary
5523 if (!mActive) {
5524 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5525 // isn't running
5526 Thread::requestExitAndWait();
5527 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5528 if (res != OK) {
5529 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005530 if (listener != NULL) {
5531 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005532 }
5533 return res;
5534 }
5535 mCancelNow = false;
5536 mActive = true;
5537 ALOGV("%s: Preparer stream started", __FUNCTION__);
5538 }
5539
5540 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005541 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005542 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5543
5544 return OK;
5545}
5546
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005547void Camera3Device::PreparerThread::pause() {
5548 ATRACE_CALL();
5549
5550 Mutex::Autolock l(mLock);
5551
5552 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5553 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5554 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5555 int currentMaxCount = mCurrentMaxCount;
5556 mPendingStreams.clear();
5557 mCancelNow = true;
5558 while (mActive) {
5559 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5560 if (res == TIMED_OUT) {
5561 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5562 return;
5563 } else if (res != OK) {
5564 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5565 return;
5566 }
5567 }
5568
5569 //Check whether the prepare thread was able to complete the current
5570 //stream. In case work is still pending emplace it along with the rest
5571 //of the streams in the pending list.
5572 if (currentStream != nullptr) {
5573 if (!mCurrentPrepareComplete) {
5574 pendingStreams.emplace(currentMaxCount, currentStream);
5575 }
5576 }
5577
5578 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5579 for (const auto& it : mPendingStreams) {
5580 it.second->cancelPrepare();
5581 }
5582}
5583
5584status_t Camera3Device::PreparerThread::resume() {
5585 ATRACE_CALL();
5586 status_t res;
5587
5588 Mutex::Autolock l(mLock);
5589 sp<NotificationListener> listener = mListener.promote();
5590
5591 if (mActive) {
5592 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5593 return NO_INIT;
5594 }
5595
5596 auto it = mPendingStreams.begin();
5597 for (; it != mPendingStreams.end();) {
5598 res = it->second->startPrepare(it->first);
5599 if (res == OK) {
5600 if (listener != NULL) {
5601 listener->notifyPrepared(it->second->getId());
5602 }
5603 it = mPendingStreams.erase(it);
5604 } else if (res != NOT_ENOUGH_DATA) {
5605 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5606 res, strerror(-res));
5607 it = mPendingStreams.erase(it);
5608 } else {
5609 it++;
5610 }
5611 }
5612
5613 if (mPendingStreams.empty()) {
5614 return OK;
5615 }
5616
5617 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5618 if (res != OK) {
5619 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5620 __FUNCTION__, res, strerror(-res));
5621 return res;
5622 }
5623 mCancelNow = false;
5624 mActive = true;
5625 ALOGV("%s: Preparer stream started", __FUNCTION__);
5626
5627 return OK;
5628}
5629
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005630status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005631 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005632 Mutex::Autolock l(mLock);
5633
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005634 for (const auto& it : mPendingStreams) {
5635 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005636 }
5637 mPendingStreams.clear();
5638 mCancelNow = true;
5639
5640 return OK;
5641}
5642
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005643void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005644 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005645 Mutex::Autolock l(mLock);
5646 mListener = listener;
5647}
5648
5649bool Camera3Device::PreparerThread::threadLoop() {
5650 status_t res;
5651 {
5652 Mutex::Autolock l(mLock);
5653 if (mCurrentStream == nullptr) {
5654 // End thread if done with work
5655 if (mPendingStreams.empty()) {
5656 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5657 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5658 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5659 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005660 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005661 return false;
5662 }
5663
5664 // Get next stream to prepare
5665 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005666 mCurrentStream = it->second;
5667 mCurrentMaxCount = it->first;
5668 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005669 mPendingStreams.erase(it);
5670 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5671 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5672 } else if (mCancelNow) {
5673 mCurrentStream->cancelPrepare();
5674 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5675 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5676 mCurrentStream.clear();
5677 mCancelNow = false;
5678 return true;
5679 }
5680 }
5681
5682 res = mCurrentStream->prepareNextBuffer();
5683 if (res == NOT_ENOUGH_DATA) return true;
5684 if (res != OK) {
5685 // Something bad happened; try to recover by cancelling prepare and
5686 // signalling listener anyway
5687 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5688 mCurrentStream->getId(), res, strerror(-res));
5689 mCurrentStream->cancelPrepare();
5690 }
5691
5692 // This stream has finished, notify listener
5693 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005694 sp<NotificationListener> listener = mListener.promote();
5695 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005696 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5697 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005698 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005699 }
5700
5701 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5702 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005703 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005704
5705 return true;
5706}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005707
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005708/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005709 * Static callback forwarding methods from HAL to instance
5710 */
5711
5712void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5713 const camera3_capture_result *result) {
5714 Camera3Device *d =
5715 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005716
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005717 d->processCaptureResult(result);
5718}
5719
5720void Camera3Device::sNotify(const camera3_callback_ops *cb,
5721 const camera3_notify_msg *msg) {
5722 Camera3Device *d =
5723 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5724 d->notify(msg);
5725}
5726
5727}; // namespace android