blob: 28ffc8b3dbaa24e3793c5630f780b6875ad2b985 [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);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800266
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700267 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800268
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700269 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700270 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700271 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272 {
273 Mutex::Autolock l(mLock);
274 if (mStatus == STATUS_UNINITIALIZED) return res;
275
276 if (mStatus == STATUS_ACTIVE ||
277 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
278 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700279 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700280 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700281 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700283 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700285 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
286 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 // Continue to close device even in case of error
288 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700289 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800290 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800291
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292 if (mStatus == STATUS_ERROR) {
293 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700295
296 if (mStatusTracker != NULL) {
297 mStatusTracker->requestExit();
298 }
299
300 if (mRequestThread != NULL) {
301 mRequestThread->requestExit();
302 }
303
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700304 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
305 for (size_t i = 0; i < mOutputStreams.size(); i++) {
306 streams.push_back(mOutputStreams[i]);
307 }
308 if (mInputStream != nullptr) {
309 streams.push_back(mInputStream);
310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 }
312
313 // Joining done without holding mLock, otherwise deadlocks may ensue
314 // as the threads try to access parent state
315 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
316 // HAL may be in a bad state, so waiting for request thread
317 // (which may be stuck in the HAL processCaptureRequest call)
318 // could be dangerous.
319 mRequestThread->join();
320 }
321
322 if (mStatusTracker != NULL) {
323 mStatusTracker->join();
324 }
325
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800326 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700327 {
328 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800329 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700330 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800331 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700332 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800333
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700334 // Call close without internal mutex held, as the HAL close may need to
335 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800336 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700337
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700338 flushInflightRequests();
339
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700340 {
341 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800342 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700343 mOutputStreams.clear();
344 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700345 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700346 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700347 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800349
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700350 for (auto& weakStream : streams) {
351 sp<Camera3StreamInterface> stream = weakStream.promote();
352 if (stream != nullptr) {
353 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
354 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
355 }
356 }
357
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700358 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700359 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800360}
361
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700362// For dumping/debugging only -
363// try to acquire a lock a few times, eventually give up to proceed with
364// debug/dump operations
365bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
366 bool gotLock = false;
367 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
368 if (lock.tryLock() == NO_ERROR) {
369 gotLock = true;
370 break;
371 } else {
372 usleep(kDumpSleepDuration);
373 }
374 }
375 return gotLock;
376}
377
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700378Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
379 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100380 const int STREAM_CONFIGURATION_SIZE = 4;
381 const int STREAM_FORMAT_OFFSET = 0;
382 const int STREAM_WIDTH_OFFSET = 1;
383 const int STREAM_HEIGHT_OFFSET = 2;
384 const int STREAM_IS_INPUT_OFFSET = 3;
385 camera_metadata_ro_entry_t availableStreamConfigs =
386 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
387 if (availableStreamConfigs.count == 0 ||
388 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
389 return Size(0, 0);
390 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700391
Emilian Peev08dd2452017-04-06 16:55:14 +0100392 // Get max jpeg size (area-wise).
393 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
394 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
395 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
396 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
397 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
398 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
399 && format == HAL_PIXEL_FORMAT_BLOB &&
400 (width * height > maxJpegWidth * maxJpegHeight)) {
401 maxJpegWidth = width;
402 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700403 }
404 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100405
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700406 return Size(maxJpegWidth, maxJpegHeight);
407}
408
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800409nsecs_t Camera3Device::getMonoToBoottimeOffset() {
410 // try three times to get the clock offset, choose the one
411 // with the minimum gap in measurements.
412 const int tries = 3;
413 nsecs_t bestGap, measured;
414 for (int i = 0; i < tries; ++i) {
415 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
416 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
417 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
418 const nsecs_t gap = tmono2 - tmono;
419 if (i == 0 || gap < bestGap) {
420 bestGap = gap;
421 measured = tbase - ((tmono + tmono2) >> 1);
422 }
423 }
424 return measured;
425}
426
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800427hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
428 int frameworkFormat) {
429 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
430}
431
432DataspaceFlags Camera3Device::mapToHidlDataspace(
433 android_dataspace dataSpace) {
434 return dataSpace;
435}
436
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700437BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100438 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700439 return usage;
440}
441
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800442StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
443 switch (rotation) {
444 case CAMERA3_STREAM_ROTATION_0:
445 return StreamRotation::ROTATION_0;
446 case CAMERA3_STREAM_ROTATION_90:
447 return StreamRotation::ROTATION_90;
448 case CAMERA3_STREAM_ROTATION_180:
449 return StreamRotation::ROTATION_180;
450 case CAMERA3_STREAM_ROTATION_270:
451 return StreamRotation::ROTATION_270;
452 }
453 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
454 return StreamRotation::ROTATION_0;
455}
456
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800457status_t Camera3Device::mapToStreamConfigurationMode(
458 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
459 if (mode == nullptr) return BAD_VALUE;
460 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
461 switch(operationMode) {
462 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
463 *mode = StreamConfigurationMode::NORMAL_MODE;
464 break;
465 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
466 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
467 break;
468 default:
469 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
470 return BAD_VALUE;
471 }
472 } else {
473 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800474 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800475 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800476}
477
478camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
479 switch (status) {
480 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
481 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
482 }
483 return CAMERA3_BUFFER_STATUS_ERROR;
484}
485
486int Camera3Device::mapToFrameworkFormat(
487 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
488 return static_cast<uint32_t>(pixelFormat);
489}
490
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700491android_dataspace Camera3Device::mapToFrameworkDataspace(
492 DataspaceFlags dataSpace) {
493 return static_cast<android_dataspace>(dataSpace);
494}
495
Emilian Peev050f5dc2017-05-18 14:43:56 +0100496uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700497 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700498 return usage;
499}
500
Emilian Peev050f5dc2017-05-18 14:43:56 +0100501uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700502 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700503 return usage;
504}
505
Zhijun Hef7da0962014-04-24 13:27:56 -0700506ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700507 // Get max jpeg size (area-wise).
508 Size maxJpegResolution = getMaxJpegResolution();
509 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800510 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
511 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700512 return BAD_VALUE;
513 }
514
Zhijun Hef7da0962014-04-24 13:27:56 -0700515 // Get max jpeg buffer size
516 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700517 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
518 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800519 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
520 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700521 return BAD_VALUE;
522 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700523 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800524 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700525
526 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700527 float scaleFactor = ((float) (width * height)) /
528 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800529 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
530 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700531 if (jpegBufferSize > maxJpegBufferSize) {
532 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700533 }
534
535 return jpegBufferSize;
536}
537
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700538ssize_t Camera3Device::getPointCloudBufferSize() const {
539 const int FLOATS_PER_POINT=4;
540 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
541 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800542 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
543 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700544 return BAD_VALUE;
545 }
546 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
547 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
548 return maxBytesForPointCloud;
549}
550
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800551ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800552 const int PER_CONFIGURATION_SIZE = 3;
553 const int WIDTH_OFFSET = 0;
554 const int HEIGHT_OFFSET = 1;
555 const int SIZE_OFFSET = 2;
556 camera_metadata_ro_entry rawOpaqueSizes =
557 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800558 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800559 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
561 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800562 return BAD_VALUE;
563 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700564
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800565 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
566 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
567 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
568 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
569 }
570 }
571
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
573 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800574 return BAD_VALUE;
575}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700576
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800577status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
578 ATRACE_CALL();
579 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700580
581 // Try to lock, but continue in case of failure (to avoid blocking in
582 // deadlocks)
583 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
584 bool gotLock = tryLockSpinRightRound(mLock);
585
586 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800587 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
588 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700589 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800590 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
591 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700592
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800593 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700594
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800595 String16 templatesOption("-t");
596 int n = args.size();
597 for (int i = 0; i < n; i++) {
598 if (args[i] == templatesOption) {
599 dumpTemplates = true;
600 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000601 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700602 if (i + 1 < n) {
603 String8 monitorTags = String8(args[i + 1]);
604 if (monitorTags == "off") {
605 mTagMonitor.disableMonitoring();
606 } else {
607 mTagMonitor.parseTagsToMonitor(monitorTags);
608 }
609 } else {
610 mTagMonitor.disableMonitoring();
611 }
612 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800613 }
614
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800615 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800616
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 const char *status =
618 mStatus == STATUS_ERROR ? "ERROR" :
619 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700620 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
621 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800622 mStatus == STATUS_ACTIVE ? "ACTIVE" :
623 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700624
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800625 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700626 if (mStatus == STATUS_ERROR) {
627 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
628 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800629 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800630 const char *mode =
631 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
632 mOperatingMode == static_cast<int>(
633 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
634 "CUSTOM";
635 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800636
637 if (mInputStream != NULL) {
638 write(fd, lines.string(), lines.size());
639 mInputStream->dump(fd, args);
640 } else {
641 lines.appendFormat(" No input stream.\n");
642 write(fd, lines.string(), lines.size());
643 }
644 for (size_t i = 0; i < mOutputStreams.size(); i++) {
645 mOutputStreams[i]->dump(fd,args);
646 }
647
Zhijun He431503c2016-03-07 17:30:16 -0800648 if (mBufferManager != NULL) {
649 lines = String8(" Camera3 Buffer Manager:\n");
650 write(fd, lines.string(), lines.size());
651 mBufferManager->dump(fd, args);
652 }
Zhijun He125684a2015-12-26 15:07:30 -0800653
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700654 lines = String8(" In-flight requests:\n");
655 if (mInFlightMap.size() == 0) {
656 lines.append(" None\n");
657 } else {
658 for (size_t i = 0; i < mInFlightMap.size(); i++) {
659 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700660 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700661 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800662 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700663 r.numBuffersLeft);
664 }
665 }
666 write(fd, lines.string(), lines.size());
667
Shuzhen Wang686f6442017-06-20 16:16:04 -0700668 if (mRequestThread != NULL) {
669 mRequestThread->dumpCaptureRequestLatency(fd,
670 " ProcessCaptureRequest latency histogram:");
671 }
672
Igor Murashkin1e479c02013-09-06 16:55:14 -0700673 {
674 lines = String8(" Last request sent:\n");
675 write(fd, lines.string(), lines.size());
676
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700677 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700678 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
679 }
680
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800681 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800682 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800683 "TEMPLATE_PREVIEW",
684 "TEMPLATE_STILL_CAPTURE",
685 "TEMPLATE_VIDEO_RECORD",
686 "TEMPLATE_VIDEO_SNAPSHOT",
687 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800688 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800689 };
690
691 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800692 camera_metadata_t *templateRequest = nullptr;
693 mInterface->constructDefaultRequestSettings(
694 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800697 lines.append(" Not supported\n");
698 write(fd, lines.string(), lines.size());
699 } else {
700 write(fd, lines.string(), lines.size());
701 dump_indented_camera_metadata(templateRequest,
702 fd, /*verbosity*/2, /*indentation*/8);
703 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800704 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800705 }
706 }
707
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700708 mTagMonitor.dumpMonitoredMetadata(fd);
709
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800710 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800711 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800712 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800713 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800715
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716 if (gotLock) mLock.unlock();
717 if (gotInterfaceLock) mInterfaceLock.unlock();
718
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800719 return OK;
720}
721
722const CameraMetadata& Camera3Device::info() const {
723 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
725 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700726 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 mStatus == STATUS_ERROR ?
728 "when in error state" : "before init");
729 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800730 return mDeviceInfo;
731}
732
Jianing Wei90e59c92014-03-12 18:29:36 -0700733status_t Camera3Device::checkStatusOkToCaptureLocked() {
734 switch (mStatus) {
735 case STATUS_ERROR:
736 CLOGE("Device has encountered a serious error");
737 return INVALID_OPERATION;
738 case STATUS_UNINITIALIZED:
739 CLOGE("Device not initialized");
740 return INVALID_OPERATION;
741 case STATUS_UNCONFIGURED:
742 case STATUS_CONFIGURED:
743 case STATUS_ACTIVE:
744 // OK
745 break;
746 default:
747 SET_ERR_L("Unexpected status: %d", mStatus);
748 return INVALID_OPERATION;
749 }
750 return OK;
751}
752
753status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000754 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700755 const std::list<const SurfaceMap> &surfaceMaps,
756 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700757 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700758 if (requestList == NULL) {
759 CLOGE("requestList cannot be NULL.");
760 return BAD_VALUE;
761 }
762
Jianing Weicb0652e2014-03-12 18:29:36 -0700763 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000764 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700765 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
766 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
767 ++metadataIt, ++surfaceMapIt) {
768 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700769 if (newRequest == 0) {
770 CLOGE("Can't create capture request");
771 return BAD_VALUE;
772 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700773
Shuzhen Wang9d066012016-09-30 11:30:20 -0700774 newRequest->mRepeating = repeating;
775
Jianing Weicb0652e2014-03-12 18:29:36 -0700776 // Setup burst Id and request Id
777 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000778 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
779 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700780 CLOGE("RequestID entry exists; but must not be empty in metadata");
781 return BAD_VALUE;
782 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000783 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
784 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700785 } else {
786 CLOGE("RequestID does not exist in metadata");
787 return BAD_VALUE;
788 }
789
Jianing Wei90e59c92014-03-12 18:29:36 -0700790 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700791
792 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700793 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
795 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
796 return BAD_VALUE;
797 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700798
799 // Setup batch size if this is a high speed video recording request.
800 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
801 auto firstRequest = requestList->begin();
802 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
803 if (outputStream->isVideoStream()) {
804 (*firstRequest)->mBatchSize = requestList->size();
805 break;
806 }
807 }
808 }
809
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 return OK;
811}
812
Jianing Weicb0652e2014-03-12 18:29:36 -0700813status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800814 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800815
Emilian Peevaebbe412018-01-15 13:53:24 +0000816 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700817 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000818 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700819
Emilian Peevaebbe412018-01-15 13:53:24 +0000820 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700821}
822
Emilian Peevaebbe412018-01-15 13:53:24 +0000823void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700824 std::list<const SurfaceMap>& surfaceMaps,
825 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000826 PhysicalCameraSettingsList requestList;
827 requestList.push_back({std::string(getId().string()), request});
828 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700829
830 SurfaceMap surfaceMap;
831 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
832 // With no surface list passed in, stream and surface will have 1-to-1
833 // mapping. So the surface index is 0 for each stream in the surfaceMap.
834 for (size_t i = 0; i < streams.count; i++) {
835 surfaceMap[streams.data.i32[i]].push_back(0);
836 }
837 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800838}
839
Jianing Wei90e59c92014-03-12 18:29:36 -0700840status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000841 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700842 const std::list<const SurfaceMap> &surfaceMaps,
843 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700844 /*out*/
845 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700846 ATRACE_CALL();
847 Mutex::Autolock il(mInterfaceLock);
848 Mutex::Autolock l(mLock);
849
850 status_t res = checkStatusOkToCaptureLocked();
851 if (res != OK) {
852 // error logged by previous call
853 return res;
854 }
855
856 RequestList requestList;
857
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
859 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700860 if (res != OK) {
861 // error logged by previous call
862 return res;
863 }
864
865 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700866 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700867 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700868 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700869 }
870
871 if (res == OK) {
872 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
873 if (res != OK) {
874 SET_ERR_L("Can't transition to active in %f seconds!",
875 kActiveTimeout/1e9);
876 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800877 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700878 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700879 } else {
880 CLOGE("Cannot queue request. Impossible.");
881 return BAD_VALUE;
882 }
883
884 return res;
885}
886
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800887hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800888 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800889 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700890 // Ideally we should grab mLock, but that can lead to deadlock, and
891 // it's not super important to get up to date value of mStatus for this
892 // warning print, hence skipping the lock here
893 if (mStatus == STATUS_ERROR) {
894 // Per API contract, HAL should act as closed after device error
895 // But mStatus can be set to error by framework as well, so just log
896 // a warning here.
897 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700898 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700899
900 if (mProcessCaptureResultLock.tryLock() != OK) {
901 // This should never happen; it indicates a wrong client implementation
902 // that doesn't follow the contract. But, we can be tolerant here.
903 ALOGE("%s: callback overlapped! waiting 1s...",
904 __FUNCTION__);
905 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
906 ALOGE("%s: cannot acquire lock in 1s, dropping results",
907 __FUNCTION__);
908 // really don't know what to do, so bail out.
909 return hardware::Void();
910 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800911 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700912 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800913 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700914 }
915 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800916 return hardware::Void();
917}
918
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800919// Only one processCaptureResult should be called at a time, so
920// the locks won't block. The locks are present here simply to enforce this.
921hardware::Return<void> Camera3Device::processCaptureResult(
922 const hardware::hidl_vec<
923 hardware::camera::device::V3_2::CaptureResult>& results) {
924 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
925
926 // Ideally we should grab mLock, but that can lead to deadlock, and
927 // it's not super important to get up to date value of mStatus for this
928 // warning print, hence skipping the lock here
929 if (mStatus == STATUS_ERROR) {
930 // Per API contract, HAL should act as closed after device error
931 // But mStatus can be set to error by framework as well, so just log
932 // a warning here.
933 ALOGW("%s: received capture result in error state.", __FUNCTION__);
934 }
935
936 if (mProcessCaptureResultLock.tryLock() != OK) {
937 // This should never happen; it indicates a wrong client implementation
938 // that doesn't follow the contract. But, we can be tolerant here.
939 ALOGE("%s: callback overlapped! waiting 1s...",
940 __FUNCTION__);
941 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
942 ALOGE("%s: cannot acquire lock in 1s, dropping results",
943 __FUNCTION__);
944 // really don't know what to do, so bail out.
945 return hardware::Void();
946 }
947 }
948 for (const auto& result : results) {
949 processOneCaptureResultLocked(result, noPhysMetadata);
950 }
951 mProcessCaptureResultLock.unlock();
952 return hardware::Void();
953}
954
955status_t Camera3Device::readOneCameraMetadataLocked(
956 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
957 const hardware::camera::device::V3_2::CameraMetadata& result) {
958 if (fmqResultSize > 0) {
959 resultMetadata.resize(fmqResultSize);
960 if (mResultMetadataQueue == nullptr) {
961 return NO_MEMORY; // logged in initialize()
962 }
963 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
964 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
965 __FUNCTION__, fmqResultSize);
966 return INVALID_OPERATION;
967 }
968 } else {
969 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
970 result.size());
971 }
972
973 if (resultMetadata.size() != 0) {
974 status_t res;
975 const camera_metadata_t* metadata =
976 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
977 size_t expected_metadata_size = resultMetadata.size();
978 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
979 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
980 __FUNCTION__, strerror(-res), res);
981 return INVALID_OPERATION;
982 }
983 }
984
985 return OK;
986}
987
Yifan Honga640c5a2017-04-12 16:30:31 -0700988void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800989 const hardware::camera::device::V3_2::CaptureResult& result,
990 const hardware::hidl_vec<
991 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800992 camera3_capture_result r;
993 status_t res;
994 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700995
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800996 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -0700997 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800998 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
999 if (res != OK) {
1000 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1001 __FUNCTION__, result.frameNumber);
1002 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001003 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001004 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001005
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001006 // Read and validate physical camera metadata
1007 size_t physResultCount = physicalCameraMetadatas.size();
1008 std::vector<const char*> physCamIds(physResultCount);
1009 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1010 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1011 physResultMetadata.resize(physResultCount);
1012 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1013 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1014 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1015 if (res != OK) {
1016 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1017 __FUNCTION__, result.frameNumber,
1018 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001019 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001020 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001021 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1022 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1023 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001024 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001025 r.num_physcam_metadata = physResultCount;
1026 r.physcam_ids = physCamIds.data();
1027 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001028
1029 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1030 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1031 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1032 auto& bDst = outputBuffers[i];
1033 const StreamBuffer &bSrc = result.outputBuffers[i];
1034
1035 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001036 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001037 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1038 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001039 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001040 }
1041 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1042
1043 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001044 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001045 if (res != OK) {
1046 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1047 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001049 }
1050 bDst.buffer = buffer;
1051 bDst.status = mapHidlBufferStatus(bSrc.status);
1052 bDst.acquire_fence = -1;
1053 if (bSrc.releaseFence == nullptr) {
1054 bDst.release_fence = -1;
1055 } else if (bSrc.releaseFence->numFds == 1) {
1056 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1057 } else {
1058 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1059 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001060 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001061 }
1062 }
1063 r.num_output_buffers = outputBuffers.size();
1064 r.output_buffers = outputBuffers.data();
1065
1066 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001067 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001068 r.input_buffer = nullptr;
1069 } else {
1070 if (mInputStream->getId() != result.inputBuffer.streamId) {
1071 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1072 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001073 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001074 }
1075 inputBuffer.stream = mInputStream->asHalStream();
1076 buffer_handle_t *buffer;
1077 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1078 &buffer);
1079 if (res != OK) {
1080 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1081 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001082 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001083 }
1084 inputBuffer.buffer = buffer;
1085 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1086 inputBuffer.acquire_fence = -1;
1087 if (result.inputBuffer.releaseFence == nullptr) {
1088 inputBuffer.release_fence = -1;
1089 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1090 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1091 } else {
1092 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1093 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001094 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001095 }
1096 r.input_buffer = &inputBuffer;
1097 }
1098
1099 r.partial_result = result.partialResult;
1100
1101 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001102}
1103
1104hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001105 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001106 // Ideally we should grab mLock, but that can lead to deadlock, and
1107 // it's not super important to get up to date value of mStatus for this
1108 // warning print, hence skipping the lock here
1109 if (mStatus == STATUS_ERROR) {
1110 // Per API contract, HAL should act as closed after device error
1111 // But mStatus can be set to error by framework as well, so just log
1112 // a warning here.
1113 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001114 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001115
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001116 for (const auto& msg : msgs) {
1117 notify(msg);
1118 }
1119 return hardware::Void();
1120}
1121
1122void Camera3Device::notify(
1123 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1124
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125 camera3_notify_msg m;
1126 switch (msg.type) {
1127 case MsgType::ERROR:
1128 m.type = CAMERA3_MSG_ERROR;
1129 m.message.error.frame_number = msg.msg.error.frameNumber;
1130 if (msg.msg.error.errorStreamId >= 0) {
1131 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001132 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001133 ALOGE("%s: Frame %d: Invalid error stream id %d",
1134 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001135 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001136 }
1137 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1138 } else {
1139 m.message.error.error_stream = nullptr;
1140 }
1141 switch (msg.msg.error.errorCode) {
1142 case ErrorCode::ERROR_DEVICE:
1143 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1144 break;
1145 case ErrorCode::ERROR_REQUEST:
1146 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1147 break;
1148 case ErrorCode::ERROR_RESULT:
1149 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1150 break;
1151 case ErrorCode::ERROR_BUFFER:
1152 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1153 break;
1154 }
1155 break;
1156 case MsgType::SHUTTER:
1157 m.type = CAMERA3_MSG_SHUTTER;
1158 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1159 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1160 break;
1161 }
1162 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001163}
1164
Emilian Peevaebbe412018-01-15 13:53:24 +00001165status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001166 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001167 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001168 ATRACE_CALL();
1169
Emilian Peevaebbe412018-01-15 13:53:24 +00001170 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001171}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001172
Jianing Weicb0652e2014-03-12 18:29:36 -07001173status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1174 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001175 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176
Emilian Peevaebbe412018-01-15 13:53:24 +00001177 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001178 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001179 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001180
Emilian Peevaebbe412018-01-15 13:53:24 +00001181 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001182 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183}
1184
Emilian Peevaebbe412018-01-15 13:53:24 +00001185status_t Camera3Device::setStreamingRequestList(
1186 const List<const PhysicalCameraSettingsList> &requestsList,
1187 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001188 ATRACE_CALL();
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001191}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192
1193sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 status_t res;
1196
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001197 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001198 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1199 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001200 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1201 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001202 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001204 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001206 } else if (mStatus == STATUS_UNCONFIGURED) {
1207 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001208 CLOGE("No streams configured");
1209 return NULL;
1210 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 }
1212
Shuzhen Wang0129d522016-10-30 22:43:41 -07001213 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001215}
1216
Jianing Weicb0652e2014-03-12 18:29:36 -07001217status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001218 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001219 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 switch (mStatus) {
1223 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001224 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 return INVALID_OPERATION;
1226 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001227 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001229 case STATUS_UNCONFIGURED:
1230 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 case STATUS_ACTIVE:
1232 // OK
1233 break;
1234 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001235 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 return INVALID_OPERATION;
1237 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001238 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001239
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001240 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001241}
1242
1243status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001247 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248}
1249
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001250status_t Camera3Device::createInputStream(
1251 uint32_t width, uint32_t height, int format, int *id) {
1252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001254 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001256 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1257 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001258
1259 status_t res;
1260 bool wasActive = false;
1261
1262 switch (mStatus) {
1263 case STATUS_ERROR:
1264 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1265 return INVALID_OPERATION;
1266 case STATUS_UNINITIALIZED:
1267 ALOGE("%s: Device not initialized", __FUNCTION__);
1268 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001269 case STATUS_UNCONFIGURED:
1270 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001271 // OK
1272 break;
1273 case STATUS_ACTIVE:
1274 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001275 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001278 return res;
1279 }
1280 wasActive = true;
1281 break;
1282 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284 return INVALID_OPERATION;
1285 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287
1288 if (mInputStream != 0) {
1289 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1290 return INVALID_OPERATION;
1291 }
1292
1293 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1294 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001295 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001296
1297 mInputStream = newStream;
1298
1299 *id = mNextStreamId++;
1300
1301 // Continue captures if active at start
1302 if (wasActive) {
1303 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001304 // Reuse current operating mode and session parameters for new stream config
1305 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 if (res != OK) {
1307 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1308 __FUNCTION__, mNextStreamId, strerror(-res), res);
1309 return res;
1310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001311 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 }
1313
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001314 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001315 return OK;
1316}
1317
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001318status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001319 uint32_t width, uint32_t height, int format,
1320 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001321 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001322 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001323 ATRACE_CALL();
1324
1325 if (consumer == nullptr) {
1326 ALOGE("%s: consumer must not be null", __FUNCTION__);
1327 return BAD_VALUE;
1328 }
1329
1330 std::vector<sp<Surface>> consumers;
1331 consumers.push_back(consumer);
1332
1333 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001334 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1335 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001336}
1337
1338status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1339 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1340 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001341 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001342 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001343 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001345 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001346 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001348 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001349 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1350 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1351 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001352
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 status_t res;
1354 bool wasActive = false;
1355
1356 switch (mStatus) {
1357 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001358 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 return INVALID_OPERATION;
1360 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001361 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001363 case STATUS_UNCONFIGURED:
1364 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 // OK
1366 break;
1367 case STATUS_ACTIVE:
1368 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001369 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001371 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372 return res;
1373 }
1374 wasActive = true;
1375 break;
1376 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001377 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 return INVALID_OPERATION;
1379 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001380 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381
1382 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001383
Shuzhen Wang0129d522016-10-30 22:43:41 -07001384 if (consumers.size() == 0 && !hasDeferredConsumer) {
1385 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1386 return BAD_VALUE;
1387 }
Zhijun He5d677d12016-05-29 16:52:39 -07001388
Shuzhen Wang0129d522016-10-30 22:43:41 -07001389 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001390 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1391 return BAD_VALUE;
1392 }
1393
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001395 ssize_t blobBufferSize;
1396 if (dataSpace != HAL_DATASPACE_DEPTH) {
1397 blobBufferSize = getJpegBufferSize(width, height);
1398 if (blobBufferSize <= 0) {
1399 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1400 return BAD_VALUE;
1401 }
1402 } else {
1403 blobBufferSize = getPointCloudBufferSize();
1404 if (blobBufferSize <= 0) {
1405 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1406 return BAD_VALUE;
1407 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001408 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001409 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001410 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001411 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001412 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1413 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1414 if (rawOpaqueBufferSize <= 0) {
1415 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1416 return BAD_VALUE;
1417 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001419 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001420 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001421 } else if (isShared) {
1422 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1423 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001424 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001426 newStream = new Camera3OutputStream(mNextStreamId,
1427 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001428 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001430 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001431 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001432 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 }
Emilian Peev40ead602017-09-26 15:46:36 +01001434
1435 size_t consumerCount = consumers.size();
1436 for (size_t i = 0; i < consumerCount; i++) {
1437 int id = newStream->getSurfaceId(consumers[i]);
1438 if (id < 0) {
1439 SET_ERR_L("Invalid surface id");
1440 return BAD_VALUE;
1441 }
1442 if (surfaceIds != nullptr) {
1443 surfaceIds->push_back(id);
1444 }
1445 }
1446
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448
Emilian Peev08dd2452017-04-06 16:55:14 +01001449 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001450
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 res = mOutputStreams.add(mNextStreamId, newStream);
1452 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001453 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 return res;
1455 }
1456
1457 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001458 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459
1460 // Continue captures if active at start
1461 if (wasActive) {
1462 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001463 // Reuse current operating mode and session parameters for new stream config
1464 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001466 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1467 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 return res;
1469 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001470 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001472 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474}
1475
Emilian Peev710c1422017-08-30 11:19:38 +01001476status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001478 if (nullptr == streamInfo) {
1479 return BAD_VALUE;
1480 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001483
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 switch (mStatus) {
1485 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001486 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return INVALID_OPERATION;
1488 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001489 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001491 case STATUS_UNCONFIGURED:
1492 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 case STATUS_ACTIVE:
1494 // OK
1495 break;
1496 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001497 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return INVALID_OPERATION;
1499 }
1500
1501 ssize_t idx = mOutputStreams.indexOfKey(id);
1502 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001503 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 return idx;
1505 }
1506
Emilian Peev710c1422017-08-30 11:19:38 +01001507 streamInfo->width = mOutputStreams[idx]->getWidth();
1508 streamInfo->height = mOutputStreams[idx]->getHeight();
1509 streamInfo->format = mOutputStreams[idx]->getFormat();
1510 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1511 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1512 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001513 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1514 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516}
1517
1518status_t Camera3Device::setStreamTransform(int id,
1519 int transform) {
1520 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 switch (mStatus) {
1525 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return INVALID_OPERATION;
1528 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 case STATUS_UNCONFIGURED:
1532 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 case STATUS_ACTIVE:
1534 // OK
1535 break;
1536 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return INVALID_OPERATION;
1539 }
1540
1541 ssize_t idx = mOutputStreams.indexOfKey(id);
1542 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001543 CLOGE("Stream %d does not exist",
1544 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return BAD_VALUE;
1546 }
1547
1548 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001549}
1550
1551status_t Camera3Device::deleteStream(int id) {
1552 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 Mutex::Autolock l(mLock);
1555 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001556
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001557 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001558
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 // CameraDevice semantics require device to already be idle before
1560 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001562 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001563 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 }
1565
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001566 if (mStatus == STATUS_ERROR) {
1567 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1568 __FUNCTION__, mId.string());
1569 return -EBUSY;
1570 }
1571
Igor Murashkin2fba5842013-04-22 14:03:54 -07001572 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001573 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 if (mInputStream != NULL && id == mInputStream->getId()) {
1575 deletedStream = mInputStream;
1576 mInputStream.clear();
1577 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001578 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001579 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 return BAD_VALUE;
1581 }
Zhijun He5f446352014-01-22 09:49:33 -08001582 }
1583
1584 // Delete output stream or the output part of a bi-directional stream.
1585 if (outputStreamIdx != NAME_NOT_FOUND) {
1586 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 mOutputStreams.removeItem(id);
1588 }
1589
1590 // Free up the stream endpoint so that it can be used by some other stream
1591 res = deletedStream->disconnect();
1592 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001593 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 // fall through since we want to still list the stream as deleted.
1595 }
1596 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001597 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598
1599 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001600}
1601
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001602status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001603 ATRACE_CALL();
1604 ALOGV("%s: E", __FUNCTION__);
1605
1606 Mutex::Autolock il(mInterfaceLock);
1607 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001608
Emilian Peev811d2952018-05-25 11:08:40 +01001609 // In case the client doesn't include any session parameter, try a
1610 // speculative configuration using the values from the last cached
1611 // default request.
1612 if (sessionParams.isEmpty() &&
1613 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1614 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1615 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1616 mLastTemplateId);
1617 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1618 operatingMode);
1619 }
1620
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001621 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1622}
1623
1624status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1625 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001626 //Filter out any incoming session parameters
1627 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001628 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1629 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001630 CameraMetadata filteredParams(availableSessionKeys.count);
1631 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1632 filteredParams.getAndLock());
1633 set_camera_metadata_vendor_id(meta, mVendorTagId);
1634 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001635 if (availableSessionKeys.count > 0) {
1636 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1637 camera_metadata_ro_entry entry = params.find(
1638 availableSessionKeys.data.i32[i]);
1639 if (entry.count > 0) {
1640 filteredParams.update(entry);
1641 }
1642 }
1643 }
1644
1645 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001646}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001648status_t Camera3Device::getInputBufferProducer(
1649 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001650 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001651 Mutex::Autolock il(mInterfaceLock);
1652 Mutex::Autolock l(mLock);
1653
1654 if (producer == NULL) {
1655 return BAD_VALUE;
1656 } else if (mInputStream == NULL) {
1657 return INVALID_OPERATION;
1658 }
1659
1660 return mInputStream->getInputBufferProducer(producer);
1661}
1662
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663status_t Camera3Device::createDefaultRequest(int templateId,
1664 CameraMetadata *request) {
1665 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001666 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001667
1668 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1669 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1670 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1671 return BAD_VALUE;
1672 }
1673
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001674 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001675
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001676 {
1677 Mutex::Autolock l(mLock);
1678 switch (mStatus) {
1679 case STATUS_ERROR:
1680 CLOGE("Device has encountered a serious error");
1681 return INVALID_OPERATION;
1682 case STATUS_UNINITIALIZED:
1683 CLOGE("Device is not initialized!");
1684 return INVALID_OPERATION;
1685 case STATUS_UNCONFIGURED:
1686 case STATUS_CONFIGURED:
1687 case STATUS_ACTIVE:
1688 // OK
1689 break;
1690 default:
1691 SET_ERR_L("Unexpected status: %d", mStatus);
1692 return INVALID_OPERATION;
1693 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001695 if (!mRequestTemplateCache[templateId].isEmpty()) {
1696 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001697 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001698 return OK;
1699 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001700 }
1701
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001702 camera_metadata_t *rawRequest;
1703 status_t res = mInterface->constructDefaultRequestSettings(
1704 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001705
1706 {
1707 Mutex::Autolock l(mLock);
1708 if (res == BAD_VALUE) {
1709 ALOGI("%s: template %d is not supported on this camera device",
1710 __FUNCTION__, templateId);
1711 return res;
1712 } else if (res != OK) {
1713 CLOGE("Unable to construct request template %d: %s (%d)",
1714 templateId, strerror(-res), res);
1715 return res;
1716 }
1717
1718 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1719 mRequestTemplateCache[templateId].acquire(rawRequest);
1720
1721 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001722 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001723 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724 return OK;
1725}
1726
1727status_t Camera3Device::waitUntilDrained() {
1728 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001729 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001730 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001731 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001733 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001734}
1735
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001736status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001737 switch (mStatus) {
1738 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001739 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001740 ALOGV("%s: Already idle", __FUNCTION__);
1741 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001742 case STATUS_CONFIGURED:
1743 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001744 case STATUS_ERROR:
1745 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001746 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001747 break;
1748 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001749 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001750 return INVALID_OPERATION;
1751 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001752 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1753 maxExpectedDuration);
1754 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001755 if (res != OK) {
1756 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1757 res);
1758 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001759 return res;
1760}
1761
Ruben Brunk183f0562015-08-12 12:55:02 -07001762
1763void Camera3Device::internalUpdateStatusLocked(Status status) {
1764 mStatus = status;
1765 mRecentStatusUpdates.add(mStatus);
1766 mStatusChanged.broadcast();
1767}
1768
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001769void Camera3Device::pauseStateNotify(bool enable) {
1770 Mutex::Autolock il(mInterfaceLock);
1771 Mutex::Autolock l(mLock);
1772
1773 mPauseStateNotify = enable;
1774}
1775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001777status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001778 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001779
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001780 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1781 maxExpectedDuration);
1782 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001783 if (res != OK) {
1784 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001785 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001786 }
1787
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001788 return res;
1789}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001790
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791// Resume after internalPauseAndWaitLocked
1792status_t Camera3Device::internalResumeLocked() {
1793 status_t res;
1794
1795 mRequestThread->setPaused(false);
1796
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001797 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1798 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1800 if (res != OK) {
1801 SET_ERR_L("Can't transition to active in %f seconds!",
1802 kActiveTimeout/1e9);
1803 }
1804 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806}
1807
Ruben Brunk183f0562015-08-12 12:55:02 -07001808status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001809 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001810
1811 size_t startIndex = 0;
1812 if (mStatusWaiters == 0) {
1813 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1814 // this status list
1815 mRecentStatusUpdates.clear();
1816 } else {
1817 // If other threads are waiting on updates to this status list, set the position of the
1818 // first element that this list will check rather than clearing the list.
1819 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820 }
1821
Ruben Brunk183f0562015-08-12 12:55:02 -07001822 mStatusWaiters++;
1823
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 bool stateSeen = false;
1825 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001826 if (active == (mStatus == STATUS_ACTIVE)) {
1827 // Desired state is current
1828 break;
1829 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001830
1831 res = mStatusChanged.waitRelative(mLock, timeout);
1832 if (res != OK) break;
1833
Ruben Brunk183f0562015-08-12 12:55:02 -07001834 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1835 // transitions.
1836 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1837 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1838 __FUNCTION__);
1839
1840 // Encountered desired state since we began waiting
1841 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1843 stateSeen = true;
1844 break;
1845 }
1846 }
1847 } while (!stateSeen);
1848
Ruben Brunk183f0562015-08-12 12:55:02 -07001849 mStatusWaiters--;
1850
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001851 return res;
1852}
1853
1854
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001855status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001856 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001857 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001858
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001859 if (listener != NULL && mListener != NULL) {
1860 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1861 }
1862 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001863 mRequestThread->setNotificationListener(listener);
1864 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001865
1866 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867}
1868
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001869bool Camera3Device::willNotify3A() {
1870 return false;
1871}
1872
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001873status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001874 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001875 status_t res;
1876 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001878 while (mResultQueue.empty()) {
1879 res = mResultSignal.waitRelative(mOutputLock, timeout);
1880 if (res == TIMED_OUT) {
1881 return res;
1882 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001883 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1884 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001885 return res;
1886 }
1887 }
1888 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889}
1890
Jianing Weicb0652e2014-03-12 18:29:36 -07001891status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001893 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001895 if (mResultQueue.empty()) {
1896 return NOT_ENOUGH_DATA;
1897 }
1898
Jianing Weicb0652e2014-03-12 18:29:36 -07001899 if (frame == NULL) {
1900 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1901 return BAD_VALUE;
1902 }
1903
1904 CaptureResult &result = *(mResultQueue.begin());
1905 frame->mResultExtras = result.mResultExtras;
1906 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001907 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 mResultQueue.erase(mResultQueue.begin());
1909
1910 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911}
1912
1913status_t Camera3Device::triggerAutofocus(uint32_t id) {
1914 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001917 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1918 // Mix-in this trigger into the next request and only the next request.
1919 RequestTrigger trigger[] = {
1920 {
1921 ANDROID_CONTROL_AF_TRIGGER,
1922 ANDROID_CONTROL_AF_TRIGGER_START
1923 },
1924 {
1925 ANDROID_CONTROL_AF_TRIGGER_ID,
1926 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001927 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001928 };
1929
1930 return mRequestThread->queueTrigger(trigger,
1931 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001932}
1933
1934status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1935 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001936 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001937
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001938 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1939 // Mix-in this trigger into the next request and only the next request.
1940 RequestTrigger trigger[] = {
1941 {
1942 ANDROID_CONTROL_AF_TRIGGER,
1943 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1944 },
1945 {
1946 ANDROID_CONTROL_AF_TRIGGER_ID,
1947 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001948 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001949 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001951 return mRequestThread->queueTrigger(trigger,
1952 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001953}
1954
1955status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1956 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001957 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001958
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001959 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1960 // Mix-in this trigger into the next request and only the next request.
1961 RequestTrigger trigger[] = {
1962 {
1963 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1964 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1965 },
1966 {
1967 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1968 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001969 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001970 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001972 return mRequestThread->queueTrigger(trigger,
1973 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974}
1975
Jianing Weicb0652e2014-03-12 18:29:36 -07001976status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001977 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001978 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001979 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001980
Zhijun He7ef20392014-04-21 16:04:17 -07001981 {
1982 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001983 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001984 }
1985
Emilian Peev08dd2452017-04-06 16:55:14 +01001986 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001987}
1988
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001989status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001990 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1991}
1992
1993status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001994 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001995 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001996 Mutex::Autolock il(mInterfaceLock);
1997 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001998
1999 sp<Camera3StreamInterface> stream;
2000 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2001 if (outputStreamIdx == NAME_NOT_FOUND) {
2002 CLOGE("Stream %d does not exist", streamId);
2003 return BAD_VALUE;
2004 }
2005
2006 stream = mOutputStreams.editValueAt(outputStreamIdx);
2007
2008 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002009 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002010 return BAD_VALUE;
2011 }
2012
2013 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002014 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002015 return BAD_VALUE;
2016 }
2017
Ruben Brunkc78ac262015-08-13 17:58:46 -07002018 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019}
2020
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002021status_t Camera3Device::tearDown(int streamId) {
2022 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002023 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002024 Mutex::Autolock il(mInterfaceLock);
2025 Mutex::Autolock l(mLock);
2026
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002027 sp<Camera3StreamInterface> stream;
2028 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2029 if (outputStreamIdx == NAME_NOT_FOUND) {
2030 CLOGE("Stream %d does not exist", streamId);
2031 return BAD_VALUE;
2032 }
2033
2034 stream = mOutputStreams.editValueAt(outputStreamIdx);
2035
2036 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2037 CLOGE("Stream %d is a target of a in-progress request", streamId);
2038 return BAD_VALUE;
2039 }
2040
2041 return stream->tearDown();
2042}
2043
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002044status_t Camera3Device::addBufferListenerForStream(int streamId,
2045 wp<Camera3StreamBufferListener> listener) {
2046 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002047 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002048 Mutex::Autolock il(mInterfaceLock);
2049 Mutex::Autolock l(mLock);
2050
2051 sp<Camera3StreamInterface> stream;
2052 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2053 if (outputStreamIdx == NAME_NOT_FOUND) {
2054 CLOGE("Stream %d does not exist", streamId);
2055 return BAD_VALUE;
2056 }
2057
2058 stream = mOutputStreams.editValueAt(outputStreamIdx);
2059 stream->addBufferListener(listener);
2060
2061 return OK;
2062}
2063
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065 * Methods called by subclasses
2066 */
2067
2068void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002069 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002070 {
2071 // Need mLock to safely update state and synchronize to current
2072 // state of methods in flight.
2073 Mutex::Autolock l(mLock);
2074 // We can get various system-idle notices from the status tracker
2075 // while starting up. Only care about them if we've actually sent
2076 // in some requests recently.
2077 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2078 return;
2079 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002080 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2081 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002082 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002083
2084 // Skip notifying listener if we're doing some user-transparent
2085 // state changes
2086 if (mPauseStateNotify) return;
2087 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002088
2089 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090 {
2091 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002092 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002093 }
2094 if (idle && listener != NULL) {
2095 listener->notifyIdle();
2096 }
2097}
2098
Shuzhen Wang758c2152017-01-10 18:26:18 -08002099status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002100 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002101 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002102 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2103 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002104
2105 if (surfaceIds == nullptr) {
2106 return BAD_VALUE;
2107 }
2108
Zhijun He5d677d12016-05-29 16:52:39 -07002109 Mutex::Autolock il(mInterfaceLock);
2110 Mutex::Autolock l(mLock);
2111
Shuzhen Wang758c2152017-01-10 18:26:18 -08002112 if (consumers.size() == 0) {
2113 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002114 return BAD_VALUE;
2115 }
2116
2117 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2118 if (idx == NAME_NOT_FOUND) {
2119 CLOGE("Stream %d is unknown", streamId);
2120 return idx;
2121 }
2122 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002123 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002124 if (res != OK) {
2125 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2126 return res;
2127 }
2128
Emilian Peev40ead602017-09-26 15:46:36 +01002129 for (auto &consumer : consumers) {
2130 int id = stream->getSurfaceId(consumer);
2131 if (id < 0) {
2132 CLOGE("Invalid surface id!");
2133 return BAD_VALUE;
2134 }
2135 surfaceIds->push_back(id);
2136 }
2137
Shuzhen Wang0129d522016-10-30 22:43:41 -07002138 if (stream->isConsumerConfigurationDeferred()) {
2139 if (!stream->isConfiguring()) {
2140 CLOGE("Stream %d was already fully configured.", streamId);
2141 return INVALID_OPERATION;
2142 }
Zhijun He5d677d12016-05-29 16:52:39 -07002143
Shuzhen Wang0129d522016-10-30 22:43:41 -07002144 res = stream->finishConfiguration();
2145 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002146 // If finishConfiguration fails due to abandoned surface, do not set
2147 // device to error state.
2148 bool isSurfaceAbandoned =
2149 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2150 if (!isSurfaceAbandoned) {
2151 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2152 stream->getId(), strerror(-res), res);
2153 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002154 return res;
2155 }
Zhijun He5d677d12016-05-29 16:52:39 -07002156 }
2157
2158 return OK;
2159}
2160
Emilian Peev40ead602017-09-26 15:46:36 +01002161status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2162 const std::vector<OutputStreamInfo> &outputInfo,
2163 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2164 Mutex::Autolock il(mInterfaceLock);
2165 Mutex::Autolock l(mLock);
2166
2167 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2168 if (idx == NAME_NOT_FOUND) {
2169 CLOGE("Stream %d is unknown", streamId);
2170 return idx;
2171 }
2172
2173 for (const auto &it : removedSurfaceIds) {
2174 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2175 CLOGE("Shared surface still part of a pending request!");
2176 return -EBUSY;
2177 }
2178 }
2179
2180 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2181 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2182 if (res != OK) {
2183 CLOGE("Stream %d failed to update stream (error %d %s) ",
2184 streamId, res, strerror(-res));
2185 if (res == UNKNOWN_ERROR) {
2186 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2187 __FUNCTION__);
2188 }
2189 return res;
2190 }
2191
2192 return res;
2193}
2194
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002195status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2196 Mutex::Autolock il(mInterfaceLock);
2197 Mutex::Autolock l(mLock);
2198
2199 int idx = mOutputStreams.indexOfKey(streamId);
2200 if (idx == NAME_NOT_FOUND) {
2201 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2202 return BAD_VALUE;
2203 }
2204
2205 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2206 return stream->dropBuffers(dropping);
2207}
2208
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002209/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 * Camera3Device private methods
2211 */
2212
2213sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002214 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002215 ATRACE_CALL();
2216 status_t res;
2217
2218 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002219 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220
2221 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002222 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 if (inputStreams.count > 0) {
2224 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002225 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002226 CLOGE("Request references unknown input stream %d",
2227 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228 return NULL;
2229 }
2230 // Lazy completion of stream configuration (allocation/registration)
2231 // on first use
2232 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002233 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002235 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002236 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002237 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238 return NULL;
2239 }
2240 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002241 // Check if stream is being prepared
2242 if (mInputStream->isPreparing()) {
2243 CLOGE("Request references an input stream that's being prepared!");
2244 return NULL;
2245 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246
2247 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002248 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 }
2250
2251 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002252 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002254 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255 return NULL;
2256 }
2257
2258 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002259 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002260 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002261 CLOGE("Request references unknown stream %d",
2262 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002263 return NULL;
2264 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002265 sp<Camera3OutputStreamInterface> stream =
2266 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002267
Zhijun He5d677d12016-05-29 16:52:39 -07002268 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002269 auto iter = surfaceMap.find(streams.data.i32[i]);
2270 if (iter != surfaceMap.end()) {
2271 const std::vector<size_t>& surfaces = iter->second;
2272 for (const auto& surface : surfaces) {
2273 if (stream->isConsumerConfigurationDeferred(surface)) {
2274 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2275 "due to deferred consumer", stream->getId(), surface);
2276 return NULL;
2277 }
2278 }
2279 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002280 }
2281
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002282 // Lazy completion of stream configuration (allocation/registration)
2283 // on first use
2284 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002285 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002286 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002287 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2288 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289 return NULL;
2290 }
2291 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002292 // Check if stream is being prepared
2293 if (stream->isPreparing()) {
2294 CLOGE("Request references an output stream that's being prepared!");
2295 return NULL;
2296 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297
2298 newRequest->mOutputStreams.push(stream);
2299 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002300 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002301 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302
2303 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304}
2305
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002306bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2307 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2308 Size size = mSupportedOpaqueInputSizes[i];
2309 if (size.width == width && size.height == height) {
2310 return true;
2311 }
2312 }
2313
2314 return false;
2315}
2316
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002317void Camera3Device::cancelStreamsConfigurationLocked() {
2318 int res = OK;
2319 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2320 res = mInputStream->cancelConfiguration();
2321 if (res != OK) {
2322 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2323 mInputStream->getId(), strerror(-res), res);
2324 }
2325 }
2326
2327 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2328 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2329 if (outputStream->isConfiguring()) {
2330 res = outputStream->cancelConfiguration();
2331 if (res != OK) {
2332 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2333 outputStream->getId(), strerror(-res), res);
2334 }
2335 }
2336 }
2337
2338 // Return state to that at start of call, so that future configures
2339 // properly clean things up
2340 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2341 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002342
2343 res = mPreparerThread->resume();
2344 if (res != OK) {
2345 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2346 }
2347}
2348
2349bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2350 ATRACE_CALL();
2351 bool ret = false;
2352
2353 Mutex::Autolock il(mInterfaceLock);
2354 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2355
2356 Mutex::Autolock l(mLock);
2357 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2358 if (rc == NO_ERROR) {
2359 mNeedConfig = true;
2360 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2361 if (rc == NO_ERROR) {
2362 ret = true;
2363 mPauseStateNotify = false;
2364 //Moving to active state while holding 'mLock' is important.
2365 //There could be pending calls to 'create-/deleteStream' which
2366 //will trigger another stream configuration while the already
2367 //present streams end up with outstanding buffers that will
2368 //not get drained.
2369 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002370 } else if (rc == DEAD_OBJECT) {
2371 // DEAD_OBJECT can be returned if either the consumer surface is
2372 // abandoned, or the HAL has died.
2373 // - If the HAL has died, configureStreamsLocked call will set
2374 // device to error state,
2375 // - If surface is abandoned, we should not set device to error
2376 // state.
2377 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002378 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002379 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002380 }
2381 } else {
2382 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2383 }
2384
2385 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002386}
2387
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002388status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002389 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 ATRACE_CALL();
2391 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002392
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002393 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002394 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 return INVALID_OPERATION;
2396 }
2397
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002398 if (operatingMode < 0) {
2399 CLOGE("Invalid operating mode: %d", operatingMode);
2400 return BAD_VALUE;
2401 }
2402
2403 bool isConstrainedHighSpeed =
2404 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2405 operatingMode;
2406
2407 if (mOperatingMode != operatingMode) {
2408 mNeedConfig = true;
2409 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2410 mOperatingMode = operatingMode;
2411 }
2412
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002413 if (!mNeedConfig) {
2414 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2415 return OK;
2416 }
2417
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002418 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2419 // adding a dummy stream instead.
2420 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2421 if (mOutputStreams.size() == 0) {
2422 addDummyStreamLocked();
2423 } else {
2424 tryRemoveDummyStreamLocked();
2425 }
2426
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002428 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002429
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002430 mPreparerThread->pause();
2431
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002432 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002433 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2435
2436 Vector<camera3_stream_t*> streams;
2437 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002438 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002439
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440
2441 if (mInputStream != NULL) {
2442 camera3_stream_t *inputStream;
2443 inputStream = mInputStream->startConfiguration();
2444 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002445 CLOGE("Can't start input stream configuration");
2446 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002447 return INVALID_OPERATION;
2448 }
2449 streams.add(inputStream);
2450 }
2451
2452 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002453
2454 // Don't configure bidi streams twice, nor add them twice to the list
2455 if (mOutputStreams[i].get() ==
2456 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2457
2458 config.num_streams--;
2459 continue;
2460 }
2461
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002462 camera3_stream_t *outputStream;
2463 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2464 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002465 CLOGE("Can't start output stream configuration");
2466 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467 return INVALID_OPERATION;
2468 }
2469 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002470
2471 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2472 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002473 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2474 // always occupy the initial entry.
2475 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002476 getJpegBufferSize(outputStream->width, outputStream->height));
2477 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478 }
2479
2480 config.streams = streams.editArray();
2481
2482 // Do the HAL configuration; will potentially touch stream
2483 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002484
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002485 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002486 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002487 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002488
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002489 if (res == BAD_VALUE) {
2490 // HAL rejected this set of streams as unsupported, clean up config
2491 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002492 CLOGE("Set of requested inputs/outputs not supported by HAL");
2493 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002494 return BAD_VALUE;
2495 } else if (res != OK) {
2496 // Some other kind of error from configure_streams - this is not
2497 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002498 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2499 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002500 return res;
2501 }
2502
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002503 // Finish all stream configuration immediately.
2504 // TODO: Try to relax this later back to lazy completion, which should be
2505 // faster
2506
Igor Murashkin073f8572013-05-02 14:59:28 -07002507 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002508 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002509 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002510 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002511 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002512 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002513 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2514 return DEAD_OBJECT;
2515 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002516 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002517 }
2518 }
2519
2520 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002521 sp<Camera3OutputStreamInterface> outputStream =
2522 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002523 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002524 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002525 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002526 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002527 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002528 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002529 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2530 return DEAD_OBJECT;
2531 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002532 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002533 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002534 }
2535 }
2536
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002537 // Request thread needs to know to avoid using repeat-last-settings protocol
2538 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002539 if (notifyRequestThread) {
2540 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2541 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002542
Zhijun He90f7c372016-08-16 16:19:43 -07002543 char value[PROPERTY_VALUE_MAX];
2544 property_get("camera.fifo.disable", value, "0");
2545 int32_t disableFifo = atoi(value);
2546 if (disableFifo != 1) {
2547 // Boost priority of request thread to SCHED_FIFO.
2548 pid_t requestThreadTid = mRequestThread->getTid();
2549 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002550 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002551 if (res != OK) {
2552 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2553 strerror(-res), res);
2554 } else {
2555 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2556 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002557 }
2558
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002559 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002560 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2561 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2562 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2563 sessionParams.unlock(newSessionParams);
2564 mSessionParams.unlock(currentSessionParams);
2565 if (updateSessionParams) {
2566 mSessionParams = sessionParams;
2567 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002568
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002569 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002570
Ruben Brunk183f0562015-08-12 12:55:02 -07002571 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2572 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002573
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002574 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002575
Zhijun He0a210512014-07-24 13:45:15 -07002576 // tear down the deleted streams after configure streams.
2577 mDeletedStreams.clear();
2578
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002579 auto rc = mPreparerThread->resume();
2580 if (rc != OK) {
2581 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2582 return rc;
2583 }
2584
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002585 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002586}
2587
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002588status_t Camera3Device::addDummyStreamLocked() {
2589 ATRACE_CALL();
2590 status_t res;
2591
2592 if (mDummyStreamId != NO_STREAM) {
2593 // Should never be adding a second dummy stream when one is already
2594 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002595 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2596 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002597 return INVALID_OPERATION;
2598 }
2599
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002600 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002601
2602 sp<Camera3OutputStreamInterface> dummyStream =
2603 new Camera3DummyStream(mNextStreamId);
2604
2605 res = mOutputStreams.add(mNextStreamId, dummyStream);
2606 if (res < 0) {
2607 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2608 return res;
2609 }
2610
2611 mDummyStreamId = mNextStreamId;
2612 mNextStreamId++;
2613
2614 return OK;
2615}
2616
2617status_t Camera3Device::tryRemoveDummyStreamLocked() {
2618 ATRACE_CALL();
2619 status_t res;
2620
2621 if (mDummyStreamId == NO_STREAM) return OK;
2622 if (mOutputStreams.size() == 1) return OK;
2623
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002624 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002625
2626 // Ok, have a dummy stream and there's at least one other output stream,
2627 // so remove the dummy
2628
2629 sp<Camera3StreamInterface> deletedStream;
2630 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2631 if (outputStreamIdx == NAME_NOT_FOUND) {
2632 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2633 return INVALID_OPERATION;
2634 }
2635
2636 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2637 mOutputStreams.removeItemsAt(outputStreamIdx);
2638
2639 // Free up the stream endpoint so that it can be used by some other stream
2640 res = deletedStream->disconnect();
2641 if (res != OK) {
2642 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2643 // fall through since we want to still list the stream as deleted.
2644 }
2645 mDeletedStreams.add(deletedStream);
2646 mDummyStreamId = NO_STREAM;
2647
2648 return res;
2649}
2650
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002651void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002652 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002653 Mutex::Autolock l(mLock);
2654 va_list args;
2655 va_start(args, fmt);
2656
2657 setErrorStateLockedV(fmt, args);
2658
2659 va_end(args);
2660}
2661
2662void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002663 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002664 Mutex::Autolock l(mLock);
2665 setErrorStateLockedV(fmt, args);
2666}
2667
2668void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2669 va_list args;
2670 va_start(args, fmt);
2671
2672 setErrorStateLockedV(fmt, args);
2673
2674 va_end(args);
2675}
2676
2677void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002678 // Print out all error messages to log
2679 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002680 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002681
2682 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002683 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002684
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002685 mErrorCause = errorCause;
2686
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002687 if (mRequestThread != nullptr) {
2688 mRequestThread->setPaused(true);
2689 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002690 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002691
2692 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002693 sp<NotificationListener> listener = mListener.promote();
2694 if (listener != NULL) {
2695 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002696 CaptureResultExtras());
2697 }
2698
2699 // Save stack trace. View by dumping it later.
2700 CameraTraces::saveTrace();
2701 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002702}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002703
2704/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002705 * In-flight request management
2706 */
2707
Jianing Weicb0652e2014-03-12 18:29:36 -07002708status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002709 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002710 bool hasAppCallback, nsecs_t maxExpectedDuration,
2711 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002712 ATRACE_CALL();
2713 Mutex::Autolock l(mInFlightLock);
2714
2715 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002716 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002717 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002718 if (res < 0) return res;
2719
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002720 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002721 // hold mLock to prevent race with disconnect
2722 Mutex::Autolock l(mLock);
2723 if (mStatusTracker != nullptr) {
2724 mStatusTracker->markComponentActive(mInFlightStatusId);
2725 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002726 }
2727
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002728 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002729 return OK;
2730}
2731
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002732void Camera3Device::returnOutputBuffers(
2733 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2734 nsecs_t timestamp) {
2735 for (size_t i = 0; i < numBuffers; i++)
2736 {
2737 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2738 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2739 // Note: stream may be deallocated at this point, if this buffer was
2740 // the last reference to it.
2741 if (res != OK) {
2742 ALOGE("Can't return buffer to its stream: %s (%d)",
2743 strerror(-res), res);
2744 }
2745 }
2746}
2747
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002748void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002749 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002750 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002751 mInFlightMap.removeItemsAt(idx, 1);
2752
2753 // Indicate idle inFlightMap to the status tracker
2754 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002755 // hold mLock to prevent race with disconnect
2756 Mutex::Autolock l(mLock);
2757 if (mStatusTracker != nullptr) {
2758 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2759 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002760 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002761 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002762}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002763
2764void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2765
2766 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2767 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2768
2769 nsecs_t sensorTimestamp = request.sensorTimestamp;
2770 nsecs_t shutterTimestamp = request.shutterTimestamp;
2771
2772 // Check if it's okay to remove the request from InFlightMap:
2773 // In the case of a successful request:
2774 // all input and output buffers, all result metadata, shutter callback
2775 // arrived.
2776 // In the case of a unsuccessful request:
2777 // all input and output buffers arrived.
2778 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002779 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002780 (request.haveResultMetadata && shutterTimestamp != 0))) {
2781 ATRACE_ASYNC_END("frame capture", frameNumber);
2782
Shuzhen Wang403044a2017-02-26 23:29:04 -08002783 // Sanity check - if sensor timestamp matches shutter timestamp in the
2784 // case of request having callback.
2785 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002786 sensorTimestamp != shutterTimestamp) {
2787 SET_ERR("sensor timestamp (%" PRId64
2788 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2789 sensorTimestamp, frameNumber, shutterTimestamp);
2790 }
2791
2792 // for an unsuccessful request, it may have pending output buffers to
2793 // return.
2794 assert(request.requestStatus != OK ||
2795 request.pendingOutputBuffers.size() == 0);
2796 returnOutputBuffers(request.pendingOutputBuffers.array(),
2797 request.pendingOutputBuffers.size(), 0);
2798
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002799 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002800 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2801 }
2802
2803 // Sanity check - if we have too many in-flight frames, something has
2804 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002805 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002806 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002807 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2808 kInFlightWarnLimitHighSpeed) {
2809 CLOGE("In-flight list too large for high speed configuration: %zu",
2810 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002811 }
2812}
2813
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002814void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002815 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002816 { // First return buffers cached in mInFlightMap
2817 Mutex::Autolock l(mInFlightLock);
2818 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2819 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2820 returnOutputBuffers(request.pendingOutputBuffers.array(),
2821 request.pendingOutputBuffers.size(), 0);
2822 }
2823 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002824 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002825 }
2826
2827 // Then return all inflight buffers not returned by HAL
2828 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2829 mInterface->getInflightBufferKeys(&inflightKeys);
2830
2831 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2832 for (auto& pair : inflightKeys) {
2833 int32_t frameNumber = pair.first;
2834 int32_t streamId = pair.second;
2835 buffer_handle_t* buffer;
2836 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2837 if (res != OK) {
2838 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2839 __FUNCTION__, frameNumber, streamId);
2840 continue;
2841 }
2842
2843 camera3_stream_buffer_t streamBuffer;
2844 streamBuffer.buffer = buffer;
2845 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2846 streamBuffer.acquire_fence = -1;
2847 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002848
2849 // First check if the buffer belongs to deleted stream
2850 bool streamDeleted = false;
2851 for (auto& stream : mDeletedStreams) {
2852 if (streamId == stream->getId()) {
2853 streamDeleted = true;
2854 // Return buffer to deleted stream
2855 camera3_stream* halStream = stream->asHalStream();
2856 streamBuffer.stream = halStream;
2857 switch (halStream->stream_type) {
2858 case CAMERA3_STREAM_OUTPUT:
2859 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2860 if (res != OK) {
2861 ALOGE("%s: Can't return output buffer for frame %d to"
2862 " stream %d: %s (%d)", __FUNCTION__,
2863 frameNumber, streamId, strerror(-res), res);
2864 }
2865 break;
2866 case CAMERA3_STREAM_INPUT:
2867 res = stream->returnInputBuffer(streamBuffer);
2868 if (res != OK) {
2869 ALOGE("%s: Can't return input buffer for frame %d to"
2870 " stream %d: %s (%d)", __FUNCTION__,
2871 frameNumber, streamId, strerror(-res), res);
2872 }
2873 break;
2874 default: // Bi-direcitonal stream is deprecated
2875 ALOGE("%s: stream %d has unknown stream type %d",
2876 __FUNCTION__, streamId, halStream->stream_type);
2877 break;
2878 }
2879 break;
2880 }
2881 }
2882 if (streamDeleted) {
2883 continue;
2884 }
2885
2886 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002887 if (streamId == inputStreamId) {
2888 streamBuffer.stream = mInputStream->asHalStream();
2889 res = mInputStream->returnInputBuffer(streamBuffer);
2890 if (res != OK) {
2891 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002892 " stream %d: %s (%d)", __FUNCTION__,
2893 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002894 }
2895 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002896 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2897 if (idx == NAME_NOT_FOUND) {
2898 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2899 continue;
2900 }
2901 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002902 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2903 }
2904 }
2905}
2906
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002907void Camera3Device::insertResultLocked(CaptureResult *result,
2908 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002909 if (result == nullptr) return;
2910
Emilian Peev71c73a22017-03-21 16:35:51 +00002911 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2912 result->mMetadata.getAndLock());
2913 set_camera_metadata_vendor_id(meta, mVendorTagId);
2914 result->mMetadata.unlock(meta);
2915
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002916 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2917 (int32_t*)&frameNumber, 1) != OK) {
2918 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2919 return;
2920 }
2921
2922 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2923 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2924 return;
2925 }
2926
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002927 // Valid result, insert into queue
2928 List<CaptureResult>::iterator queuedResult =
2929 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2930 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2931 ", burstId = %" PRId32, __FUNCTION__,
2932 queuedResult->mResultExtras.requestId,
2933 queuedResult->mResultExtras.frameNumber,
2934 queuedResult->mResultExtras.burstId);
2935
2936 mResultSignal.signal();
2937}
2938
2939
2940void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002941 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002942 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002943 Mutex::Autolock l(mOutputLock);
2944
2945 CaptureResult captureResult;
2946 captureResult.mResultExtras = resultExtras;
2947 captureResult.mMetadata = partialResult;
2948
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002949 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002950}
2951
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002952
2953void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2954 CaptureResultExtras &resultExtras,
2955 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002956 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002957 bool reprocess,
2958 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002959 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002960 if (pendingMetadata.isEmpty())
2961 return;
2962
2963 Mutex::Autolock l(mOutputLock);
2964
2965 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002966 if (reprocess) {
2967 if (frameNumber < mNextReprocessResultFrameNumber) {
2968 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002969 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002970 frameNumber, mNextReprocessResultFrameNumber);
2971 return;
2972 }
2973 mNextReprocessResultFrameNumber = frameNumber + 1;
2974 } else {
2975 if (frameNumber < mNextResultFrameNumber) {
2976 SET_ERR("Out-of-order capture result metadata submitted! "
2977 "(got frame number %d, expecting %d)",
2978 frameNumber, mNextResultFrameNumber);
2979 return;
2980 }
2981 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002982 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002983
2984 CaptureResult captureResult;
2985 captureResult.mResultExtras = resultExtras;
2986 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002987 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002988
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002989 // Append any previous partials to form a complete result
2990 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2991 captureResult.mMetadata.append(collectedPartialResult);
2992 }
2993
2994 captureResult.mMetadata.sort();
2995
2996 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002997 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2998 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002999 SET_ERR("No timestamp provided by HAL for frame %d!",
3000 frameNumber);
3001 return;
3002 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003003 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3004 camera_metadata_entry timestamp =
3005 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3006 if (timestamp.count == 0) {
3007 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3008 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3009 return;
3010 }
3011 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003013 // Fix up some result metadata to account for HAL-level distortion correction
3014 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3015 if (res != OK) {
3016 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3017 frameNumber, strerror(res), res);
3018 return;
3019 }
3020
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003021 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3022 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3023
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003024 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025}
3026
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003027/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003028 * Camera HAL device callback methods
3029 */
3030
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003031void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003032 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003033
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003034 status_t res;
3035
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003036 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003037 if (result->result == NULL && result->num_output_buffers == 0 &&
3038 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003039 SET_ERR("No result data provided by HAL for frame %d",
3040 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003041 return;
3042 }
Zhijun He204e3292014-07-14 17:09:23 -07003043
Zhijun He204e3292014-07-14 17:09:23 -07003044 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003045 result->result != NULL &&
3046 result->partial_result != 1) {
3047 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3048 " if partial result is not supported",
3049 frameNumber, result->partial_result);
3050 return;
3051 }
3052
3053 bool isPartialResult = false;
3054 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003055 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003056
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003057 // Get shutter timestamp and resultExtras from list of in-flight requests,
3058 // where it was added by the shutter notification for this frame. If the
3059 // shutter timestamp isn't received yet, append the output buffers to the
3060 // in-flight request and they will be returned when the shutter timestamp
3061 // arrives. Update the in-flight status and remove the in-flight entry if
3062 // all result data and shutter timestamp have been received.
3063 nsecs_t shutterTimestamp = 0;
3064
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003065 {
3066 Mutex::Autolock l(mInFlightLock);
3067 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3068 if (idx == NAME_NOT_FOUND) {
3069 SET_ERR("Unknown frame number for capture result: %d",
3070 frameNumber);
3071 return;
3072 }
3073 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003074 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3075 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003076 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003077 __FUNCTION__, request.resultExtras.requestId,
3078 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003079 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003080 // Always update the partial count to the latest one if it's not 0
3081 // (buffers only). When framework aggregates adjacent partial results
3082 // into one, the latest partial count will be used.
3083 if (result->partial_result != 0)
3084 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003085
3086 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003087 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003088 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3089 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3090 " the range of [1, %d] when metadata is included in the result",
3091 frameNumber, result->partial_result, mNumPartialResults);
3092 return;
3093 }
3094 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003095 if (isPartialResult && result->num_physcam_metadata) {
3096 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3097 " physical camera result", frameNumber);
3098 return;
3099 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003100 if (isPartialResult) {
3101 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003102 }
3103
Shuzhen Wang4a472662017-02-26 23:29:04 -08003104 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003105 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003106 sendPartialCaptureResult(result->result, request.resultExtras,
3107 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003108 }
3109 }
3110
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003111 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003112 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003113
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003114 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003115 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003116 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3117 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3118 request.physicalCameraIds.size(), result->num_physcam_metadata);
3119 return;
3120 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003121 if (request.haveResultMetadata) {
3122 SET_ERR("Called multiple times with metadata for frame %d",
3123 frameNumber);
3124 return;
3125 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003126 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3127 String8 physicalId(result->physcam_ids[i]);
3128 std::set<String8>::iterator cameraIdIter =
3129 request.physicalCameraIds.find(physicalId);
3130 if (cameraIdIter != request.physicalCameraIds.end()) {
3131 request.physicalCameraIds.erase(cameraIdIter);
3132 } else {
3133 SET_ERR("Total result for frame %d has already returned for camera %s",
3134 frameNumber, physicalId.c_str());
3135 return;
3136 }
3137 }
Zhijun He204e3292014-07-14 17:09:23 -07003138 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003139 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003140 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003141 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003142 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003143 request.haveResultMetadata = true;
3144 }
3145
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003146 uint32_t numBuffersReturned = result->num_output_buffers;
3147 if (result->input_buffer != NULL) {
3148 if (hasInputBufferInRequest) {
3149 numBuffersReturned += 1;
3150 } else {
3151 ALOGW("%s: Input buffer should be NULL if there is no input"
3152 " buffer sent in the request",
3153 __FUNCTION__);
3154 }
3155 }
3156 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003157 if (request.numBuffersLeft < 0) {
3158 SET_ERR("Too many buffers returned for frame %d",
3159 frameNumber);
3160 return;
3161 }
3162
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003163 camera_metadata_ro_entry_t entry;
3164 res = find_camera_metadata_ro_entry(result->result,
3165 ANDROID_SENSOR_TIMESTAMP, &entry);
3166 if (res == OK && entry.count == 1) {
3167 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003168 }
3169
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003170 // If shutter event isn't received yet, append the output buffers to
3171 // the in-flight request. Otherwise, return the output buffers to
3172 // streams.
3173 if (shutterTimestamp == 0) {
3174 request.pendingOutputBuffers.appendArray(result->output_buffers,
3175 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003176 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003177 returnOutputBuffers(result->output_buffers,
3178 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003179 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003180
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003181 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003182 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3183 CameraMetadata physicalMetadata;
3184 physicalMetadata.append(result->physcam_metadata[i]);
3185 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3186 physicalMetadata});
3187 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003188 if (shutterTimestamp == 0) {
3189 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003190 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003191 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003192 CameraMetadata metadata;
3193 metadata = result->result;
3194 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003195 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003196 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003197 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003198 }
3199
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003200 removeInFlightRequestIfReadyLocked(idx);
3201 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003202
Zhijun Hef0d962a2014-06-30 10:24:11 -07003203 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003204 if (hasInputBufferInRequest) {
3205 Camera3Stream *stream =
3206 Camera3Stream::cast(result->input_buffer->stream);
3207 res = stream->returnInputBuffer(*(result->input_buffer));
3208 // Note: stream may be deallocated at this point, if this buffer was the
3209 // last reference to it.
3210 if (res != OK) {
3211 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3212 " its stream:%s (%d)", __FUNCTION__,
3213 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003214 }
3215 } else {
3216 ALOGW("%s: Input buffer should be NULL if there is no input"
3217 " buffer sent in the request, skipping input buffer return.",
3218 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003219 }
3220 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003221}
3222
3223void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003224 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003225 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003226 {
3227 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003228 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003229 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003230
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003231 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003232 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003233 return;
3234 }
3235
3236 switch (msg->type) {
3237 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003238 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003239 break;
3240 }
3241 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003242 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003243 break;
3244 }
3245 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003246 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003247 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003248 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003249}
3250
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003251void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003252 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003253 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003254 // Map camera HAL error codes to ICameraDeviceCallback error codes
3255 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003256 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003257 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003258 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003259 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003260 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003261 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003262 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003263 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003264 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003265 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003266 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003267 };
3268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003269 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003270 ((msg.error_code >= 0) &&
3271 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3272 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003273 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003274
3275 int streamId = 0;
3276 if (msg.error_stream != NULL) {
3277 Camera3Stream *stream =
3278 Camera3Stream::cast(msg.error_stream);
3279 streamId = stream->getId();
3280 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003281 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3282 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003283 streamId, msg.error_code);
3284
3285 CaptureResultExtras resultExtras;
3286 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003287 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288 // SET_ERR calls notifyError
3289 SET_ERR("Camera HAL reported serious device error");
3290 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003291 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3292 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3293 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003294 {
3295 Mutex::Autolock l(mInFlightLock);
3296 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3297 if (idx >= 0) {
3298 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3299 r.requestStatus = msg.error_code;
3300 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003301 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3302 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3303 errorCode) {
3304 r.skipResultMetadata = true;
3305 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003306 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3307 errorCode) {
3308 // In case of missing result check whether the buffers
3309 // returned. If they returned, then remove inflight
3310 // request.
3311 removeInFlightRequestIfReadyLocked(idx);
3312 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003313 } else {
3314 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003315 ALOGE("Camera %s: %s: cannot find in-flight request on "
3316 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003317 resultExtras.frameNumber);
3318 }
3319 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003320 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003321 if (listener != NULL) {
3322 listener->notifyError(errorCode, resultExtras);
3323 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003324 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003325 }
3326 break;
3327 default:
3328 // SET_ERR calls notifyError
3329 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3330 break;
3331 }
3332}
3333
3334void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003335 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003336 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003337 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003338
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003339 // Set timestamp for the request in the in-flight tracking
3340 // and get the request ID to send upstream
3341 {
3342 Mutex::Autolock l(mInFlightLock);
3343 idx = mInFlightMap.indexOfKey(msg.frame_number);
3344 if (idx >= 0) {
3345 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003346
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003347 // Verify ordering of shutter notifications
3348 {
3349 Mutex::Autolock l(mOutputLock);
3350 // TODO: need to track errors for tighter bounds on expected frame number.
3351 if (r.hasInputBuffer) {
3352 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3353 SET_ERR("Shutter notification out-of-order. Expected "
3354 "notification for frame %d, got frame %d",
3355 mNextReprocessShutterFrameNumber, msg.frame_number);
3356 return;
3357 }
3358 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3359 } else {
3360 if (msg.frame_number < mNextShutterFrameNumber) {
3361 SET_ERR("Shutter notification out-of-order. Expected "
3362 "notification for frame %d, got frame %d",
3363 mNextShutterFrameNumber, msg.frame_number);
3364 return;
3365 }
3366 mNextShutterFrameNumber = msg.frame_number + 1;
3367 }
3368 }
3369
Shuzhen Wang4a472662017-02-26 23:29:04 -08003370 r.shutterTimestamp = msg.timestamp;
3371 if (r.hasCallback) {
3372 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003373 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003374 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003375 // Call listener, if any
3376 if (listener != NULL) {
3377 listener->notifyShutter(r.resultExtras, msg.timestamp);
3378 }
3379 // send pending result and buffers
3380 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3381 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003382 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003383 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003384 returnOutputBuffers(r.pendingOutputBuffers.array(),
3385 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3386 r.pendingOutputBuffers.clear();
3387
3388 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003389 }
3390 }
3391 if (idx < 0) {
3392 SET_ERR("Shutter notification for non-existent frame number %d",
3393 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003394 }
3395}
3396
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003397CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003398 ALOGV("%s", __FUNCTION__);
3399
Igor Murashkin1e479c02013-09-06 16:55:14 -07003400 CameraMetadata retVal;
3401
3402 if (mRequestThread != NULL) {
3403 retVal = mRequestThread->getLatestRequest();
3404 }
3405
Igor Murashkin1e479c02013-09-06 16:55:14 -07003406 return retVal;
3407}
3408
Jianing Weicb0652e2014-03-12 18:29:36 -07003409
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003410void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3411 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3412 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3413}
3414
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003415/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003416 * HalInterface inner class methods
3417 */
3418
Yifan Hongf79b5542017-04-11 14:44:25 -07003419Camera3Device::HalInterface::HalInterface(
3420 sp<ICameraDeviceSession> &session,
3421 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003422 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003423 mRequestMetadataQueue(queue) {
3424 // Check with hardware service manager if we can downcast these interfaces
3425 // Somewhat expensive, so cache the results at startup
3426 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3427 if (castResult_3_4.isOk()) {
3428 mHidlSession_3_4 = castResult_3_4;
3429 }
3430 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3431 if (castResult_3_3.isOk()) {
3432 mHidlSession_3_3 = castResult_3_3;
3433 }
3434}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003435
Emilian Peev31abd0a2017-05-11 18:37:46 +01003436Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003437
3438Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003439 mHidlSession(other.mHidlSession),
3440 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003441
3442bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003443 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003444}
3445
3446void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003447 mHidlSession_3_4.clear();
3448 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003449 mHidlSession.clear();
3450}
3451
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003452bool Camera3Device::HalInterface::supportBatchRequest() {
3453 return mHidlSession != nullptr;
3454}
3455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003456status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3457 camera3_request_template_t templateId,
3458 /*out*/ camera_metadata_t **requestTemplate) {
3459 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3460 if (!valid()) return INVALID_OPERATION;
3461 status_t res = OK;
3462
Emilian Peev31abd0a2017-05-11 18:37:46 +01003463 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003464
3465 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003466 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003467 status = s;
3468 if (status == common::V1_0::Status::OK) {
3469 const camera_metadata *r =
3470 reinterpret_cast<const camera_metadata_t*>(request.data());
3471 size_t expectedSize = request.size();
3472 int ret = validate_camera_metadata_structure(r, &expectedSize);
3473 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3474 *requestTemplate = clone_camera_metadata(r);
3475 if (*requestTemplate == nullptr) {
3476 ALOGE("%s: Unable to clone camera metadata received from HAL",
3477 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003479 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003480 } else {
3481 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3482 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003484 }
3485 };
3486 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003487 RequestTemplate id;
3488 switch (templateId) {
3489 case CAMERA3_TEMPLATE_PREVIEW:
3490 id = RequestTemplate::PREVIEW;
3491 break;
3492 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3493 id = RequestTemplate::STILL_CAPTURE;
3494 break;
3495 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3496 id = RequestTemplate::VIDEO_RECORD;
3497 break;
3498 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3499 id = RequestTemplate::VIDEO_SNAPSHOT;
3500 break;
3501 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3502 id = RequestTemplate::ZERO_SHUTTER_LAG;
3503 break;
3504 case CAMERA3_TEMPLATE_MANUAL:
3505 id = RequestTemplate::MANUAL;
3506 break;
3507 default:
3508 // Unknown template ID, or this HAL is too old to support it
3509 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003510 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003511 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003512
Emilian Peev31abd0a2017-05-11 18:37:46 +01003513 if (!err.isOk()) {
3514 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3515 res = DEAD_OBJECT;
3516 } else {
3517 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003518 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003520 return res;
3521}
3522
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003523status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003524 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003525 ATRACE_NAME("CameraHal::configureStreams");
3526 if (!valid()) return INVALID_OPERATION;
3527 status_t res = OK;
3528
Emilian Peev31abd0a2017-05-11 18:37:46 +01003529 // Convert stream config to HIDL
3530 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003531 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3532 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3533 requestedConfiguration3_2.streams.resize(config->num_streams);
3534 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003535 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003536 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3537 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003539
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3541 cam3stream->setBufferFreedListener(this);
3542 int streamId = cam3stream->getId();
3543 StreamType streamType;
3544 switch (src->stream_type) {
3545 case CAMERA3_STREAM_OUTPUT:
3546 streamType = StreamType::OUTPUT;
3547 break;
3548 case CAMERA3_STREAM_INPUT:
3549 streamType = StreamType::INPUT;
3550 break;
3551 default:
3552 ALOGE("%s: Stream %d: Unsupported stream type %d",
3553 __FUNCTION__, streamId, config->streams[i]->stream_type);
3554 return BAD_VALUE;
3555 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003556 dst3_2.id = streamId;
3557 dst3_2.streamType = streamType;
3558 dst3_2.width = src->width;
3559 dst3_2.height = src->height;
3560 dst3_2.format = mapToPixelFormat(src->format);
3561 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3562 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3563 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3564 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003565 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003566 if (src->physical_camera_id != nullptr) {
3567 dst3_4.physicalCameraId = src->physical_camera_id;
3568 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003569
3570 activeStreams.insert(streamId);
3571 // Create Buffer ID map if necessary
3572 if (mBufferIdMaps.count(streamId) == 0) {
3573 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3574 }
3575 }
3576 // remove BufferIdMap for deleted streams
3577 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3578 int streamId = it->first;
3579 bool active = activeStreams.count(streamId) > 0;
3580 if (!active) {
3581 it = mBufferIdMaps.erase(it);
3582 } else {
3583 ++it;
3584 }
3585 }
3586
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003587 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003588 res = mapToStreamConfigurationMode(
3589 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003590 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003591 if (res != OK) {
3592 return res;
3593 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003594 requestedConfiguration3_2.operationMode = operationMode;
3595 requestedConfiguration3_4.operationMode = operationMode;
3596 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003597 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3598 get_camera_metadata_size(sessionParams));
3599
Emilian Peev31abd0a2017-05-11 18:37:46 +01003600 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003601 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003602 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003603
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003604 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003605 if (mHidlSession_3_4 != nullptr) {
3606 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003607 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003608 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003609 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003610 [&status, &finalConfiguration3_4]
3611 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3612 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003613 status = s;
3614 });
3615 if (!err.isOk()) {
3616 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3617 return DEAD_OBJECT;
3618 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003619 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3620 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3621 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3622 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003623 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003624 // We do; use v3.3 for the call
3625 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003626 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003627 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003628 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003629 finalConfiguration = halConfiguration;
3630 status = s;
3631 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003632 if (!err.isOk()) {
3633 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3634 return DEAD_OBJECT;
3635 }
3636 } else {
3637 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3638 ALOGV("%s: v3.2 device found", __FUNCTION__);
3639 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003640 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003641 [&status, &finalConfiguration_3_2]
3642 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3643 finalConfiguration_3_2 = halConfiguration;
3644 status = s;
3645 });
3646 if (!err.isOk()) {
3647 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3648 return DEAD_OBJECT;
3649 }
3650 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3651 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3652 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3653 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003654 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003655 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003656 }
3657
3658 if (status != common::V1_0::Status::OK ) {
3659 return CameraProviderManager::mapToStatusT(status);
3660 }
3661
3662 // And convert output stream configuration from HIDL
3663
3664 for (size_t i = 0; i < config->num_streams; i++) {
3665 camera3_stream_t *dst = config->streams[i];
3666 int streamId = Camera3Stream::cast(dst)->getId();
3667
3668 // Start scan at i, with the assumption that the stream order matches
3669 size_t realIdx = i;
3670 bool found = false;
3671 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003672 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003673 found = true;
3674 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003675 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003676 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3677 }
3678 if (!found) {
3679 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3680 __FUNCTION__, streamId);
3681 return INVALID_OPERATION;
3682 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003683 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003684
Emilian Peev710c1422017-08-30 11:19:38 +01003685 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3686 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003687 dstStream->setDataSpaceOverride(false);
3688 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3689 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3690
Emilian Peev31abd0a2017-05-11 18:37:46 +01003691 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3692 if (dst->format != overrideFormat) {
3693 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3694 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003695 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003696 if (dst->data_space != overrideDataSpace) {
3697 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3698 streamId, dst->format);
3699 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003700 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003701 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003702 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3703
Emilian Peev31abd0a2017-05-11 18:37:46 +01003704 // Override allowed with IMPLEMENTATION_DEFINED
3705 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003706 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003707 }
3708
Emilian Peev31abd0a2017-05-11 18:37:46 +01003709 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003710 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003711 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003712 __FUNCTION__, streamId);
3713 return INVALID_OPERATION;
3714 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003715 dstStream->setUsage(
3716 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003717 } else {
3718 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003719 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003720 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3721 __FUNCTION__, streamId);
3722 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003723 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003724 dstStream->setUsage(
3725 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003726 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003727 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003728 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003729
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003730 return res;
3731}
3732
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003733void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3734 /*out*/device::V3_2::CaptureRequest* captureRequest,
3735 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003736 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003737 if (captureRequest == nullptr || handlesCreated == nullptr) {
3738 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3739 __FUNCTION__, captureRequest, handlesCreated);
3740 return;
3741 }
3742
3743 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003744
3745 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003746
3747 {
3748 std::lock_guard<std::mutex> lock(mInflightLock);
3749 if (request->input_buffer != nullptr) {
3750 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3751 buffer_handle_t buf = *(request->input_buffer->buffer);
3752 auto pair = getBufferId(buf, streamId);
3753 bool isNewBuffer = pair.first;
3754 uint64_t bufferId = pair.second;
3755 captureRequest->inputBuffer.streamId = streamId;
3756 captureRequest->inputBuffer.bufferId = bufferId;
3757 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3758 captureRequest->inputBuffer.status = BufferStatus::OK;
3759 native_handle_t *acquireFence = nullptr;
3760 if (request->input_buffer->acquire_fence != -1) {
3761 acquireFence = native_handle_create(1,0);
3762 acquireFence->data[0] = request->input_buffer->acquire_fence;
3763 handlesCreated->push_back(acquireFence);
3764 }
3765 captureRequest->inputBuffer.acquireFence = acquireFence;
3766 captureRequest->inputBuffer.releaseFence = nullptr;
3767
3768 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3769 request->input_buffer->buffer,
3770 request->input_buffer->acquire_fence);
3771 } else {
3772 captureRequest->inputBuffer.streamId = -1;
3773 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3774 }
3775
3776 captureRequest->outputBuffers.resize(request->num_output_buffers);
3777 for (size_t i = 0; i < request->num_output_buffers; i++) {
3778 const camera3_stream_buffer_t *src = request->output_buffers + i;
3779 StreamBuffer &dst = captureRequest->outputBuffers[i];
3780 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3781 buffer_handle_t buf = *(src->buffer);
3782 auto pair = getBufferId(buf, streamId);
3783 bool isNewBuffer = pair.first;
3784 dst.streamId = streamId;
3785 dst.bufferId = pair.second;
3786 dst.buffer = isNewBuffer ? buf : nullptr;
3787 dst.status = BufferStatus::OK;
3788 native_handle_t *acquireFence = nullptr;
3789 if (src->acquire_fence != -1) {
3790 acquireFence = native_handle_create(1,0);
3791 acquireFence->data[0] = src->acquire_fence;
3792 handlesCreated->push_back(acquireFence);
3793 }
3794 dst.acquireFence = acquireFence;
3795 dst.releaseFence = nullptr;
3796
3797 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3798 src->buffer, src->acquire_fence);
3799 }
3800 }
3801}
3802
3803status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3804 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3805 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3806 if (!valid()) return INVALID_OPERATION;
3807
Emilian Peevaebbe412018-01-15 13:53:24 +00003808 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3809 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3810 if (castResult_3_4.isOk()) {
3811 hidlSession_3_4 = castResult_3_4;
3812 }
3813
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003814 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003815 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003817 if (hidlSession_3_4 != nullptr) {
3818 captureRequests_3_4.resize(batchSize);
3819 } else {
3820 captureRequests.resize(batchSize);
3821 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003822 std::vector<native_handle_t*> handlesCreated;
3823
3824 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003825 if (hidlSession_3_4 != nullptr) {
3826 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3827 /*out*/&handlesCreated);
3828 } else {
3829 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3830 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003831 }
3832
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003833 std::vector<device::V3_2::BufferCache> cachesToRemove;
3834 {
3835 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3836 for (auto& pair : mFreedBuffers) {
3837 // The stream might have been removed since onBufferFreed
3838 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3839 cachesToRemove.push_back({pair.first, pair.second});
3840 }
3841 }
3842 mFreedBuffers.clear();
3843 }
3844
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003845 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3846 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003847
3848 // Write metadata to FMQ.
3849 for (size_t i = 0; i < batchSize; i++) {
3850 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 device::V3_2::CaptureRequest* captureRequest;
3852 if (hidlSession_3_4 != nullptr) {
3853 captureRequest = &captureRequests_3_4[i].v3_2;
3854 } else {
3855 captureRequest = &captureRequests[i];
3856 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003857
3858 if (request->settings != nullptr) {
3859 size_t settingsSize = get_camera_metadata_size(request->settings);
3860 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3861 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3862 captureRequest->settings.resize(0);
3863 captureRequest->fmqSettingsSize = settingsSize;
3864 } else {
3865 if (mRequestMetadataQueue != nullptr) {
3866 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3867 }
3868 captureRequest->settings.setToExternal(
3869 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3870 get_camera_metadata_size(request->settings));
3871 captureRequest->fmqSettingsSize = 0u;
3872 }
3873 } else {
3874 // A null request settings maps to a size-0 CameraMetadata
3875 captureRequest->settings.resize(0);
3876 captureRequest->fmqSettingsSize = 0u;
3877 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003878
3879 if (hidlSession_3_4 != nullptr) {
3880 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3881 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003882 if (request->physcam_settings != nullptr) {
3883 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3884 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3885 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3886 settingsSize)) {
3887 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3888 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3889 settingsSize;
3890 } else {
3891 if (mRequestMetadataQueue != nullptr) {
3892 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3893 }
3894 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3895 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3896 request->physcam_settings[j])),
3897 get_camera_metadata_size(request->physcam_settings[j]));
3898 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003899 }
Emilian Peev00420d22018-02-05 21:33:13 +00003900 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003901 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003902 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003903 }
3904 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3905 request->physcam_id[j];
3906 }
3907 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003908 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003909
3910 hardware::details::return_status err;
3911 if (hidlSession_3_4 != nullptr) {
3912 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003913 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3914 status = s;
3915 *numRequestProcessed = n;
3916 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003917 } else {
3918 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3919 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3920 status = s;
3921 *numRequestProcessed = n;
3922 });
3923 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003924 if (!err.isOk()) {
3925 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3926 return DEAD_OBJECT;
3927 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003928 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3929 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3930 __FUNCTION__, *numRequestProcessed, batchSize);
3931 status = common::V1_0::Status::INTERNAL_ERROR;
3932 }
3933
3934 for (auto& handle : handlesCreated) {
3935 native_handle_delete(handle);
3936 }
3937 return CameraProviderManager::mapToStatusT(status);
3938}
3939
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003940status_t Camera3Device::HalInterface::processCaptureRequest(
3941 camera3_capture_request_t *request) {
3942 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003943 if (!valid()) return INVALID_OPERATION;
3944 status_t res = OK;
3945
Emilian Peev31abd0a2017-05-11 18:37:46 +01003946 uint32_t numRequestProcessed = 0;
3947 std::vector<camera3_capture_request_t*> requests(1);
3948 requests[0] = request;
3949 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3950
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003951 return res;
3952}
3953
3954status_t Camera3Device::HalInterface::flush() {
3955 ATRACE_NAME("CameraHal::flush");
3956 if (!valid()) return INVALID_OPERATION;
3957 status_t res = OK;
3958
Emilian Peev31abd0a2017-05-11 18:37:46 +01003959 auto err = mHidlSession->flush();
3960 if (!err.isOk()) {
3961 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3962 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003963 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003964 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003965 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003966
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003967 return res;
3968}
3969
Emilian Peev31abd0a2017-05-11 18:37:46 +01003970status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003971 ATRACE_NAME("CameraHal::dump");
3972 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003973
Emilian Peev31abd0a2017-05-11 18:37:46 +01003974 // Handled by CameraProviderManager::dump
3975
3976 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977}
3978
3979status_t Camera3Device::HalInterface::close() {
3980 ATRACE_NAME("CameraHal::close()");
3981 if (!valid()) return INVALID_OPERATION;
3982 status_t res = OK;
3983
Emilian Peev31abd0a2017-05-11 18:37:46 +01003984 auto err = mHidlSession->close();
3985 // Interface will be dead shortly anyway, so don't log errors
3986 if (!err.isOk()) {
3987 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003988 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003990 return res;
3991}
3992
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003993void Camera3Device::HalInterface::getInflightBufferKeys(
3994 std::vector<std::pair<int32_t, int32_t>>* out) {
3995 std::lock_guard<std::mutex> lock(mInflightLock);
3996 out->clear();
3997 out->reserve(mInflightBufferMap.size());
3998 for (auto& pair : mInflightBufferMap) {
3999 uint64_t key = pair.first;
4000 int32_t streamId = key & 0xFFFFFFFF;
4001 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4002 out->push_back(std::make_pair(frameNumber, streamId));
4003 }
4004 return;
4005}
4006
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004007status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004008 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004009 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004010 auto pair = std::make_pair(buffer, acquireFence);
4011 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012 return OK;
4013}
4014
4015status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004016 int32_t frameNumber, int32_t streamId,
4017 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004018 std::lock_guard<std::mutex> lock(mInflightLock);
4019
4020 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4021 auto it = mInflightBufferMap.find(key);
4022 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004023 auto pair = it->second;
4024 *buffer = pair.first;
4025 int acquireFence = pair.second;
4026 if (acquireFence > 0) {
4027 ::close(acquireFence);
4028 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004029 mInflightBufferMap.erase(it);
4030 return OK;
4031}
4032
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004033std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4034 const buffer_handle_t& buf, int streamId) {
4035 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4036
4037 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4038 auto it = bIdMap.find(buf);
4039 if (it == bIdMap.end()) {
4040 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004041 ALOGV("stream %d now have %zu buffer caches, buf %p",
4042 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004043 return std::make_pair(true, mNextBufferId - 1);
4044 } else {
4045 return std::make_pair(false, it->second);
4046 }
4047}
4048
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004049void Camera3Device::HalInterface::onBufferFreed(
4050 int streamId, const native_handle_t* handle) {
4051 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4052 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4053 auto mapIt = mBufferIdMaps.find(streamId);
4054 if (mapIt == mBufferIdMaps.end()) {
4055 // streamId might be from a deleted stream here
4056 ALOGI("%s: stream %d has been removed",
4057 __FUNCTION__, streamId);
4058 return;
4059 }
4060 BufferIdMap& bIdMap = mapIt->second;
4061 auto it = bIdMap.find(handle);
4062 if (it == bIdMap.end()) {
4063 ALOGW("%s: cannot find buffer %p in stream %d",
4064 __FUNCTION__, handle, streamId);
4065 return;
4066 } else {
4067 bufferId = it->second;
4068 bIdMap.erase(it);
4069 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4070 __FUNCTION__, streamId, bIdMap.size(), handle);
4071 }
4072 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4073}
4074
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004075/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004076 * RequestThread inner class methods
4077 */
4078
4079Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004080 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004081 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004082 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004083 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004084 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004085 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004086 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004087 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004088 mReconfigured(false),
4089 mDoPause(false),
4090 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004091 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004092 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004093 mCurrentAfTriggerId(0),
4094 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004095 mRepeatingLastFrameNumber(
4096 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004097 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004098 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004099 mRequestLatency(kRequestLatencyBinSize),
4100 mSessionParamKeys(sessionParamKeys),
4101 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004102 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004103}
4104
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004105Camera3Device::RequestThread::~RequestThread() {}
4106
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004107void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004108 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004109 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004110 Mutex::Autolock l(mRequestLock);
4111 mListener = listener;
4112}
4113
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004114void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4115 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004116 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004117 Mutex::Autolock l(mRequestLock);
4118 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004119 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004120 // Prepare video stream for high speed recording.
4121 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004122 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004123}
4124
Jianing Wei90e59c92014-03-12 18:29:36 -07004125status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004126 List<sp<CaptureRequest> > &requests,
4127 /*out*/
4128 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004129 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004130 Mutex::Autolock l(mRequestLock);
4131 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4132 ++it) {
4133 mRequestQueue.push_back(*it);
4134 }
4135
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004136 if (lastFrameNumber != NULL) {
4137 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4138 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4139 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4140 *lastFrameNumber);
4141 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004142
Jianing Wei90e59c92014-03-12 18:29:36 -07004143 unpauseForNewRequests();
4144
4145 return OK;
4146}
4147
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004148
4149status_t Camera3Device::RequestThread::queueTrigger(
4150 RequestTrigger trigger[],
4151 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004152 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004153 Mutex::Autolock l(mTriggerMutex);
4154 status_t ret;
4155
4156 for (size_t i = 0; i < count; ++i) {
4157 ret = queueTriggerLocked(trigger[i]);
4158
4159 if (ret != OK) {
4160 return ret;
4161 }
4162 }
4163
4164 return OK;
4165}
4166
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004167const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4168 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004169 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004170 if (d != nullptr) return d->mId;
4171 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004172}
4173
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004174status_t Camera3Device::RequestThread::queueTriggerLocked(
4175 RequestTrigger trigger) {
4176
4177 uint32_t tag = trigger.metadataTag;
4178 ssize_t index = mTriggerMap.indexOfKey(tag);
4179
4180 switch (trigger.getTagType()) {
4181 case TYPE_BYTE:
4182 // fall-through
4183 case TYPE_INT32:
4184 break;
4185 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004186 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4187 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004188 return INVALID_OPERATION;
4189 }
4190
4191 /**
4192 * Collect only the latest trigger, since we only have 1 field
4193 * in the request settings per trigger tag, and can't send more than 1
4194 * trigger per request.
4195 */
4196 if (index != NAME_NOT_FOUND) {
4197 mTriggerMap.editValueAt(index) = trigger;
4198 } else {
4199 mTriggerMap.add(tag, trigger);
4200 }
4201
4202 return OK;
4203}
4204
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004206 const RequestList &requests,
4207 /*out*/
4208 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004209 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004210 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004211 if (lastFrameNumber != NULL) {
4212 *lastFrameNumber = mRepeatingLastFrameNumber;
4213 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 mRepeatingRequests.clear();
4215 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4216 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004217
4218 unpauseForNewRequests();
4219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004220 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004221 return OK;
4222}
4223
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004224bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004225 if (mRepeatingRequests.empty()) {
4226 return false;
4227 }
4228 int32_t requestId = requestIn->mResultExtras.requestId;
4229 const RequestList &repeatRequests = mRepeatingRequests;
4230 // All repeating requests are guaranteed to have same id so only check first quest
4231 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4232 return (firstRequest->mResultExtras.requestId == requestId);
4233}
4234
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004235status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004236 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004237 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004238 return clearRepeatingRequestsLocked(lastFrameNumber);
4239
4240}
4241
4242status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004244 if (lastFrameNumber != NULL) {
4245 *lastFrameNumber = mRepeatingLastFrameNumber;
4246 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004247 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248 return OK;
4249}
4250
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004251status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004252 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004253 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004254 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004255 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004256
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004257 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004258
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004259 // Send errors for all requests pending in the request queue, including
4260 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004261 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004262 if (listener != NULL) {
4263 for (RequestList::iterator it = mRequestQueue.begin();
4264 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004265 // Abort the input buffers for reprocess requests.
4266 if ((*it)->mInputStream != NULL) {
4267 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004268 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4269 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004270 if (res != OK) {
4271 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4272 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4273 } else {
4274 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4275 if (res != OK) {
4276 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4277 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4278 }
4279 }
4280 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004281 // Set the frame number this request would have had, if it
4282 // had been submitted; this frame number will not be reused.
4283 // The requestId and burstId fields were set when the request was
4284 // submitted originally (in convertMetadataListToRequestListLocked)
4285 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004286 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004287 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004288 }
4289 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004290 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004291
4292 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004293 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004294 if (lastFrameNumber != NULL) {
4295 *lastFrameNumber = mRepeatingLastFrameNumber;
4296 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004297 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004298 return OK;
4299}
4300
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004301status_t Camera3Device::RequestThread::flush() {
4302 ATRACE_CALL();
4303 Mutex::Autolock l(mFlushLock);
4304
Emilian Peev08dd2452017-04-06 16:55:14 +01004305 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004306}
4307
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004308void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004309 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 Mutex::Autolock l(mPauseLock);
4311 mDoPause = paused;
4312 mDoPauseSignal.signal();
4313}
4314
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004315status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4316 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004317 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004318 Mutex::Autolock l(mLatestRequestMutex);
4319 status_t res;
4320 while (mLatestRequestId != requestId) {
4321 nsecs_t startTime = systemTime();
4322
4323 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4324 if (res != OK) return res;
4325
4326 timeout -= (systemTime() - startTime);
4327 }
4328
4329 return OK;
4330}
4331
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004332void Camera3Device::RequestThread::requestExit() {
4333 // Call parent to set up shutdown
4334 Thread::requestExit();
4335 // The exit from any possible waits
4336 mDoPauseSignal.signal();
4337 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004338
4339 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4340 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004341}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004342
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004343void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004344 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004345 bool surfaceAbandoned = false;
4346 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004347 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004348 {
4349 Mutex::Autolock l(mRequestLock);
4350 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4351 // repeating requests.
4352 for (const auto& request : mRepeatingRequests) {
4353 for (const auto& s : request->mOutputStreams) {
4354 if (s->isAbandoned()) {
4355 surfaceAbandoned = true;
4356 clearRepeatingRequestsLocked(&lastFrameNumber);
4357 break;
4358 }
4359 }
4360 if (surfaceAbandoned) {
4361 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004362 }
4363 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004364 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004365 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004366
4367 if (listener != NULL && surfaceAbandoned) {
4368 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004369 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004370}
4371
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004372bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004373 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004374 status_t res;
4375 size_t batchSize = mNextRequests.size();
4376 std::vector<camera3_capture_request_t*> requests(batchSize);
4377 uint32_t numRequestProcessed = 0;
4378 for (size_t i = 0; i < batchSize; i++) {
4379 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004380 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004381 }
4382
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004383 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4384
4385 bool triggerRemoveFailed = false;
4386 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4387 for (size_t i = 0; i < numRequestProcessed; i++) {
4388 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4389 nextRequest.submitted = true;
4390
4391
4392 // Update the latest request sent to HAL
4393 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4394 Mutex::Autolock al(mLatestRequestMutex);
4395
4396 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4397 mLatestRequest.acquire(cloned);
4398
4399 sp<Camera3Device> parent = mParent.promote();
4400 if (parent != NULL) {
4401 parent->monitorMetadata(TagMonitor::REQUEST,
4402 nextRequest.halRequest.frame_number,
4403 0, mLatestRequest);
4404 }
4405 }
4406
4407 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004408 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4409 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004410 }
4411
Emilian Peevaebbe412018-01-15 13:53:24 +00004412 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4413
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004414 if (!triggerRemoveFailed) {
4415 // Remove any previously queued triggers (after unlock)
4416 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4417 if (removeTriggerRes != OK) {
4418 triggerRemoveFailed = true;
4419 triggerFailedRequest = nextRequest;
4420 }
4421 }
4422 }
4423
4424 if (triggerRemoveFailed) {
4425 SET_ERR("RequestThread: Unable to remove triggers "
4426 "(capture request %d, HAL device: %s (%d)",
4427 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4428 cleanUpFailedRequests(/*sendRequestError*/ false);
4429 return false;
4430 }
4431
4432 if (res != OK) {
4433 // Should only get a failure here for malformed requests or device-level
4434 // errors, so consider all errors fatal. Bad metadata failures should
4435 // come through notify.
4436 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4437 mNextRequests[numRequestProcessed].halRequest.frame_number,
4438 strerror(-res), res);
4439 cleanUpFailedRequests(/*sendRequestError*/ false);
4440 return false;
4441 }
4442 return true;
4443}
4444
4445bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4446 status_t res;
4447
4448 for (auto& nextRequest : mNextRequests) {
4449 // Submit request and block until ready for next one
4450 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4451 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4452
4453 if (res != OK) {
4454 // Should only get a failure here for malformed requests or device-level
4455 // errors, so consider all errors fatal. Bad metadata failures should
4456 // come through notify.
4457 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4458 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4459 res);
4460 cleanUpFailedRequests(/*sendRequestError*/ false);
4461 return false;
4462 }
4463
4464 // Mark that the request has be submitted successfully.
4465 nextRequest.submitted = true;
4466
4467 // Update the latest request sent to HAL
4468 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4469 Mutex::Autolock al(mLatestRequestMutex);
4470
4471 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4472 mLatestRequest.acquire(cloned);
4473
4474 sp<Camera3Device> parent = mParent.promote();
4475 if (parent != NULL) {
4476 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4477 0, mLatestRequest);
4478 }
4479 }
4480
4481 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004482 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4483 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004484 }
4485
Emilian Peevaebbe412018-01-15 13:53:24 +00004486 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004488 // Remove any previously queued triggers (after unlock)
4489 res = removeTriggers(mPrevRequest);
4490 if (res != OK) {
4491 SET_ERR("RequestThread: Unable to remove triggers "
4492 "(capture request %d, HAL device: %s (%d)",
4493 nextRequest.halRequest.frame_number, strerror(-res), res);
4494 cleanUpFailedRequests(/*sendRequestError*/ false);
4495 return false;
4496 }
4497 }
4498 return true;
4499}
4500
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004501nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4502 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4503 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4504 find_camera_metadata_ro_entry(request,
4505 ANDROID_CONTROL_AE_MODE,
4506 &e);
4507 if (e.count == 0) return maxExpectedDuration;
4508
4509 switch (e.data.u8[0]) {
4510 case ANDROID_CONTROL_AE_MODE_OFF:
4511 find_camera_metadata_ro_entry(request,
4512 ANDROID_SENSOR_EXPOSURE_TIME,
4513 &e);
4514 if (e.count > 0) {
4515 maxExpectedDuration = e.data.i64[0];
4516 }
4517 find_camera_metadata_ro_entry(request,
4518 ANDROID_SENSOR_FRAME_DURATION,
4519 &e);
4520 if (e.count > 0) {
4521 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4522 }
4523 break;
4524 default:
4525 find_camera_metadata_ro_entry(request,
4526 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4527 &e);
4528 if (e.count > 1) {
4529 maxExpectedDuration = 1e9 / e.data.u8[0];
4530 }
4531 break;
4532 }
4533
4534 return maxExpectedDuration;
4535}
4536
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004537bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4538 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4539 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4540 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4541 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4542 return true;
4543 }
4544
4545 return false;
4546}
4547
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004548bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4549 ATRACE_CALL();
4550 bool updatesDetected = false;
4551
4552 for (auto tag : mSessionParamKeys) {
4553 camera_metadata_ro_entry entry = settings.find(tag);
4554 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4555
4556 if (entry.count > 0) {
4557 bool isDifferent = false;
4558 if (lastEntry.count > 0) {
4559 // Have a last value, compare to see if changed
4560 if (lastEntry.type == entry.type &&
4561 lastEntry.count == entry.count) {
4562 // Same type and count, compare values
4563 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4564 size_t entryBytes = bytesPerValue * lastEntry.count;
4565 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4566 if (cmp != 0) {
4567 isDifferent = true;
4568 }
4569 } else {
4570 // Count or type has changed
4571 isDifferent = true;
4572 }
4573 } else {
4574 // No last entry, so always consider to be different
4575 isDifferent = true;
4576 }
4577
4578 if (isDifferent) {
4579 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004580 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4581 updatesDetected = true;
4582 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004583 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004584 }
4585 } else if (lastEntry.count > 0) {
4586 // Value has been removed
4587 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4588 mLatestSessionParams.erase(tag);
4589 updatesDetected = true;
4590 }
4591 }
4592
4593 return updatesDetected;
4594}
4595
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004596bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004597 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004598 status_t res;
4599
4600 // Handle paused state.
4601 if (waitIfPaused()) {
4602 return true;
4603 }
4604
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004605 // Wait for the next batch of requests.
4606 waitForNextRequestBatch();
4607 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004608 return true;
4609 }
4610
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004611 // Get the latest request ID, if any
4612 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004613 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004614 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004615 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004616 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004617 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004618 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4619 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004620 }
4621
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004622 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4623 // or a single request from streaming or burst. In either case the first element
4624 // should contain the latest camera settings that we need to check for any session
4625 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004626 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004627 res = OK;
4628
4629 //Input stream buffers are already acquired at this point so an input stream
4630 //will not be able to move to idle state unless we force it.
4631 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4632 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4633 if (res != OK) {
4634 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4635 cleanUpFailedRequests(/*sendRequestError*/ false);
4636 return false;
4637 }
4638 }
4639
4640 if (res == OK) {
4641 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4642 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004643 sp<Camera3Device> parent = mParent.promote();
4644 if (parent != nullptr) {
4645 parent->pauseStateNotify(true);
4646 }
4647
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004648 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4649
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004650 if (parent != nullptr) {
4651 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4652 }
4653
4654 statusTracker->markComponentActive(mStatusId);
4655 setPaused(false);
4656 }
4657
4658 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4659 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4660 if (res != OK) {
4661 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4662 cleanUpFailedRequests(/*sendRequestError*/ false);
4663 return false;
4664 }
4665 }
4666 }
4667 }
4668
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004669 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004670 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004671 if (res == TIMED_OUT) {
4672 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004673 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004674 // Check if any stream is abandoned.
4675 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004676 return true;
4677 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004678 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004679 return false;
4680 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004681
Zhijun Hecc27e112013-10-03 16:12:43 -07004682 // Inform waitUntilRequestProcessed thread of a new request ID
4683 {
4684 Mutex::Autolock al(mLatestRequestMutex);
4685
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004686 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004687 mLatestRequestSignal.signal();
4688 }
4689
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004690 // Submit a batch of requests to HAL.
4691 // Use flush lock only when submitting multilple requests in a batch.
4692 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4693 // which may take a long time to finish so synchronizing flush() and
4694 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4695 // For now, only synchronize for high speed recording and we should figure something out for
4696 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004697 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004698
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004699 if (useFlushLock) {
4700 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004701 }
4702
Zhijun Hef0645c12016-08-02 00:58:11 -07004703 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004704 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004705
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004706 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004707 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004708 if (mInterface->supportBatchRequest()) {
4709 submitRequestSuccess = sendRequestsBatch();
4710 } else {
4711 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004712 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004713 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4714 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004715
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004716 if (useFlushLock) {
4717 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004718 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004719
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004720 // Unset as current request
4721 {
4722 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004723 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004724 }
4725
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004726 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004727}
4728
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004729status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004730 ATRACE_CALL();
4731
Shuzhen Wang4a472662017-02-26 23:29:04 -08004732 for (size_t i = 0; i < mNextRequests.size(); i++) {
4733 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4735 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4736 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4737
4738 // Prepare a request to HAL
4739 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4740
4741 // Insert any queued triggers (before metadata is locked)
4742 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004743 if (res < 0) {
4744 SET_ERR("RequestThread: Unable to insert triggers "
4745 "(capture request %d, HAL device: %s (%d)",
4746 halRequest->frame_number, strerror(-res), res);
4747 return INVALID_OPERATION;
4748 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004749
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004750 int triggerCount = res;
4751 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4752 mPrevTriggers = triggerCount;
4753
4754 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004755 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4756 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004757 /**
4758 * HAL workaround:
4759 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4760 */
4761 res = addDummyTriggerIds(captureRequest);
4762 if (res != OK) {
4763 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4764 "(capture request %d, HAL device: %s (%d)",
4765 halRequest->frame_number, strerror(-res), res);
4766 return INVALID_OPERATION;
4767 }
4768
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004769 {
4770 // Correct metadata regions for distortion correction if enabled
4771 sp<Camera3Device> parent = mParent.promote();
4772 if (parent != nullptr) {
4773 res = parent->mDistortionMapper.correctCaptureRequest(
4774 &(captureRequest->mSettingsList.begin()->metadata));
4775 if (res != OK) {
4776 SET_ERR("RequestThread: Unable to correct capture requests "
4777 "for lens distortion for request %d: %s (%d)",
4778 halRequest->frame_number, strerror(-res), res);
4779 return INVALID_OPERATION;
4780 }
4781 }
4782 }
4783
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004784 /**
4785 * The request should be presorted so accesses in HAL
4786 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4787 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004788 captureRequest->mSettingsList.begin()->metadata.sort();
4789 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004790 mPrevRequest = captureRequest;
4791 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4792
4793 IF_ALOGV() {
4794 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4795 find_camera_metadata_ro_entry(
4796 halRequest->settings,
4797 ANDROID_CONTROL_AF_TRIGGER,
4798 &e
4799 );
4800 if (e.count > 0) {
4801 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4802 __FUNCTION__,
4803 halRequest->frame_number,
4804 e.data.u8[0]);
4805 }
4806 }
4807 } else {
4808 // leave request.settings NULL to indicate 'reuse latest given'
4809 ALOGVV("%s: Request settings are REUSED",
4810 __FUNCTION__);
4811 }
4812
Emilian Peevaebbe412018-01-15 13:53:24 +00004813 if (captureRequest->mSettingsList.size() > 1) {
4814 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4815 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004816 if (newRequest) {
4817 halRequest->physcam_settings =
4818 new const camera_metadata* [halRequest->num_physcam_settings];
4819 } else {
4820 halRequest->physcam_settings = nullptr;
4821 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004822 auto it = ++captureRequest->mSettingsList.begin();
4823 size_t i = 0;
4824 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4825 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004826 if (newRequest) {
4827 it->metadata.sort();
4828 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4829 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004830 }
4831 }
4832
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004833 uint32_t totalNumBuffers = 0;
4834
4835 // Fill in buffers
4836 if (captureRequest->mInputStream != NULL) {
4837 halRequest->input_buffer = &captureRequest->mInputBuffer;
4838 totalNumBuffers += 1;
4839 } else {
4840 halRequest->input_buffer = NULL;
4841 }
4842
4843 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4844 captureRequest->mOutputStreams.size());
4845 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004846 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004847 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4848 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004849
4850 // Prepare video buffers for high speed recording on the first video request.
4851 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4852 // Only try to prepare video stream on the first video request.
4853 mPrepareVideoStream = false;
4854
4855 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4856 while (res == NOT_ENOUGH_DATA) {
4857 res = outputStream->prepareNextBuffer();
4858 }
4859 if (res != OK) {
4860 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4861 __FUNCTION__, strerror(-res), res);
4862 outputStream->cancelPrepare();
4863 }
4864 }
4865
Shuzhen Wang4a472662017-02-26 23:29:04 -08004866 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4867 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004868 if (res != OK) {
4869 // Can't get output buffer from gralloc queue - this could be due to
4870 // abandoned queue or other consumer misbehavior, so not a fatal
4871 // error
4872 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4873 " %s (%d)", strerror(-res), res);
4874
4875 return TIMED_OUT;
4876 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004877
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004878 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4879
4880 if (!physicalCameraId.isEmpty()) {
4881 // Physical stream isn't supported for input request.
4882 if (halRequest->input_buffer) {
4883 CLOGE("Physical stream is not supported for input request");
4884 return INVALID_OPERATION;
4885 }
4886 requestedPhysicalCameras.insert(physicalCameraId);
4887 }
4888 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004889 }
4890 totalNumBuffers += halRequest->num_output_buffers;
4891
4892 // Log request in the in-flight queue
4893 sp<Camera3Device> parent = mParent.promote();
4894 if (parent == NULL) {
4895 // Should not happen, and nowhere to send errors to, so just log it
4896 CLOGE("RequestThread: Parent is gone");
4897 return INVALID_OPERATION;
4898 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004899
4900 // If this request list is for constrained high speed recording (not
4901 // preview), and the current request is not the last one in the batch,
4902 // do not send callback to the app.
4903 bool hasCallback = true;
4904 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4905 hasCallback = false;
4906 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 res = parent->registerInFlight(halRequest->frame_number,
4908 totalNumBuffers, captureRequest->mResultExtras,
4909 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004910 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004911 calculateMaxExpectedDuration(halRequest->settings),
4912 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004913 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4914 ", burstId = %" PRId32 ".",
4915 __FUNCTION__,
4916 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4917 captureRequest->mResultExtras.burstId);
4918 if (res != OK) {
4919 SET_ERR("RequestThread: Unable to register new in-flight request:"
4920 " %s (%d)", strerror(-res), res);
4921 return INVALID_OPERATION;
4922 }
4923 }
4924
4925 return OK;
4926}
4927
Igor Murashkin1e479c02013-09-06 16:55:14 -07004928CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004929 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004930 Mutex::Autolock al(mLatestRequestMutex);
4931
4932 ALOGV("RequestThread::%s", __FUNCTION__);
4933
4934 return mLatestRequest;
4935}
4936
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004937bool Camera3Device::RequestThread::isStreamPending(
4938 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004939 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004940 Mutex::Autolock l(mRequestLock);
4941
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004942 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004943 if (!nextRequest.submitted) {
4944 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4945 if (stream == s) return true;
4946 }
4947 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004948 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004949 }
4950
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004951 for (const auto& request : mRequestQueue) {
4952 for (const auto& s : request->mOutputStreams) {
4953 if (stream == s) return true;
4954 }
4955 if (stream == request->mInputStream) return true;
4956 }
4957
4958 for (const auto& request : mRepeatingRequests) {
4959 for (const auto& s : request->mOutputStreams) {
4960 if (stream == s) return true;
4961 }
4962 if (stream == request->mInputStream) return true;
4963 }
4964
4965 return false;
4966}
Jianing Weicb0652e2014-03-12 18:29:36 -07004967
Emilian Peev40ead602017-09-26 15:46:36 +01004968bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4969 ATRACE_CALL();
4970 Mutex::Autolock l(mRequestLock);
4971
4972 for (const auto& nextRequest : mNextRequests) {
4973 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4974 if (s.first == streamId) {
4975 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4976 if (it != s.second.end()) {
4977 return true;
4978 }
4979 }
4980 }
4981 }
4982
4983 for (const auto& request : mRequestQueue) {
4984 for (const auto& s : request->mOutputSurfaces) {
4985 if (s.first == streamId) {
4986 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4987 if (it != s.second.end()) {
4988 return true;
4989 }
4990 }
4991 }
4992 }
4993
4994 for (const auto& request : mRepeatingRequests) {
4995 for (const auto& s : request->mOutputSurfaces) {
4996 if (s.first == streamId) {
4997 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4998 if (it != s.second.end()) {
4999 return true;
5000 }
5001 }
5002 }
5003 }
5004
5005 return false;
5006}
5007
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005008nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005009 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005010 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005011 return mExpectedInflightDuration > kMinInflightDuration ?
5012 mExpectedInflightDuration : kMinInflightDuration;
5013}
5014
Emilian Peevaebbe412018-01-15 13:53:24 +00005015void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5016 camera3_capture_request_t *halRequest) {
5017 if ((request == nullptr) || (halRequest == nullptr)) {
5018 ALOGE("%s: Invalid request!", __FUNCTION__);
5019 return;
5020 }
5021
5022 if (halRequest->num_physcam_settings > 0) {
5023 if (halRequest->physcam_id != nullptr) {
5024 delete [] halRequest->physcam_id;
5025 halRequest->physcam_id = nullptr;
5026 }
5027 if (halRequest->physcam_settings != nullptr) {
5028 auto it = ++(request->mSettingsList.begin());
5029 size_t i = 0;
5030 for (; it != request->mSettingsList.end(); it++, i++) {
5031 it->metadata.unlock(halRequest->physcam_settings[i]);
5032 }
5033 delete [] halRequest->physcam_settings;
5034 halRequest->physcam_settings = nullptr;
5035 }
5036 }
5037}
5038
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005039void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5040 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005041 return;
5042 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005043
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005044 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005045 // Skip the ones that have been submitted successfully.
5046 if (nextRequest.submitted) {
5047 continue;
5048 }
5049
5050 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5051 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5052 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5053
5054 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005055 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005056 }
5057
Emilian Peevaebbe412018-01-15 13:53:24 +00005058 cleanupPhysicalSettings(captureRequest, halRequest);
5059
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005060 if (captureRequest->mInputStream != NULL) {
5061 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5062 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5063 }
5064
5065 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005066 //Buffers that failed processing could still have
5067 //valid acquire fence.
5068 int acquireFence = (*outputBuffers)[i].acquire_fence;
5069 if (0 <= acquireFence) {
5070 close(acquireFence);
5071 outputBuffers->editItemAt(i).acquire_fence = -1;
5072 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005073 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5074 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5075 }
5076
5077 if (sendRequestError) {
5078 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005079 sp<NotificationListener> listener = mListener.promote();
5080 if (listener != NULL) {
5081 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005082 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005083 captureRequest->mResultExtras);
5084 }
5085 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005086
5087 // Remove yet-to-be submitted inflight request from inflightMap
5088 {
5089 sp<Camera3Device> parent = mParent.promote();
5090 if (parent != NULL) {
5091 Mutex::Autolock l(parent->mInFlightLock);
5092 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5093 if (idx >= 0) {
5094 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5095 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5096 parent->removeInFlightMapEntryLocked(idx);
5097 }
5098 }
5099 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005100 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005101
5102 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005103 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104}
5105
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005106void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005107 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005108 // Optimized a bit for the simple steady-state case (single repeating
5109 // request), to avoid putting that request in the queue temporarily.
5110 Mutex::Autolock l(mRequestLock);
5111
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005112 assert(mNextRequests.empty());
5113
5114 NextRequest nextRequest;
5115 nextRequest.captureRequest = waitForNextRequestLocked();
5116 if (nextRequest.captureRequest == nullptr) {
5117 return;
5118 }
5119
5120 nextRequest.halRequest = camera3_capture_request_t();
5121 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005122 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005123
5124 // Wait for additional requests
5125 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5126
5127 for (size_t i = 1; i < batchSize; i++) {
5128 NextRequest additionalRequest;
5129 additionalRequest.captureRequest = waitForNextRequestLocked();
5130 if (additionalRequest.captureRequest == nullptr) {
5131 break;
5132 }
5133
5134 additionalRequest.halRequest = camera3_capture_request_t();
5135 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005136 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005137 }
5138
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005139 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005140 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005141 mNextRequests.size(), batchSize);
5142 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005143 }
5144
5145 return;
5146}
5147
5148sp<Camera3Device::CaptureRequest>
5149 Camera3Device::RequestThread::waitForNextRequestLocked() {
5150 status_t res;
5151 sp<CaptureRequest> nextRequest;
5152
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005153 while (mRequestQueue.empty()) {
5154 if (!mRepeatingRequests.empty()) {
5155 // Always atomically enqueue all requests in a repeating request
5156 // list. Guarantees a complete in-sequence set of captures to
5157 // application.
5158 const RequestList &requests = mRepeatingRequests;
5159 RequestList::const_iterator firstRequest =
5160 requests.begin();
5161 nextRequest = *firstRequest;
5162 mRequestQueue.insert(mRequestQueue.end(),
5163 ++firstRequest,
5164 requests.end());
5165 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005166
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005167 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005169 break;
5170 }
5171
5172 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5173
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005174 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5175 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005176 Mutex::Autolock pl(mPauseLock);
5177 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005178 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005179 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005180 // Let the tracker know
5181 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5182 if (statusTracker != 0) {
5183 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5184 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005185 }
5186 // Stop waiting for now and let thread management happen
5187 return NULL;
5188 }
5189 }
5190
5191 if (nextRequest == NULL) {
5192 // Don't have a repeating request already in hand, so queue
5193 // must have an entry now.
5194 RequestList::iterator firstRequest =
5195 mRequestQueue.begin();
5196 nextRequest = *firstRequest;
5197 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005198 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5199 sp<NotificationListener> listener = mListener.promote();
5200 if (listener != NULL) {
5201 listener->notifyRequestQueueEmpty();
5202 }
5203 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005204 }
5205
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005206 // In case we've been unpaused by setPaused clearing mDoPause, need to
5207 // update internal pause state (capture/setRepeatingRequest unpause
5208 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005209 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005210 if (mPaused) {
5211 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5212 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5213 if (statusTracker != 0) {
5214 statusTracker->markComponentActive(mStatusId);
5215 }
5216 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005217 mPaused = false;
5218
5219 // Check if we've reconfigured since last time, and reset the preview
5220 // request if so. Can't use 'NULL request == repeat' across configure calls.
5221 if (mReconfigured) {
5222 mPrevRequest.clear();
5223 mReconfigured = false;
5224 }
5225
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005226 if (nextRequest != NULL) {
5227 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005228 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5229 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005230
5231 // Since RequestThread::clear() removes buffers from the input stream,
5232 // get the right buffer here before unlocking mRequestLock
5233 if (nextRequest->mInputStream != NULL) {
5234 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5235 if (res != OK) {
5236 // Can't get input buffer from gralloc queue - this could be due to
5237 // disconnected queue or other producer misbehavior, so not a fatal
5238 // error
5239 ALOGE("%s: Can't get input buffer, skipping request:"
5240 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005241
5242 sp<NotificationListener> listener = mListener.promote();
5243 if (listener != NULL) {
5244 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005245 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005246 nextRequest->mResultExtras);
5247 }
5248 return NULL;
5249 }
5250 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005251 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005252
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005253 return nextRequest;
5254}
5255
5256bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005257 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005258 status_t res;
5259 Mutex::Autolock l(mPauseLock);
5260 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005261 if (mPaused == false) {
5262 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005263 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5264 // Let the tracker know
5265 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5266 if (statusTracker != 0) {
5267 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5268 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005269 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005270
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005271 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005272 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005273 return true;
5274 }
5275 }
5276 // We don't set mPaused to false here, because waitForNextRequest needs
5277 // to further manage the paused state in case of starvation.
5278 return false;
5279}
5280
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005281void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005282 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005283 // With work to do, mark thread as unpaused.
5284 // If paused by request (setPaused), don't resume, to avoid
5285 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005286 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005287 Mutex::Autolock p(mPauseLock);
5288 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005289 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5290 if (mPaused) {
5291 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5292 if (statusTracker != 0) {
5293 statusTracker->markComponentActive(mStatusId);
5294 }
5295 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005296 mPaused = false;
5297 }
5298}
5299
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005300void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5301 sp<Camera3Device> parent = mParent.promote();
5302 if (parent != NULL) {
5303 va_list args;
5304 va_start(args, fmt);
5305
5306 parent->setErrorStateV(fmt, args);
5307
5308 va_end(args);
5309 }
5310}
5311
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005312status_t Camera3Device::RequestThread::insertTriggers(
5313 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005314 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005315 Mutex::Autolock al(mTriggerMutex);
5316
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005317 sp<Camera3Device> parent = mParent.promote();
5318 if (parent == NULL) {
5319 CLOGE("RequestThread: Parent is gone");
5320 return DEAD_OBJECT;
5321 }
5322
Emilian Peevaebbe412018-01-15 13:53:24 +00005323 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005324 size_t count = mTriggerMap.size();
5325
5326 for (size_t i = 0; i < count; ++i) {
5327 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005328 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005329
5330 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5331 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5332 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005333 if (isAeTrigger) {
5334 request->mResultExtras.precaptureTriggerId = triggerId;
5335 mCurrentPreCaptureTriggerId = triggerId;
5336 } else {
5337 request->mResultExtras.afTriggerId = triggerId;
5338 mCurrentAfTriggerId = triggerId;
5339 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005340 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005341 }
5342
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005343 camera_metadata_entry entry = metadata.find(tag);
5344
5345 if (entry.count > 0) {
5346 /**
5347 * Already has an entry for this trigger in the request.
5348 * Rewrite it with our requested trigger value.
5349 */
5350 RequestTrigger oldTrigger = trigger;
5351
5352 oldTrigger.entryValue = entry.data.u8[0];
5353
5354 mTriggerReplacedMap.add(tag, oldTrigger);
5355 } else {
5356 /**
5357 * More typical, no trigger entry, so we just add it
5358 */
5359 mTriggerRemovedMap.add(tag, trigger);
5360 }
5361
5362 status_t res;
5363
5364 switch (trigger.getTagType()) {
5365 case TYPE_BYTE: {
5366 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5367 res = metadata.update(tag,
5368 &entryValue,
5369 /*count*/1);
5370 break;
5371 }
5372 case TYPE_INT32:
5373 res = metadata.update(tag,
5374 &trigger.entryValue,
5375 /*count*/1);
5376 break;
5377 default:
5378 ALOGE("%s: Type not supported: 0x%x",
5379 __FUNCTION__,
5380 trigger.getTagType());
5381 return INVALID_OPERATION;
5382 }
5383
5384 if (res != OK) {
5385 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5386 ", value %d", __FUNCTION__, trigger.getTagName(),
5387 trigger.entryValue);
5388 return res;
5389 }
5390
5391 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5392 trigger.getTagName(),
5393 trigger.entryValue);
5394 }
5395
5396 mTriggerMap.clear();
5397
5398 return count;
5399}
5400
5401status_t Camera3Device::RequestThread::removeTriggers(
5402 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005403 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005404 Mutex::Autolock al(mTriggerMutex);
5405
Emilian Peevaebbe412018-01-15 13:53:24 +00005406 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005407
5408 /**
5409 * Replace all old entries with their old values.
5410 */
5411 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5412 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5413
5414 status_t res;
5415
5416 uint32_t tag = trigger.metadataTag;
5417 switch (trigger.getTagType()) {
5418 case TYPE_BYTE: {
5419 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5420 res = metadata.update(tag,
5421 &entryValue,
5422 /*count*/1);
5423 break;
5424 }
5425 case TYPE_INT32:
5426 res = metadata.update(tag,
5427 &trigger.entryValue,
5428 /*count*/1);
5429 break;
5430 default:
5431 ALOGE("%s: Type not supported: 0x%x",
5432 __FUNCTION__,
5433 trigger.getTagType());
5434 return INVALID_OPERATION;
5435 }
5436
5437 if (res != OK) {
5438 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5439 ", trigger value %d", __FUNCTION__,
5440 trigger.getTagName(), trigger.entryValue);
5441 return res;
5442 }
5443 }
5444 mTriggerReplacedMap.clear();
5445
5446 /**
5447 * Remove all new entries.
5448 */
5449 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5450 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5451 status_t res = metadata.erase(trigger.metadataTag);
5452
5453 if (res != OK) {
5454 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5455 ", trigger value %d", __FUNCTION__,
5456 trigger.getTagName(), trigger.entryValue);
5457 return res;
5458 }
5459 }
5460 mTriggerRemovedMap.clear();
5461
5462 return OK;
5463}
5464
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005465status_t Camera3Device::RequestThread::addDummyTriggerIds(
5466 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005467 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005468 static const int32_t dummyTriggerId = 1;
5469 status_t res;
5470
Emilian Peevaebbe412018-01-15 13:53:24 +00005471 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005472
5473 // If AF trigger is active, insert a dummy AF trigger ID if none already
5474 // exists
5475 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5476 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5477 if (afTrigger.count > 0 &&
5478 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5479 afId.count == 0) {
5480 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5481 if (res != OK) return res;
5482 }
5483
5484 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5485 // if none already exists
5486 camera_metadata_entry pcTrigger =
5487 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5488 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5489 if (pcTrigger.count > 0 &&
5490 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5491 pcId.count == 0) {
5492 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5493 &dummyTriggerId, 1);
5494 if (res != OK) return res;
5495 }
5496
5497 return OK;
5498}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005499
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005500/**
5501 * PreparerThread inner class methods
5502 */
5503
5504Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005505 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005506 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005507}
5508
5509Camera3Device::PreparerThread::~PreparerThread() {
5510 Thread::requestExitAndWait();
5511 if (mCurrentStream != nullptr) {
5512 mCurrentStream->cancelPrepare();
5513 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5514 mCurrentStream.clear();
5515 }
5516 clear();
5517}
5518
Ruben Brunkc78ac262015-08-13 17:58:46 -07005519status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005520 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005521 status_t res;
5522
5523 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005524 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005525
Ruben Brunkc78ac262015-08-13 17:58:46 -07005526 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005527 if (res == OK) {
5528 // No preparation needed, fire listener right off
5529 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
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 OK;
5534 } else if (res != NOT_ENOUGH_DATA) {
5535 return res;
5536 }
5537
5538 // Need to prepare, start up thread if necessary
5539 if (!mActive) {
5540 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5541 // isn't running
5542 Thread::requestExitAndWait();
5543 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5544 if (res != OK) {
5545 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005546 if (listener != NULL) {
5547 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005548 }
5549 return res;
5550 }
5551 mCancelNow = false;
5552 mActive = true;
5553 ALOGV("%s: Preparer stream started", __FUNCTION__);
5554 }
5555
5556 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005557 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005558 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5559
5560 return OK;
5561}
5562
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005563void Camera3Device::PreparerThread::pause() {
5564 ATRACE_CALL();
5565
5566 Mutex::Autolock l(mLock);
5567
5568 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5569 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5570 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5571 int currentMaxCount = mCurrentMaxCount;
5572 mPendingStreams.clear();
5573 mCancelNow = true;
5574 while (mActive) {
5575 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5576 if (res == TIMED_OUT) {
5577 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5578 return;
5579 } else if (res != OK) {
5580 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5581 return;
5582 }
5583 }
5584
5585 //Check whether the prepare thread was able to complete the current
5586 //stream. In case work is still pending emplace it along with the rest
5587 //of the streams in the pending list.
5588 if (currentStream != nullptr) {
5589 if (!mCurrentPrepareComplete) {
5590 pendingStreams.emplace(currentMaxCount, currentStream);
5591 }
5592 }
5593
5594 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5595 for (const auto& it : mPendingStreams) {
5596 it.second->cancelPrepare();
5597 }
5598}
5599
5600status_t Camera3Device::PreparerThread::resume() {
5601 ATRACE_CALL();
5602 status_t res;
5603
5604 Mutex::Autolock l(mLock);
5605 sp<NotificationListener> listener = mListener.promote();
5606
5607 if (mActive) {
5608 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5609 return NO_INIT;
5610 }
5611
5612 auto it = mPendingStreams.begin();
5613 for (; it != mPendingStreams.end();) {
5614 res = it->second->startPrepare(it->first);
5615 if (res == OK) {
5616 if (listener != NULL) {
5617 listener->notifyPrepared(it->second->getId());
5618 }
5619 it = mPendingStreams.erase(it);
5620 } else if (res != NOT_ENOUGH_DATA) {
5621 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5622 res, strerror(-res));
5623 it = mPendingStreams.erase(it);
5624 } else {
5625 it++;
5626 }
5627 }
5628
5629 if (mPendingStreams.empty()) {
5630 return OK;
5631 }
5632
5633 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5634 if (res != OK) {
5635 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5636 __FUNCTION__, res, strerror(-res));
5637 return res;
5638 }
5639 mCancelNow = false;
5640 mActive = true;
5641 ALOGV("%s: Preparer stream started", __FUNCTION__);
5642
5643 return OK;
5644}
5645
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005646status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005647 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005648 Mutex::Autolock l(mLock);
5649
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005650 for (const auto& it : mPendingStreams) {
5651 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005652 }
5653 mPendingStreams.clear();
5654 mCancelNow = true;
5655
5656 return OK;
5657}
5658
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005659void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005660 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005661 Mutex::Autolock l(mLock);
5662 mListener = listener;
5663}
5664
5665bool Camera3Device::PreparerThread::threadLoop() {
5666 status_t res;
5667 {
5668 Mutex::Autolock l(mLock);
5669 if (mCurrentStream == nullptr) {
5670 // End thread if done with work
5671 if (mPendingStreams.empty()) {
5672 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5673 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5674 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5675 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005676 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005677 return false;
5678 }
5679
5680 // Get next stream to prepare
5681 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005682 mCurrentStream = it->second;
5683 mCurrentMaxCount = it->first;
5684 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005685 mPendingStreams.erase(it);
5686 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5687 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5688 } else if (mCancelNow) {
5689 mCurrentStream->cancelPrepare();
5690 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5691 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5692 mCurrentStream.clear();
5693 mCancelNow = false;
5694 return true;
5695 }
5696 }
5697
5698 res = mCurrentStream->prepareNextBuffer();
5699 if (res == NOT_ENOUGH_DATA) return true;
5700 if (res != OK) {
5701 // Something bad happened; try to recover by cancelling prepare and
5702 // signalling listener anyway
5703 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5704 mCurrentStream->getId(), res, strerror(-res));
5705 mCurrentStream->cancelPrepare();
5706 }
5707
5708 // This stream has finished, notify listener
5709 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005710 sp<NotificationListener> listener = mListener.promote();
5711 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005712 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5713 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005714 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005715 }
5716
5717 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5718 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005719 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005720
5721 return true;
5722}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005724/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005725 * Static callback forwarding methods from HAL to instance
5726 */
5727
5728void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5729 const camera3_capture_result *result) {
5730 Camera3Device *d =
5731 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005732
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005733 d->processCaptureResult(result);
5734}
5735
5736void Camera3Device::sNotify(const camera3_callback_ops *cb,
5737 const camera3_notify_msg *msg) {
5738 Camera3Device *d =
5739 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5740 d->notify(msg);
5741}
5742
5743}; // namespace android