blob: fb81b88efb0a9d2737082b55931e281d5f3c6ded [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 }
Yin-Chia Yeh1859a382020-03-16 11:49:30 -07003003
3004 nsecs_t sensorTimestamp = timestamp.data.i64[0];
3005
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003006 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3007 camera_metadata_entry timestamp =
3008 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3009 if (timestamp.count == 0) {
3010 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3011 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3012 return;
3013 }
3014 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003015
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003016 // Fix up some result metadata to account for HAL-level distortion correction
3017 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3018 if (res != OK) {
3019 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3020 frameNumber, strerror(res), res);
3021 return;
3022 }
3023
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003024 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Yin-Chia Yeh1859a382020-03-16 11:49:30 -07003025 frameNumber, sensorTimestamp, captureResult.mMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003026
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003027 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003028}
3029
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003030/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003031 * Camera HAL device callback methods
3032 */
3033
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003034void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003035 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003036
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003037 status_t res;
3038
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003039 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003040 if (result->result == NULL && result->num_output_buffers == 0 &&
3041 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003042 SET_ERR("No result data provided by HAL for frame %d",
3043 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003044 return;
3045 }
Zhijun He204e3292014-07-14 17:09:23 -07003046
Zhijun He204e3292014-07-14 17:09:23 -07003047 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003048 result->result != NULL &&
3049 result->partial_result != 1) {
3050 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3051 " if partial result is not supported",
3052 frameNumber, result->partial_result);
3053 return;
3054 }
3055
3056 bool isPartialResult = false;
3057 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003058 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003059
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003060 // Get shutter timestamp and resultExtras from list of in-flight requests,
3061 // where it was added by the shutter notification for this frame. If the
3062 // shutter timestamp isn't received yet, append the output buffers to the
3063 // in-flight request and they will be returned when the shutter timestamp
3064 // arrives. Update the in-flight status and remove the in-flight entry if
3065 // all result data and shutter timestamp have been received.
3066 nsecs_t shutterTimestamp = 0;
3067
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003068 {
3069 Mutex::Autolock l(mInFlightLock);
3070 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3071 if (idx == NAME_NOT_FOUND) {
3072 SET_ERR("Unknown frame number for capture result: %d",
3073 frameNumber);
3074 return;
3075 }
3076 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003077 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3078 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003079 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003080 __FUNCTION__, request.resultExtras.requestId,
3081 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003082 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003083 // Always update the partial count to the latest one if it's not 0
3084 // (buffers only). When framework aggregates adjacent partial results
3085 // into one, the latest partial count will be used.
3086 if (result->partial_result != 0)
3087 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003088
3089 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003090 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003091 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3092 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3093 " the range of [1, %d] when metadata is included in the result",
3094 frameNumber, result->partial_result, mNumPartialResults);
3095 return;
3096 }
3097 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003098 if (isPartialResult && result->num_physcam_metadata) {
3099 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3100 " physical camera result", frameNumber);
3101 return;
3102 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003103 if (isPartialResult) {
3104 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003105 }
3106
Shuzhen Wang4a472662017-02-26 23:29:04 -08003107 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003108 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003109 sendPartialCaptureResult(result->result, request.resultExtras,
3110 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003111 }
3112 }
3113
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003114 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003115 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003116
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003117 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003118 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003119 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3120 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3121 request.physicalCameraIds.size(), result->num_physcam_metadata);
3122 return;
3123 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003124 if (request.haveResultMetadata) {
3125 SET_ERR("Called multiple times with metadata for frame %d",
3126 frameNumber);
3127 return;
3128 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003129 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3130 String8 physicalId(result->physcam_ids[i]);
3131 std::set<String8>::iterator cameraIdIter =
3132 request.physicalCameraIds.find(physicalId);
3133 if (cameraIdIter != request.physicalCameraIds.end()) {
3134 request.physicalCameraIds.erase(cameraIdIter);
3135 } else {
3136 SET_ERR("Total result for frame %d has already returned for camera %s",
3137 frameNumber, physicalId.c_str());
3138 return;
3139 }
3140 }
Zhijun He204e3292014-07-14 17:09:23 -07003141 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003142 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003143 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003144 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003145 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003146 request.haveResultMetadata = true;
3147 }
3148
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003149 uint32_t numBuffersReturned = result->num_output_buffers;
3150 if (result->input_buffer != NULL) {
3151 if (hasInputBufferInRequest) {
3152 numBuffersReturned += 1;
3153 } else {
3154 ALOGW("%s: Input buffer should be NULL if there is no input"
3155 " buffer sent in the request",
3156 __FUNCTION__);
3157 }
3158 }
3159 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003160 if (request.numBuffersLeft < 0) {
3161 SET_ERR("Too many buffers returned for frame %d",
3162 frameNumber);
3163 return;
3164 }
3165
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003166 camera_metadata_ro_entry_t entry;
3167 res = find_camera_metadata_ro_entry(result->result,
3168 ANDROID_SENSOR_TIMESTAMP, &entry);
3169 if (res == OK && entry.count == 1) {
3170 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003171 }
3172
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003173 // If shutter event isn't received yet, append the output buffers to
3174 // the in-flight request. Otherwise, return the output buffers to
3175 // streams.
3176 if (shutterTimestamp == 0) {
3177 request.pendingOutputBuffers.appendArray(result->output_buffers,
3178 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003179 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003180 returnOutputBuffers(result->output_buffers,
3181 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003182 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003183
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003184 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003185 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3186 CameraMetadata physicalMetadata;
3187 physicalMetadata.append(result->physcam_metadata[i]);
3188 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3189 physicalMetadata});
3190 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003191 if (shutterTimestamp == 0) {
3192 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003193 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003194 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003195 CameraMetadata metadata;
3196 metadata = result->result;
3197 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003198 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003199 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003200 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003201 }
3202
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003203 removeInFlightRequestIfReadyLocked(idx);
3204 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003205
Zhijun Hef0d962a2014-06-30 10:24:11 -07003206 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003207 if (hasInputBufferInRequest) {
3208 Camera3Stream *stream =
3209 Camera3Stream::cast(result->input_buffer->stream);
3210 res = stream->returnInputBuffer(*(result->input_buffer));
3211 // Note: stream may be deallocated at this point, if this buffer was the
3212 // last reference to it.
3213 if (res != OK) {
3214 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3215 " its stream:%s (%d)", __FUNCTION__,
3216 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003217 }
3218 } else {
3219 ALOGW("%s: Input buffer should be NULL if there is no input"
3220 " buffer sent in the request, skipping input buffer return.",
3221 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003222 }
3223 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003224}
3225
3226void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003227 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003228 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003229 {
3230 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003231 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003232 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003233
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003234 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003235 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003236 return;
3237 }
3238
3239 switch (msg->type) {
3240 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003241 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003242 break;
3243 }
3244 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003245 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003246 break;
3247 }
3248 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003249 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003250 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003251 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003252}
3253
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003254void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003255 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003256 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003257 // Map camera HAL error codes to ICameraDeviceCallback error codes
3258 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003259 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003260 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003261 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003262 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003263 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003264 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003265 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003266 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003267 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003268 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003269 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003270 };
3271
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003272 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003273 ((msg.error_code >= 0) &&
3274 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3275 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003276 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003277
3278 int streamId = 0;
3279 if (msg.error_stream != NULL) {
3280 Camera3Stream *stream =
3281 Camera3Stream::cast(msg.error_stream);
3282 streamId = stream->getId();
3283 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003284 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3285 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003286 streamId, msg.error_code);
3287
3288 CaptureResultExtras resultExtras;
3289 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003290 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003291 // SET_ERR calls notifyError
3292 SET_ERR("Camera HAL reported serious device error");
3293 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003294 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3295 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3296 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003297 {
3298 Mutex::Autolock l(mInFlightLock);
3299 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3300 if (idx >= 0) {
3301 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3302 r.requestStatus = msg.error_code;
3303 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003304 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3305 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3306 errorCode) {
3307 r.skipResultMetadata = true;
3308 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003309 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3310 errorCode) {
3311 // In case of missing result check whether the buffers
3312 // returned. If they returned, then remove inflight
3313 // request.
3314 removeInFlightRequestIfReadyLocked(idx);
3315 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003316 } else {
3317 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003318 ALOGE("Camera %s: %s: cannot find in-flight request on "
3319 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003320 resultExtras.frameNumber);
3321 }
3322 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003323 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003324 if (listener != NULL) {
3325 listener->notifyError(errorCode, resultExtras);
3326 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003327 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003328 }
3329 break;
3330 default:
3331 // SET_ERR calls notifyError
3332 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3333 break;
3334 }
3335}
3336
3337void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003338 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003339 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003340 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003341
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003342 // Set timestamp for the request in the in-flight tracking
3343 // and get the request ID to send upstream
3344 {
3345 Mutex::Autolock l(mInFlightLock);
3346 idx = mInFlightMap.indexOfKey(msg.frame_number);
3347 if (idx >= 0) {
3348 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003349
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003350 // Verify ordering of shutter notifications
3351 {
3352 Mutex::Autolock l(mOutputLock);
3353 // TODO: need to track errors for tighter bounds on expected frame number.
3354 if (r.hasInputBuffer) {
3355 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3356 SET_ERR("Shutter notification out-of-order. Expected "
3357 "notification for frame %d, got frame %d",
3358 mNextReprocessShutterFrameNumber, msg.frame_number);
3359 return;
3360 }
3361 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3362 } else {
3363 if (msg.frame_number < mNextShutterFrameNumber) {
3364 SET_ERR("Shutter notification out-of-order. Expected "
3365 "notification for frame %d, got frame %d",
3366 mNextShutterFrameNumber, msg.frame_number);
3367 return;
3368 }
3369 mNextShutterFrameNumber = msg.frame_number + 1;
3370 }
3371 }
3372
Shuzhen Wang4a472662017-02-26 23:29:04 -08003373 r.shutterTimestamp = msg.timestamp;
3374 if (r.hasCallback) {
3375 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003376 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003377 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003378 // Call listener, if any
3379 if (listener != NULL) {
3380 listener->notifyShutter(r.resultExtras, msg.timestamp);
3381 }
3382 // send pending result and buffers
3383 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3384 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003385 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003386 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003387 returnOutputBuffers(r.pendingOutputBuffers.array(),
3388 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3389 r.pendingOutputBuffers.clear();
3390
3391 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003392 }
3393 }
3394 if (idx < 0) {
3395 SET_ERR("Shutter notification for non-existent frame number %d",
3396 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003397 }
3398}
3399
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003400CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003401 ALOGV("%s", __FUNCTION__);
3402
Igor Murashkin1e479c02013-09-06 16:55:14 -07003403 CameraMetadata retVal;
3404
3405 if (mRequestThread != NULL) {
3406 retVal = mRequestThread->getLatestRequest();
3407 }
3408
Igor Murashkin1e479c02013-09-06 16:55:14 -07003409 return retVal;
3410}
3411
Jianing Weicb0652e2014-03-12 18:29:36 -07003412
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003413void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3414 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3415 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3416}
3417
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003418/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003419 * HalInterface inner class methods
3420 */
3421
Yifan Hongf79b5542017-04-11 14:44:25 -07003422Camera3Device::HalInterface::HalInterface(
3423 sp<ICameraDeviceSession> &session,
3424 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003425 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003426 mRequestMetadataQueue(queue) {
3427 // Check with hardware service manager if we can downcast these interfaces
3428 // Somewhat expensive, so cache the results at startup
3429 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3430 if (castResult_3_4.isOk()) {
3431 mHidlSession_3_4 = castResult_3_4;
3432 }
3433 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3434 if (castResult_3_3.isOk()) {
3435 mHidlSession_3_3 = castResult_3_3;
3436 }
3437}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003438
Emilian Peev31abd0a2017-05-11 18:37:46 +01003439Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003440
3441Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003442 mHidlSession(other.mHidlSession),
3443 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003444
3445bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003446 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003447}
3448
3449void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003450 mHidlSession_3_4.clear();
3451 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003452 mHidlSession.clear();
3453}
3454
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003455bool Camera3Device::HalInterface::supportBatchRequest() {
3456 return mHidlSession != nullptr;
3457}
3458
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003459status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3460 camera3_request_template_t templateId,
3461 /*out*/ camera_metadata_t **requestTemplate) {
3462 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3463 if (!valid()) return INVALID_OPERATION;
3464 status_t res = OK;
3465
Emilian Peev31abd0a2017-05-11 18:37:46 +01003466 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003467
3468 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003469 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003470 status = s;
3471 if (status == common::V1_0::Status::OK) {
3472 const camera_metadata *r =
3473 reinterpret_cast<const camera_metadata_t*>(request.data());
3474 size_t expectedSize = request.size();
3475 int ret = validate_camera_metadata_structure(r, &expectedSize);
3476 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3477 *requestTemplate = clone_camera_metadata(r);
3478 if (*requestTemplate == nullptr) {
3479 ALOGE("%s: Unable to clone camera metadata received from HAL",
3480 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003481 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003482 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003483 } else {
3484 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3485 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003486 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003487 }
3488 };
3489 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003490 RequestTemplate id;
3491 switch (templateId) {
3492 case CAMERA3_TEMPLATE_PREVIEW:
3493 id = RequestTemplate::PREVIEW;
3494 break;
3495 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3496 id = RequestTemplate::STILL_CAPTURE;
3497 break;
3498 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3499 id = RequestTemplate::VIDEO_RECORD;
3500 break;
3501 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3502 id = RequestTemplate::VIDEO_SNAPSHOT;
3503 break;
3504 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3505 id = RequestTemplate::ZERO_SHUTTER_LAG;
3506 break;
3507 case CAMERA3_TEMPLATE_MANUAL:
3508 id = RequestTemplate::MANUAL;
3509 break;
3510 default:
3511 // Unknown template ID, or this HAL is too old to support it
3512 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003513 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003514 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003515
Emilian Peev31abd0a2017-05-11 18:37:46 +01003516 if (!err.isOk()) {
3517 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3518 res = DEAD_OBJECT;
3519 } else {
3520 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003521 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003522
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003523 return res;
3524}
3525
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003526status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003527 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003528 ATRACE_NAME("CameraHal::configureStreams");
3529 if (!valid()) return INVALID_OPERATION;
3530 status_t res = OK;
3531
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532 // Convert stream config to HIDL
3533 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003534 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3535 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3536 requestedConfiguration3_2.streams.resize(config->num_streams);
3537 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003539 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3540 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003542
Emilian Peev31abd0a2017-05-11 18:37:46 +01003543 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3544 cam3stream->setBufferFreedListener(this);
3545 int streamId = cam3stream->getId();
3546 StreamType streamType;
3547 switch (src->stream_type) {
3548 case CAMERA3_STREAM_OUTPUT:
3549 streamType = StreamType::OUTPUT;
3550 break;
3551 case CAMERA3_STREAM_INPUT:
3552 streamType = StreamType::INPUT;
3553 break;
3554 default:
3555 ALOGE("%s: Stream %d: Unsupported stream type %d",
3556 __FUNCTION__, streamId, config->streams[i]->stream_type);
3557 return BAD_VALUE;
3558 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003559 dst3_2.id = streamId;
3560 dst3_2.streamType = streamType;
3561 dst3_2.width = src->width;
3562 dst3_2.height = src->height;
3563 dst3_2.format = mapToPixelFormat(src->format);
3564 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3565 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3566 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3567 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003568 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003569 if (src->physical_camera_id != nullptr) {
3570 dst3_4.physicalCameraId = src->physical_camera_id;
3571 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003572
3573 activeStreams.insert(streamId);
3574 // Create Buffer ID map if necessary
3575 if (mBufferIdMaps.count(streamId) == 0) {
3576 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3577 }
3578 }
3579 // remove BufferIdMap for deleted streams
3580 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3581 int streamId = it->first;
3582 bool active = activeStreams.count(streamId) > 0;
3583 if (!active) {
3584 it = mBufferIdMaps.erase(it);
3585 } else {
3586 ++it;
3587 }
3588 }
3589
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003590 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003591 res = mapToStreamConfigurationMode(
3592 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003593 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003594 if (res != OK) {
3595 return res;
3596 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003597 requestedConfiguration3_2.operationMode = operationMode;
3598 requestedConfiguration3_4.operationMode = operationMode;
3599 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003600 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3601 get_camera_metadata_size(sessionParams));
3602
Emilian Peev31abd0a2017-05-11 18:37:46 +01003603 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003604 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003605 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003606
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003607 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003608 if (mHidlSession_3_4 != nullptr) {
3609 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003610 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003611 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003612 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003613 [&status, &finalConfiguration3_4]
3614 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3615 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003616 status = s;
3617 });
3618 if (!err.isOk()) {
3619 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3620 return DEAD_OBJECT;
3621 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003622 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3623 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3624 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3625 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003626 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003627 // We do; use v3.3 for the call
3628 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003629 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003630 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003631 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003632 finalConfiguration = halConfiguration;
3633 status = s;
3634 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003635 if (!err.isOk()) {
3636 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3637 return DEAD_OBJECT;
3638 }
3639 } else {
3640 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3641 ALOGV("%s: v3.2 device found", __FUNCTION__);
3642 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003643 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003644 [&status, &finalConfiguration_3_2]
3645 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3646 finalConfiguration_3_2 = halConfiguration;
3647 status = s;
3648 });
3649 if (!err.isOk()) {
3650 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3651 return DEAD_OBJECT;
3652 }
3653 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3654 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3655 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3656 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003657 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003658 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003659 }
3660
3661 if (status != common::V1_0::Status::OK ) {
3662 return CameraProviderManager::mapToStatusT(status);
3663 }
3664
3665 // And convert output stream configuration from HIDL
3666
3667 for (size_t i = 0; i < config->num_streams; i++) {
3668 camera3_stream_t *dst = config->streams[i];
3669 int streamId = Camera3Stream::cast(dst)->getId();
3670
3671 // Start scan at i, with the assumption that the stream order matches
3672 size_t realIdx = i;
3673 bool found = false;
3674 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003675 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003676 found = true;
3677 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003678 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003679 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3680 }
3681 if (!found) {
3682 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3683 __FUNCTION__, streamId);
3684 return INVALID_OPERATION;
3685 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003686 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003687
Emilian Peev710c1422017-08-30 11:19:38 +01003688 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3689 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003690 dstStream->setDataSpaceOverride(false);
3691 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3692 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3693
Emilian Peev31abd0a2017-05-11 18:37:46 +01003694 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3695 if (dst->format != overrideFormat) {
3696 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3697 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003698 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003699 if (dst->data_space != overrideDataSpace) {
3700 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3701 streamId, dst->format);
3702 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003703 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003704 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003705 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3706
Emilian Peev31abd0a2017-05-11 18:37:46 +01003707 // Override allowed with IMPLEMENTATION_DEFINED
3708 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003709 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003710 }
3711
Emilian Peev31abd0a2017-05-11 18:37:46 +01003712 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003713 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003714 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003715 __FUNCTION__, streamId);
3716 return INVALID_OPERATION;
3717 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003718 dstStream->setUsage(
3719 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003720 } else {
3721 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003722 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003723 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3724 __FUNCTION__, streamId);
3725 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003726 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003727 dstStream->setUsage(
3728 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003729 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003730 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003731 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003732
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003733 return res;
3734}
3735
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003736void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3737 /*out*/device::V3_2::CaptureRequest* captureRequest,
3738 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003739 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003740 if (captureRequest == nullptr || handlesCreated == nullptr) {
3741 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3742 __FUNCTION__, captureRequest, handlesCreated);
3743 return;
3744 }
3745
3746 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003747
3748 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003749
3750 {
3751 std::lock_guard<std::mutex> lock(mInflightLock);
3752 if (request->input_buffer != nullptr) {
3753 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3754 buffer_handle_t buf = *(request->input_buffer->buffer);
3755 auto pair = getBufferId(buf, streamId);
3756 bool isNewBuffer = pair.first;
3757 uint64_t bufferId = pair.second;
3758 captureRequest->inputBuffer.streamId = streamId;
3759 captureRequest->inputBuffer.bufferId = bufferId;
3760 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3761 captureRequest->inputBuffer.status = BufferStatus::OK;
3762 native_handle_t *acquireFence = nullptr;
3763 if (request->input_buffer->acquire_fence != -1) {
3764 acquireFence = native_handle_create(1,0);
3765 acquireFence->data[0] = request->input_buffer->acquire_fence;
3766 handlesCreated->push_back(acquireFence);
3767 }
3768 captureRequest->inputBuffer.acquireFence = acquireFence;
3769 captureRequest->inputBuffer.releaseFence = nullptr;
3770
3771 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3772 request->input_buffer->buffer,
3773 request->input_buffer->acquire_fence);
3774 } else {
3775 captureRequest->inputBuffer.streamId = -1;
3776 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3777 }
3778
3779 captureRequest->outputBuffers.resize(request->num_output_buffers);
3780 for (size_t i = 0; i < request->num_output_buffers; i++) {
3781 const camera3_stream_buffer_t *src = request->output_buffers + i;
3782 StreamBuffer &dst = captureRequest->outputBuffers[i];
3783 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3784 buffer_handle_t buf = *(src->buffer);
3785 auto pair = getBufferId(buf, streamId);
3786 bool isNewBuffer = pair.first;
3787 dst.streamId = streamId;
3788 dst.bufferId = pair.second;
3789 dst.buffer = isNewBuffer ? buf : nullptr;
3790 dst.status = BufferStatus::OK;
3791 native_handle_t *acquireFence = nullptr;
3792 if (src->acquire_fence != -1) {
3793 acquireFence = native_handle_create(1,0);
3794 acquireFence->data[0] = src->acquire_fence;
3795 handlesCreated->push_back(acquireFence);
3796 }
3797 dst.acquireFence = acquireFence;
3798 dst.releaseFence = nullptr;
3799
3800 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3801 src->buffer, src->acquire_fence);
3802 }
3803 }
3804}
3805
3806status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3807 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3808 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3809 if (!valid()) return INVALID_OPERATION;
3810
Emilian Peevaebbe412018-01-15 13:53:24 +00003811 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3812 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3813 if (castResult_3_4.isOk()) {
3814 hidlSession_3_4 = castResult_3_4;
3815 }
3816
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003817 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003818 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003819 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003820 if (hidlSession_3_4 != nullptr) {
3821 captureRequests_3_4.resize(batchSize);
3822 } else {
3823 captureRequests.resize(batchSize);
3824 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003825 std::vector<native_handle_t*> handlesCreated;
3826
3827 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003828 if (hidlSession_3_4 != nullptr) {
3829 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3830 /*out*/&handlesCreated);
3831 } else {
3832 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3833 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003834 }
3835
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003836 std::vector<device::V3_2::BufferCache> cachesToRemove;
3837 {
3838 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3839 for (auto& pair : mFreedBuffers) {
3840 // The stream might have been removed since onBufferFreed
3841 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3842 cachesToRemove.push_back({pair.first, pair.second});
3843 }
3844 }
3845 mFreedBuffers.clear();
3846 }
3847
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003848 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3849 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003850
3851 // Write metadata to FMQ.
3852 for (size_t i = 0; i < batchSize; i++) {
3853 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003854 device::V3_2::CaptureRequest* captureRequest;
3855 if (hidlSession_3_4 != nullptr) {
3856 captureRequest = &captureRequests_3_4[i].v3_2;
3857 } else {
3858 captureRequest = &captureRequests[i];
3859 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003860
3861 if (request->settings != nullptr) {
3862 size_t settingsSize = get_camera_metadata_size(request->settings);
3863 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3864 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3865 captureRequest->settings.resize(0);
3866 captureRequest->fmqSettingsSize = settingsSize;
3867 } else {
3868 if (mRequestMetadataQueue != nullptr) {
3869 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3870 }
3871 captureRequest->settings.setToExternal(
3872 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3873 get_camera_metadata_size(request->settings));
3874 captureRequest->fmqSettingsSize = 0u;
3875 }
3876 } else {
3877 // A null request settings maps to a size-0 CameraMetadata
3878 captureRequest->settings.resize(0);
3879 captureRequest->fmqSettingsSize = 0u;
3880 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003881
3882 if (hidlSession_3_4 != nullptr) {
3883 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3884 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003885 if (request->physcam_settings != nullptr) {
3886 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3887 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3888 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3889 settingsSize)) {
3890 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3891 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3892 settingsSize;
3893 } else {
3894 if (mRequestMetadataQueue != nullptr) {
3895 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3896 }
3897 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3898 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3899 request->physcam_settings[j])),
3900 get_camera_metadata_size(request->physcam_settings[j]));
3901 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003902 }
Emilian Peev00420d22018-02-05 21:33:13 +00003903 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003904 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003905 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003906 }
3907 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3908 request->physcam_id[j];
3909 }
3910 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003911 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003912
3913 hardware::details::return_status err;
3914 if (hidlSession_3_4 != nullptr) {
3915 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003916 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3917 status = s;
3918 *numRequestProcessed = n;
3919 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003920 } else {
3921 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3922 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3923 status = s;
3924 *numRequestProcessed = n;
3925 });
3926 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003927 if (!err.isOk()) {
3928 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3929 return DEAD_OBJECT;
3930 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003931 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3932 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3933 __FUNCTION__, *numRequestProcessed, batchSize);
3934 status = common::V1_0::Status::INTERNAL_ERROR;
3935 }
3936
3937 for (auto& handle : handlesCreated) {
3938 native_handle_delete(handle);
3939 }
3940 return CameraProviderManager::mapToStatusT(status);
3941}
3942
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003943status_t Camera3Device::HalInterface::processCaptureRequest(
3944 camera3_capture_request_t *request) {
3945 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003946 if (!valid()) return INVALID_OPERATION;
3947 status_t res = OK;
3948
Emilian Peev31abd0a2017-05-11 18:37:46 +01003949 uint32_t numRequestProcessed = 0;
3950 std::vector<camera3_capture_request_t*> requests(1);
3951 requests[0] = request;
3952 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3953
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003954 return res;
3955}
3956
3957status_t Camera3Device::HalInterface::flush() {
3958 ATRACE_NAME("CameraHal::flush");
3959 if (!valid()) return INVALID_OPERATION;
3960 status_t res = OK;
3961
Emilian Peev31abd0a2017-05-11 18:37:46 +01003962 auto err = mHidlSession->flush();
3963 if (!err.isOk()) {
3964 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3965 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003966 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003967 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003968 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003969
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003970 return res;
3971}
3972
Emilian Peev31abd0a2017-05-11 18:37:46 +01003973status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974 ATRACE_NAME("CameraHal::dump");
3975 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003976
Emilian Peev31abd0a2017-05-11 18:37:46 +01003977 // Handled by CameraProviderManager::dump
3978
3979 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003980}
3981
3982status_t Camera3Device::HalInterface::close() {
3983 ATRACE_NAME("CameraHal::close()");
3984 if (!valid()) return INVALID_OPERATION;
3985 status_t res = OK;
3986
Emilian Peev31abd0a2017-05-11 18:37:46 +01003987 auto err = mHidlSession->close();
3988 // Interface will be dead shortly anyway, so don't log errors
3989 if (!err.isOk()) {
3990 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003992
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003993 return res;
3994}
3995
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003996void Camera3Device::HalInterface::getInflightBufferKeys(
3997 std::vector<std::pair<int32_t, int32_t>>* out) {
3998 std::lock_guard<std::mutex> lock(mInflightLock);
3999 out->clear();
4000 out->reserve(mInflightBufferMap.size());
4001 for (auto& pair : mInflightBufferMap) {
4002 uint64_t key = pair.first;
4003 int32_t streamId = key & 0xFFFFFFFF;
4004 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4005 out->push_back(std::make_pair(frameNumber, streamId));
4006 }
4007 return;
4008}
4009
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004010status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004011 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004013 auto pair = std::make_pair(buffer, acquireFence);
4014 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015 return OK;
4016}
4017
4018status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004019 int32_t frameNumber, int32_t streamId,
4020 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004021 std::lock_guard<std::mutex> lock(mInflightLock);
4022
4023 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4024 auto it = mInflightBufferMap.find(key);
4025 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004026 auto pair = it->second;
4027 *buffer = pair.first;
4028 int acquireFence = pair.second;
4029 if (acquireFence > 0) {
4030 ::close(acquireFence);
4031 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004032 mInflightBufferMap.erase(it);
4033 return OK;
4034}
4035
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004036std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4037 const buffer_handle_t& buf, int streamId) {
4038 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4039
4040 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4041 auto it = bIdMap.find(buf);
4042 if (it == bIdMap.end()) {
4043 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004044 ALOGV("stream %d now have %zu buffer caches, buf %p",
4045 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004046 return std::make_pair(true, mNextBufferId - 1);
4047 } else {
4048 return std::make_pair(false, it->second);
4049 }
4050}
4051
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004052void Camera3Device::HalInterface::onBufferFreed(
4053 int streamId, const native_handle_t* handle) {
4054 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4055 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4056 auto mapIt = mBufferIdMaps.find(streamId);
4057 if (mapIt == mBufferIdMaps.end()) {
4058 // streamId might be from a deleted stream here
4059 ALOGI("%s: stream %d has been removed",
4060 __FUNCTION__, streamId);
4061 return;
4062 }
4063 BufferIdMap& bIdMap = mapIt->second;
4064 auto it = bIdMap.find(handle);
4065 if (it == bIdMap.end()) {
4066 ALOGW("%s: cannot find buffer %p in stream %d",
4067 __FUNCTION__, handle, streamId);
4068 return;
4069 } else {
4070 bufferId = it->second;
4071 bIdMap.erase(it);
4072 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4073 __FUNCTION__, streamId, bIdMap.size(), handle);
4074 }
4075 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4076}
4077
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004078/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004079 * RequestThread inner class methods
4080 */
4081
4082Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004083 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004084 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004085 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004086 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004087 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004088 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004089 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004090 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004091 mReconfigured(false),
4092 mDoPause(false),
4093 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004094 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004095 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004096 mCurrentAfTriggerId(0),
4097 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004098 mRepeatingLastFrameNumber(
4099 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004100 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004101 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004102 mRequestLatency(kRequestLatencyBinSize),
4103 mSessionParamKeys(sessionParamKeys),
4104 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004105 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004106}
4107
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004108Camera3Device::RequestThread::~RequestThread() {}
4109
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004110void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004111 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004112 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004113 Mutex::Autolock l(mRequestLock);
4114 mListener = listener;
4115}
4116
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004117void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4118 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004119 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004120 Mutex::Autolock l(mRequestLock);
4121 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004122 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004123 // Prepare video stream for high speed recording.
4124 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004125 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004126}
4127
Jianing Wei90e59c92014-03-12 18:29:36 -07004128status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004129 List<sp<CaptureRequest> > &requests,
4130 /*out*/
4131 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004132 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004133 Mutex::Autolock l(mRequestLock);
4134 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4135 ++it) {
4136 mRequestQueue.push_back(*it);
4137 }
4138
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004139 if (lastFrameNumber != NULL) {
4140 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4141 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4142 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4143 *lastFrameNumber);
4144 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004145
Jianing Wei90e59c92014-03-12 18:29:36 -07004146 unpauseForNewRequests();
4147
4148 return OK;
4149}
4150
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004151
4152status_t Camera3Device::RequestThread::queueTrigger(
4153 RequestTrigger trigger[],
4154 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004155 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004156 Mutex::Autolock l(mTriggerMutex);
4157 status_t ret;
4158
4159 for (size_t i = 0; i < count; ++i) {
4160 ret = queueTriggerLocked(trigger[i]);
4161
4162 if (ret != OK) {
4163 return ret;
4164 }
4165 }
4166
4167 return OK;
4168}
4169
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004170const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4171 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004172 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004173 if (d != nullptr) return d->mId;
4174 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004175}
4176
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004177status_t Camera3Device::RequestThread::queueTriggerLocked(
4178 RequestTrigger trigger) {
4179
4180 uint32_t tag = trigger.metadataTag;
4181 ssize_t index = mTriggerMap.indexOfKey(tag);
4182
4183 switch (trigger.getTagType()) {
4184 case TYPE_BYTE:
4185 // fall-through
4186 case TYPE_INT32:
4187 break;
4188 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004189 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4190 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004191 return INVALID_OPERATION;
4192 }
4193
4194 /**
4195 * Collect only the latest trigger, since we only have 1 field
4196 * in the request settings per trigger tag, and can't send more than 1
4197 * trigger per request.
4198 */
4199 if (index != NAME_NOT_FOUND) {
4200 mTriggerMap.editValueAt(index) = trigger;
4201 } else {
4202 mTriggerMap.add(tag, trigger);
4203 }
4204
4205 return OK;
4206}
4207
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004208status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004209 const RequestList &requests,
4210 /*out*/
4211 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004212 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004213 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004214 if (lastFrameNumber != NULL) {
4215 *lastFrameNumber = mRepeatingLastFrameNumber;
4216 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217 mRepeatingRequests.clear();
4218 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4219 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004220
4221 unpauseForNewRequests();
4222
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004223 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004224 return OK;
4225}
4226
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004227bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004228 if (mRepeatingRequests.empty()) {
4229 return false;
4230 }
4231 int32_t requestId = requestIn->mResultExtras.requestId;
4232 const RequestList &repeatRequests = mRepeatingRequests;
4233 // All repeating requests are guaranteed to have same id so only check first quest
4234 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4235 return (firstRequest->mResultExtras.requestId == requestId);
4236}
4237
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004238status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004239 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004240 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004241 return clearRepeatingRequestsLocked(lastFrameNumber);
4242
4243}
4244
4245status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004246 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004247 if (lastFrameNumber != NULL) {
4248 *lastFrameNumber = mRepeatingLastFrameNumber;
4249 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004250 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251 return OK;
4252}
4253
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004254status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004255 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004256 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004257 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004258 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004259
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004260 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004261
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004262 // Send errors for all requests pending in the request queue, including
4263 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004264 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004265 if (listener != NULL) {
4266 for (RequestList::iterator it = mRequestQueue.begin();
4267 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004268 // Abort the input buffers for reprocess requests.
4269 if ((*it)->mInputStream != NULL) {
4270 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004271 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4272 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004273 if (res != OK) {
4274 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4275 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4276 } else {
4277 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4278 if (res != OK) {
4279 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4280 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4281 }
4282 }
4283 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004284 // Set the frame number this request would have had, if it
4285 // had been submitted; this frame number will not be reused.
4286 // The requestId and burstId fields were set when the request was
4287 // submitted originally (in convertMetadataListToRequestListLocked)
4288 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004289 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004290 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004291 }
4292 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004293 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004294
4295 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004296 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004297 if (lastFrameNumber != NULL) {
4298 *lastFrameNumber = mRepeatingLastFrameNumber;
4299 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004300 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004301 return OK;
4302}
4303
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004304status_t Camera3Device::RequestThread::flush() {
4305 ATRACE_CALL();
4306 Mutex::Autolock l(mFlushLock);
4307
Emilian Peev08dd2452017-04-06 16:55:14 +01004308 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004309}
4310
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004312 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004313 Mutex::Autolock l(mPauseLock);
4314 mDoPause = paused;
4315 mDoPauseSignal.signal();
4316}
4317
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004318status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4319 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004320 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004321 Mutex::Autolock l(mLatestRequestMutex);
4322 status_t res;
4323 while (mLatestRequestId != requestId) {
4324 nsecs_t startTime = systemTime();
4325
4326 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4327 if (res != OK) return res;
4328
4329 timeout -= (systemTime() - startTime);
4330 }
4331
4332 return OK;
4333}
4334
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004335void Camera3Device::RequestThread::requestExit() {
4336 // Call parent to set up shutdown
4337 Thread::requestExit();
4338 // The exit from any possible waits
4339 mDoPauseSignal.signal();
4340 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004341
4342 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4343 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004344}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004345
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004346void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004347 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004348 bool surfaceAbandoned = false;
4349 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004350 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004351 {
4352 Mutex::Autolock l(mRequestLock);
4353 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4354 // repeating requests.
4355 for (const auto& request : mRepeatingRequests) {
4356 for (const auto& s : request->mOutputStreams) {
4357 if (s->isAbandoned()) {
4358 surfaceAbandoned = true;
4359 clearRepeatingRequestsLocked(&lastFrameNumber);
4360 break;
4361 }
4362 }
4363 if (surfaceAbandoned) {
4364 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004365 }
4366 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004367 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004368 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004369
4370 if (listener != NULL && surfaceAbandoned) {
4371 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004372 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004373}
4374
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004375bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004376 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004377 status_t res;
4378 size_t batchSize = mNextRequests.size();
4379 std::vector<camera3_capture_request_t*> requests(batchSize);
4380 uint32_t numRequestProcessed = 0;
4381 for (size_t i = 0; i < batchSize; i++) {
4382 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004383 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004384 }
4385
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004386 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4387
4388 bool triggerRemoveFailed = false;
4389 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4390 for (size_t i = 0; i < numRequestProcessed; i++) {
4391 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4392 nextRequest.submitted = true;
4393
4394
4395 // Update the latest request sent to HAL
4396 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4397 Mutex::Autolock al(mLatestRequestMutex);
4398
4399 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4400 mLatestRequest.acquire(cloned);
4401
4402 sp<Camera3Device> parent = mParent.promote();
4403 if (parent != NULL) {
4404 parent->monitorMetadata(TagMonitor::REQUEST,
4405 nextRequest.halRequest.frame_number,
4406 0, mLatestRequest);
4407 }
4408 }
4409
4410 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004411 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4412 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004413 }
4414
Emilian Peevaebbe412018-01-15 13:53:24 +00004415 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4416
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004417 if (!triggerRemoveFailed) {
4418 // Remove any previously queued triggers (after unlock)
4419 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4420 if (removeTriggerRes != OK) {
4421 triggerRemoveFailed = true;
4422 triggerFailedRequest = nextRequest;
4423 }
4424 }
4425 }
4426
4427 if (triggerRemoveFailed) {
4428 SET_ERR("RequestThread: Unable to remove triggers "
4429 "(capture request %d, HAL device: %s (%d)",
4430 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4431 cleanUpFailedRequests(/*sendRequestError*/ false);
4432 return false;
4433 }
4434
4435 if (res != OK) {
4436 // Should only get a failure here for malformed requests or device-level
4437 // errors, so consider all errors fatal. Bad metadata failures should
4438 // come through notify.
4439 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4440 mNextRequests[numRequestProcessed].halRequest.frame_number,
4441 strerror(-res), res);
4442 cleanUpFailedRequests(/*sendRequestError*/ false);
4443 return false;
4444 }
4445 return true;
4446}
4447
4448bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4449 status_t res;
4450
4451 for (auto& nextRequest : mNextRequests) {
4452 // Submit request and block until ready for next one
4453 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4454 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4455
4456 if (res != OK) {
4457 // Should only get a failure here for malformed requests or device-level
4458 // errors, so consider all errors fatal. Bad metadata failures should
4459 // come through notify.
4460 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4461 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4462 res);
4463 cleanUpFailedRequests(/*sendRequestError*/ false);
4464 return false;
4465 }
4466
4467 // Mark that the request has be submitted successfully.
4468 nextRequest.submitted = true;
4469
4470 // Update the latest request sent to HAL
4471 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4472 Mutex::Autolock al(mLatestRequestMutex);
4473
4474 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4475 mLatestRequest.acquire(cloned);
4476
4477 sp<Camera3Device> parent = mParent.promote();
4478 if (parent != NULL) {
4479 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4480 0, mLatestRequest);
4481 }
4482 }
4483
4484 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004485 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4486 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004487 }
4488
Emilian Peevaebbe412018-01-15 13:53:24 +00004489 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4490
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004491 // Remove any previously queued triggers (after unlock)
4492 res = removeTriggers(mPrevRequest);
4493 if (res != OK) {
4494 SET_ERR("RequestThread: Unable to remove triggers "
4495 "(capture request %d, HAL device: %s (%d)",
4496 nextRequest.halRequest.frame_number, strerror(-res), res);
4497 cleanUpFailedRequests(/*sendRequestError*/ false);
4498 return false;
4499 }
4500 }
4501 return true;
4502}
4503
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004504nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4505 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4506 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4507 find_camera_metadata_ro_entry(request,
4508 ANDROID_CONTROL_AE_MODE,
4509 &e);
4510 if (e.count == 0) return maxExpectedDuration;
4511
4512 switch (e.data.u8[0]) {
4513 case ANDROID_CONTROL_AE_MODE_OFF:
4514 find_camera_metadata_ro_entry(request,
4515 ANDROID_SENSOR_EXPOSURE_TIME,
4516 &e);
4517 if (e.count > 0) {
4518 maxExpectedDuration = e.data.i64[0];
4519 }
4520 find_camera_metadata_ro_entry(request,
4521 ANDROID_SENSOR_FRAME_DURATION,
4522 &e);
4523 if (e.count > 0) {
4524 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4525 }
4526 break;
4527 default:
4528 find_camera_metadata_ro_entry(request,
4529 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4530 &e);
4531 if (e.count > 1) {
4532 maxExpectedDuration = 1e9 / e.data.u8[0];
4533 }
4534 break;
4535 }
4536
4537 return maxExpectedDuration;
4538}
4539
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004540bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4541 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4542 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4543 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4544 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4545 return true;
4546 }
4547
4548 return false;
4549}
4550
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004551bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4552 ATRACE_CALL();
4553 bool updatesDetected = false;
4554
4555 for (auto tag : mSessionParamKeys) {
4556 camera_metadata_ro_entry entry = settings.find(tag);
4557 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4558
4559 if (entry.count > 0) {
4560 bool isDifferent = false;
4561 if (lastEntry.count > 0) {
4562 // Have a last value, compare to see if changed
4563 if (lastEntry.type == entry.type &&
4564 lastEntry.count == entry.count) {
4565 // Same type and count, compare values
4566 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4567 size_t entryBytes = bytesPerValue * lastEntry.count;
4568 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4569 if (cmp != 0) {
4570 isDifferent = true;
4571 }
4572 } else {
4573 // Count or type has changed
4574 isDifferent = true;
4575 }
4576 } else {
4577 // No last entry, so always consider to be different
4578 isDifferent = true;
4579 }
4580
4581 if (isDifferent) {
4582 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004583 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4584 updatesDetected = true;
4585 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004586 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004587 }
4588 } else if (lastEntry.count > 0) {
4589 // Value has been removed
4590 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4591 mLatestSessionParams.erase(tag);
4592 updatesDetected = true;
4593 }
4594 }
4595
4596 return updatesDetected;
4597}
4598
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004599bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004600 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004601 status_t res;
4602
4603 // Handle paused state.
4604 if (waitIfPaused()) {
4605 return true;
4606 }
4607
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004608 // Wait for the next batch of requests.
4609 waitForNextRequestBatch();
4610 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004611 return true;
4612 }
4613
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004614 // Get the latest request ID, if any
4615 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004616 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004617 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004618 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004619 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004620 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004621 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4622 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004623 }
4624
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004625 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4626 // or a single request from streaming or burst. In either case the first element
4627 // should contain the latest camera settings that we need to check for any session
4628 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004629 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004630 res = OK;
4631
4632 //Input stream buffers are already acquired at this point so an input stream
4633 //will not be able to move to idle state unless we force it.
4634 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4635 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4636 if (res != OK) {
4637 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4638 cleanUpFailedRequests(/*sendRequestError*/ false);
4639 return false;
4640 }
4641 }
4642
4643 if (res == OK) {
4644 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4645 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004646 sp<Camera3Device> parent = mParent.promote();
4647 if (parent != nullptr) {
4648 parent->pauseStateNotify(true);
4649 }
4650
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004651 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4652
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004653 if (parent != nullptr) {
4654 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4655 }
4656
4657 statusTracker->markComponentActive(mStatusId);
4658 setPaused(false);
4659 }
4660
4661 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4662 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4663 if (res != OK) {
4664 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4665 cleanUpFailedRequests(/*sendRequestError*/ false);
4666 return false;
4667 }
4668 }
4669 }
4670 }
4671
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004672 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004673 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004674 if (res == TIMED_OUT) {
4675 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004676 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004677 // Check if any stream is abandoned.
4678 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004679 return true;
4680 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004681 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004682 return false;
4683 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004684
Zhijun Hecc27e112013-10-03 16:12:43 -07004685 // Inform waitUntilRequestProcessed thread of a new request ID
4686 {
4687 Mutex::Autolock al(mLatestRequestMutex);
4688
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004689 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004690 mLatestRequestSignal.signal();
4691 }
4692
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004693 // Submit a batch of requests to HAL.
4694 // Use flush lock only when submitting multilple requests in a batch.
4695 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4696 // which may take a long time to finish so synchronizing flush() and
4697 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4698 // For now, only synchronize for high speed recording and we should figure something out for
4699 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004700 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004701
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004702 if (useFlushLock) {
4703 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004704 }
4705
Zhijun Hef0645c12016-08-02 00:58:11 -07004706 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004708
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004709 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004710 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004711 if (mInterface->supportBatchRequest()) {
4712 submitRequestSuccess = sendRequestsBatch();
4713 } else {
4714 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004715 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004716 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4717 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004718
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004719 if (useFlushLock) {
4720 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004721 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004722
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004723 // Unset as current request
4724 {
4725 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004727 }
4728
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004729 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004730}
4731
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004732status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004733 ATRACE_CALL();
4734
Shuzhen Wang4a472662017-02-26 23:29:04 -08004735 for (size_t i = 0; i < mNextRequests.size(); i++) {
4736 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004737 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4738 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4739 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4740
4741 // Prepare a request to HAL
4742 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4743
4744 // Insert any queued triggers (before metadata is locked)
4745 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004746 if (res < 0) {
4747 SET_ERR("RequestThread: Unable to insert triggers "
4748 "(capture request %d, HAL device: %s (%d)",
4749 halRequest->frame_number, strerror(-res), res);
4750 return INVALID_OPERATION;
4751 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004752
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004753 int triggerCount = res;
4754 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4755 mPrevTriggers = triggerCount;
4756
4757 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004758 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4759 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004760 /**
4761 * HAL workaround:
4762 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4763 */
4764 res = addDummyTriggerIds(captureRequest);
4765 if (res != OK) {
4766 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4767 "(capture request %d, HAL device: %s (%d)",
4768 halRequest->frame_number, strerror(-res), res);
4769 return INVALID_OPERATION;
4770 }
4771
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004772 {
4773 // Correct metadata regions for distortion correction if enabled
4774 sp<Camera3Device> parent = mParent.promote();
4775 if (parent != nullptr) {
4776 res = parent->mDistortionMapper.correctCaptureRequest(
4777 &(captureRequest->mSettingsList.begin()->metadata));
4778 if (res != OK) {
4779 SET_ERR("RequestThread: Unable to correct capture requests "
4780 "for lens distortion for request %d: %s (%d)",
4781 halRequest->frame_number, strerror(-res), res);
4782 return INVALID_OPERATION;
4783 }
4784 }
4785 }
4786
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787 /**
4788 * The request should be presorted so accesses in HAL
4789 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4790 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004791 captureRequest->mSettingsList.begin()->metadata.sort();
4792 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 mPrevRequest = captureRequest;
4794 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4795
4796 IF_ALOGV() {
4797 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4798 find_camera_metadata_ro_entry(
4799 halRequest->settings,
4800 ANDROID_CONTROL_AF_TRIGGER,
4801 &e
4802 );
4803 if (e.count > 0) {
4804 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4805 __FUNCTION__,
4806 halRequest->frame_number,
4807 e.data.u8[0]);
4808 }
4809 }
4810 } else {
4811 // leave request.settings NULL to indicate 'reuse latest given'
4812 ALOGVV("%s: Request settings are REUSED",
4813 __FUNCTION__);
4814 }
4815
Emilian Peevaebbe412018-01-15 13:53:24 +00004816 if (captureRequest->mSettingsList.size() > 1) {
4817 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4818 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004819 if (newRequest) {
4820 halRequest->physcam_settings =
4821 new const camera_metadata* [halRequest->num_physcam_settings];
4822 } else {
4823 halRequest->physcam_settings = nullptr;
4824 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004825 auto it = ++captureRequest->mSettingsList.begin();
4826 size_t i = 0;
4827 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4828 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004829 if (newRequest) {
4830 it->metadata.sort();
4831 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4832 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004833 }
4834 }
4835
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004836 uint32_t totalNumBuffers = 0;
4837
4838 // Fill in buffers
4839 if (captureRequest->mInputStream != NULL) {
4840 halRequest->input_buffer = &captureRequest->mInputBuffer;
4841 totalNumBuffers += 1;
4842 } else {
4843 halRequest->input_buffer = NULL;
4844 }
4845
4846 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4847 captureRequest->mOutputStreams.size());
4848 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004849 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004850 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4851 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004852
4853 // Prepare video buffers for high speed recording on the first video request.
4854 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4855 // Only try to prepare video stream on the first video request.
4856 mPrepareVideoStream = false;
4857
4858 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4859 while (res == NOT_ENOUGH_DATA) {
4860 res = outputStream->prepareNextBuffer();
4861 }
4862 if (res != OK) {
4863 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4864 __FUNCTION__, strerror(-res), res);
4865 outputStream->cancelPrepare();
4866 }
4867 }
4868
Shuzhen Wang4a472662017-02-26 23:29:04 -08004869 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4870 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004871 if (res != OK) {
4872 // Can't get output buffer from gralloc queue - this could be due to
4873 // abandoned queue or other consumer misbehavior, so not a fatal
4874 // error
4875 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4876 " %s (%d)", strerror(-res), res);
4877
4878 return TIMED_OUT;
4879 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004880
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004881 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4882
4883 if (!physicalCameraId.isEmpty()) {
4884 // Physical stream isn't supported for input request.
4885 if (halRequest->input_buffer) {
4886 CLOGE("Physical stream is not supported for input request");
4887 return INVALID_OPERATION;
4888 }
4889 requestedPhysicalCameras.insert(physicalCameraId);
4890 }
4891 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004892 }
4893 totalNumBuffers += halRequest->num_output_buffers;
4894
4895 // Log request in the in-flight queue
4896 sp<Camera3Device> parent = mParent.promote();
4897 if (parent == NULL) {
4898 // Should not happen, and nowhere to send errors to, so just log it
4899 CLOGE("RequestThread: Parent is gone");
4900 return INVALID_OPERATION;
4901 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004902
4903 // If this request list is for constrained high speed recording (not
4904 // preview), and the current request is not the last one in the batch,
4905 // do not send callback to the app.
4906 bool hasCallback = true;
4907 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4908 hasCallback = false;
4909 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004910 res = parent->registerInFlight(halRequest->frame_number,
4911 totalNumBuffers, captureRequest->mResultExtras,
4912 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004913 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004914 calculateMaxExpectedDuration(halRequest->settings),
4915 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004916 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4917 ", burstId = %" PRId32 ".",
4918 __FUNCTION__,
4919 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4920 captureRequest->mResultExtras.burstId);
4921 if (res != OK) {
4922 SET_ERR("RequestThread: Unable to register new in-flight request:"
4923 " %s (%d)", strerror(-res), res);
4924 return INVALID_OPERATION;
4925 }
4926 }
4927
4928 return OK;
4929}
4930
Igor Murashkin1e479c02013-09-06 16:55:14 -07004931CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004932 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004933 Mutex::Autolock al(mLatestRequestMutex);
4934
4935 ALOGV("RequestThread::%s", __FUNCTION__);
4936
4937 return mLatestRequest;
4938}
4939
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004940bool Camera3Device::RequestThread::isStreamPending(
4941 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004942 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004943 Mutex::Autolock l(mRequestLock);
4944
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004945 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004946 if (!nextRequest.submitted) {
4947 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4948 if (stream == s) return true;
4949 }
4950 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004951 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004952 }
4953
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004954 for (const auto& request : mRequestQueue) {
4955 for (const auto& s : request->mOutputStreams) {
4956 if (stream == s) return true;
4957 }
4958 if (stream == request->mInputStream) return true;
4959 }
4960
4961 for (const auto& request : mRepeatingRequests) {
4962 for (const auto& s : request->mOutputStreams) {
4963 if (stream == s) return true;
4964 }
4965 if (stream == request->mInputStream) return true;
4966 }
4967
4968 return false;
4969}
Jianing Weicb0652e2014-03-12 18:29:36 -07004970
Emilian Peev40ead602017-09-26 15:46:36 +01004971bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4972 ATRACE_CALL();
4973 Mutex::Autolock l(mRequestLock);
4974
4975 for (const auto& nextRequest : mNextRequests) {
4976 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4977 if (s.first == streamId) {
4978 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4979 if (it != s.second.end()) {
4980 return true;
4981 }
4982 }
4983 }
4984 }
4985
4986 for (const auto& request : mRequestQueue) {
4987 for (const auto& s : request->mOutputSurfaces) {
4988 if (s.first == streamId) {
4989 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4990 if (it != s.second.end()) {
4991 return true;
4992 }
4993 }
4994 }
4995 }
4996
4997 for (const auto& request : mRepeatingRequests) {
4998 for (const auto& s : request->mOutputSurfaces) {
4999 if (s.first == streamId) {
5000 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5001 if (it != s.second.end()) {
5002 return true;
5003 }
5004 }
5005 }
5006 }
5007
5008 return false;
5009}
5010
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005011nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005012 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005013 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005014 return mExpectedInflightDuration > kMinInflightDuration ?
5015 mExpectedInflightDuration : kMinInflightDuration;
5016}
5017
Emilian Peevaebbe412018-01-15 13:53:24 +00005018void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5019 camera3_capture_request_t *halRequest) {
5020 if ((request == nullptr) || (halRequest == nullptr)) {
5021 ALOGE("%s: Invalid request!", __FUNCTION__);
5022 return;
5023 }
5024
5025 if (halRequest->num_physcam_settings > 0) {
5026 if (halRequest->physcam_id != nullptr) {
5027 delete [] halRequest->physcam_id;
5028 halRequest->physcam_id = nullptr;
5029 }
5030 if (halRequest->physcam_settings != nullptr) {
5031 auto it = ++(request->mSettingsList.begin());
5032 size_t i = 0;
5033 for (; it != request->mSettingsList.end(); it++, i++) {
5034 it->metadata.unlock(halRequest->physcam_settings[i]);
5035 }
5036 delete [] halRequest->physcam_settings;
5037 halRequest->physcam_settings = nullptr;
5038 }
5039 }
5040}
5041
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005042void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5043 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005044 return;
5045 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005046
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005047 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005048 // Skip the ones that have been submitted successfully.
5049 if (nextRequest.submitted) {
5050 continue;
5051 }
5052
5053 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5054 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5055 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5056
5057 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005058 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005059 }
5060
Emilian Peevaebbe412018-01-15 13:53:24 +00005061 cleanupPhysicalSettings(captureRequest, halRequest);
5062
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005063 if (captureRequest->mInputStream != NULL) {
5064 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5065 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5066 }
5067
5068 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005069 //Buffers that failed processing could still have
5070 //valid acquire fence.
5071 int acquireFence = (*outputBuffers)[i].acquire_fence;
5072 if (0 <= acquireFence) {
5073 close(acquireFence);
5074 outputBuffers->editItemAt(i).acquire_fence = -1;
5075 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005076 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5077 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5078 }
5079
5080 if (sendRequestError) {
5081 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005082 sp<NotificationListener> listener = mListener.promote();
5083 if (listener != NULL) {
5084 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005085 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005086 captureRequest->mResultExtras);
5087 }
5088 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005089
5090 // Remove yet-to-be submitted inflight request from inflightMap
5091 {
5092 sp<Camera3Device> parent = mParent.promote();
5093 if (parent != NULL) {
5094 Mutex::Autolock l(parent->mInFlightLock);
5095 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5096 if (idx >= 0) {
5097 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5098 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5099 parent->removeInFlightMapEntryLocked(idx);
5100 }
5101 }
5102 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005103 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005104
5105 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005106 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005107}
5108
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005109void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005110 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005111 // Optimized a bit for the simple steady-state case (single repeating
5112 // request), to avoid putting that request in the queue temporarily.
5113 Mutex::Autolock l(mRequestLock);
5114
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005115 assert(mNextRequests.empty());
5116
5117 NextRequest nextRequest;
5118 nextRequest.captureRequest = waitForNextRequestLocked();
5119 if (nextRequest.captureRequest == nullptr) {
5120 return;
5121 }
5122
5123 nextRequest.halRequest = camera3_capture_request_t();
5124 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005125 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005126
5127 // Wait for additional requests
5128 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5129
5130 for (size_t i = 1; i < batchSize; i++) {
5131 NextRequest additionalRequest;
5132 additionalRequest.captureRequest = waitForNextRequestLocked();
5133 if (additionalRequest.captureRequest == nullptr) {
5134 break;
5135 }
5136
5137 additionalRequest.halRequest = camera3_capture_request_t();
5138 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005139 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005140 }
5141
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005142 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005143 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005144 mNextRequests.size(), batchSize);
5145 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005146 }
5147
5148 return;
5149}
5150
5151sp<Camera3Device::CaptureRequest>
5152 Camera3Device::RequestThread::waitForNextRequestLocked() {
5153 status_t res;
5154 sp<CaptureRequest> nextRequest;
5155
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005156 while (mRequestQueue.empty()) {
5157 if (!mRepeatingRequests.empty()) {
5158 // Always atomically enqueue all requests in a repeating request
5159 // list. Guarantees a complete in-sequence set of captures to
5160 // application.
5161 const RequestList &requests = mRepeatingRequests;
5162 RequestList::const_iterator firstRequest =
5163 requests.begin();
5164 nextRequest = *firstRequest;
5165 mRequestQueue.insert(mRequestQueue.end(),
5166 ++firstRequest,
5167 requests.end());
5168 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005169
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005170 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005171
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005172 break;
5173 }
5174
5175 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5176
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005177 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5178 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005179 Mutex::Autolock pl(mPauseLock);
5180 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005181 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005182 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005183 // Let the tracker know
5184 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5185 if (statusTracker != 0) {
5186 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5187 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005188 }
5189 // Stop waiting for now and let thread management happen
5190 return NULL;
5191 }
5192 }
5193
5194 if (nextRequest == NULL) {
5195 // Don't have a repeating request already in hand, so queue
5196 // must have an entry now.
5197 RequestList::iterator firstRequest =
5198 mRequestQueue.begin();
5199 nextRequest = *firstRequest;
5200 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005201 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5202 sp<NotificationListener> listener = mListener.promote();
5203 if (listener != NULL) {
5204 listener->notifyRequestQueueEmpty();
5205 }
5206 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005207 }
5208
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005209 // In case we've been unpaused by setPaused clearing mDoPause, need to
5210 // update internal pause state (capture/setRepeatingRequest unpause
5211 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005212 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005213 if (mPaused) {
5214 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5215 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5216 if (statusTracker != 0) {
5217 statusTracker->markComponentActive(mStatusId);
5218 }
5219 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005220 mPaused = false;
5221
5222 // Check if we've reconfigured since last time, and reset the preview
5223 // request if so. Can't use 'NULL request == repeat' across configure calls.
5224 if (mReconfigured) {
5225 mPrevRequest.clear();
5226 mReconfigured = false;
5227 }
5228
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005229 if (nextRequest != NULL) {
5230 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005231 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5232 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005233
5234 // Since RequestThread::clear() removes buffers from the input stream,
5235 // get the right buffer here before unlocking mRequestLock
5236 if (nextRequest->mInputStream != NULL) {
5237 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5238 if (res != OK) {
5239 // Can't get input buffer from gralloc queue - this could be due to
5240 // disconnected queue or other producer misbehavior, so not a fatal
5241 // error
5242 ALOGE("%s: Can't get input buffer, skipping request:"
5243 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005244
5245 sp<NotificationListener> listener = mListener.promote();
5246 if (listener != NULL) {
5247 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005248 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005249 nextRequest->mResultExtras);
5250 }
5251 return NULL;
5252 }
5253 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005254 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005256 return nextRequest;
5257}
5258
5259bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005260 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005261 status_t res;
5262 Mutex::Autolock l(mPauseLock);
5263 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005264 if (mPaused == false) {
5265 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005266 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5267 // Let the tracker know
5268 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5269 if (statusTracker != 0) {
5270 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005272 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005273
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005274 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005275 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005276 return true;
5277 }
5278 }
5279 // We don't set mPaused to false here, because waitForNextRequest needs
5280 // to further manage the paused state in case of starvation.
5281 return false;
5282}
5283
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005284void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005285 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005286 // With work to do, mark thread as unpaused.
5287 // If paused by request (setPaused), don't resume, to avoid
5288 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005289 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005290 Mutex::Autolock p(mPauseLock);
5291 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005292 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5293 if (mPaused) {
5294 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5295 if (statusTracker != 0) {
5296 statusTracker->markComponentActive(mStatusId);
5297 }
5298 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005299 mPaused = false;
5300 }
5301}
5302
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005303void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5304 sp<Camera3Device> parent = mParent.promote();
5305 if (parent != NULL) {
5306 va_list args;
5307 va_start(args, fmt);
5308
5309 parent->setErrorStateV(fmt, args);
5310
5311 va_end(args);
5312 }
5313}
5314
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005315status_t Camera3Device::RequestThread::insertTriggers(
5316 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005317 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005318 Mutex::Autolock al(mTriggerMutex);
5319
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005320 sp<Camera3Device> parent = mParent.promote();
5321 if (parent == NULL) {
5322 CLOGE("RequestThread: Parent is gone");
5323 return DEAD_OBJECT;
5324 }
5325
Emilian Peevaebbe412018-01-15 13:53:24 +00005326 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005327 size_t count = mTriggerMap.size();
5328
5329 for (size_t i = 0; i < count; ++i) {
5330 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005331 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005332
5333 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5334 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5335 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005336 if (isAeTrigger) {
5337 request->mResultExtras.precaptureTriggerId = triggerId;
5338 mCurrentPreCaptureTriggerId = triggerId;
5339 } else {
5340 request->mResultExtras.afTriggerId = triggerId;
5341 mCurrentAfTriggerId = triggerId;
5342 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005343 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005344 }
5345
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005346 camera_metadata_entry entry = metadata.find(tag);
5347
5348 if (entry.count > 0) {
5349 /**
5350 * Already has an entry for this trigger in the request.
5351 * Rewrite it with our requested trigger value.
5352 */
5353 RequestTrigger oldTrigger = trigger;
5354
5355 oldTrigger.entryValue = entry.data.u8[0];
5356
5357 mTriggerReplacedMap.add(tag, oldTrigger);
5358 } else {
5359 /**
5360 * More typical, no trigger entry, so we just add it
5361 */
5362 mTriggerRemovedMap.add(tag, trigger);
5363 }
5364
5365 status_t res;
5366
5367 switch (trigger.getTagType()) {
5368 case TYPE_BYTE: {
5369 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5370 res = metadata.update(tag,
5371 &entryValue,
5372 /*count*/1);
5373 break;
5374 }
5375 case TYPE_INT32:
5376 res = metadata.update(tag,
5377 &trigger.entryValue,
5378 /*count*/1);
5379 break;
5380 default:
5381 ALOGE("%s: Type not supported: 0x%x",
5382 __FUNCTION__,
5383 trigger.getTagType());
5384 return INVALID_OPERATION;
5385 }
5386
5387 if (res != OK) {
5388 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5389 ", value %d", __FUNCTION__, trigger.getTagName(),
5390 trigger.entryValue);
5391 return res;
5392 }
5393
5394 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5395 trigger.getTagName(),
5396 trigger.entryValue);
5397 }
5398
5399 mTriggerMap.clear();
5400
5401 return count;
5402}
5403
5404status_t Camera3Device::RequestThread::removeTriggers(
5405 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005406 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005407 Mutex::Autolock al(mTriggerMutex);
5408
Emilian Peevaebbe412018-01-15 13:53:24 +00005409 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005410
5411 /**
5412 * Replace all old entries with their old values.
5413 */
5414 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5415 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5416
5417 status_t res;
5418
5419 uint32_t tag = trigger.metadataTag;
5420 switch (trigger.getTagType()) {
5421 case TYPE_BYTE: {
5422 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5423 res = metadata.update(tag,
5424 &entryValue,
5425 /*count*/1);
5426 break;
5427 }
5428 case TYPE_INT32:
5429 res = metadata.update(tag,
5430 &trigger.entryValue,
5431 /*count*/1);
5432 break;
5433 default:
5434 ALOGE("%s: Type not supported: 0x%x",
5435 __FUNCTION__,
5436 trigger.getTagType());
5437 return INVALID_OPERATION;
5438 }
5439
5440 if (res != OK) {
5441 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5442 ", trigger value %d", __FUNCTION__,
5443 trigger.getTagName(), trigger.entryValue);
5444 return res;
5445 }
5446 }
5447 mTriggerReplacedMap.clear();
5448
5449 /**
5450 * Remove all new entries.
5451 */
5452 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5453 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5454 status_t res = metadata.erase(trigger.metadataTag);
5455
5456 if (res != OK) {
5457 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5458 ", trigger value %d", __FUNCTION__,
5459 trigger.getTagName(), trigger.entryValue);
5460 return res;
5461 }
5462 }
5463 mTriggerRemovedMap.clear();
5464
5465 return OK;
5466}
5467
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005468status_t Camera3Device::RequestThread::addDummyTriggerIds(
5469 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005470 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005471 static const int32_t dummyTriggerId = 1;
5472 status_t res;
5473
Emilian Peevaebbe412018-01-15 13:53:24 +00005474 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005475
5476 // If AF trigger is active, insert a dummy AF trigger ID if none already
5477 // exists
5478 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5479 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5480 if (afTrigger.count > 0 &&
5481 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5482 afId.count == 0) {
5483 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5484 if (res != OK) return res;
5485 }
5486
5487 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5488 // if none already exists
5489 camera_metadata_entry pcTrigger =
5490 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5491 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5492 if (pcTrigger.count > 0 &&
5493 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5494 pcId.count == 0) {
5495 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5496 &dummyTriggerId, 1);
5497 if (res != OK) return res;
5498 }
5499
5500 return OK;
5501}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005502
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005503/**
5504 * PreparerThread inner class methods
5505 */
5506
5507Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005508 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005509 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005510}
5511
5512Camera3Device::PreparerThread::~PreparerThread() {
5513 Thread::requestExitAndWait();
5514 if (mCurrentStream != nullptr) {
5515 mCurrentStream->cancelPrepare();
5516 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5517 mCurrentStream.clear();
5518 }
5519 clear();
5520}
5521
Ruben Brunkc78ac262015-08-13 17:58:46 -07005522status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005523 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005524 status_t res;
5525
5526 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005527 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005528
Ruben Brunkc78ac262015-08-13 17:58:46 -07005529 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005530 if (res == OK) {
5531 // No preparation needed, fire listener right off
5532 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005533 if (listener != NULL) {
5534 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005535 }
5536 return OK;
5537 } else if (res != NOT_ENOUGH_DATA) {
5538 return res;
5539 }
5540
5541 // Need to prepare, start up thread if necessary
5542 if (!mActive) {
5543 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5544 // isn't running
5545 Thread::requestExitAndWait();
5546 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5547 if (res != OK) {
5548 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005549 if (listener != NULL) {
5550 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005551 }
5552 return res;
5553 }
5554 mCancelNow = false;
5555 mActive = true;
5556 ALOGV("%s: Preparer stream started", __FUNCTION__);
5557 }
5558
5559 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005560 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005561 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5562
5563 return OK;
5564}
5565
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005566void Camera3Device::PreparerThread::pause() {
5567 ATRACE_CALL();
5568
5569 Mutex::Autolock l(mLock);
5570
5571 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5572 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5573 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5574 int currentMaxCount = mCurrentMaxCount;
5575 mPendingStreams.clear();
5576 mCancelNow = true;
5577 while (mActive) {
5578 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5579 if (res == TIMED_OUT) {
5580 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5581 return;
5582 } else if (res != OK) {
5583 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5584 return;
5585 }
5586 }
5587
5588 //Check whether the prepare thread was able to complete the current
5589 //stream. In case work is still pending emplace it along with the rest
5590 //of the streams in the pending list.
5591 if (currentStream != nullptr) {
5592 if (!mCurrentPrepareComplete) {
5593 pendingStreams.emplace(currentMaxCount, currentStream);
5594 }
5595 }
5596
5597 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5598 for (const auto& it : mPendingStreams) {
5599 it.second->cancelPrepare();
5600 }
5601}
5602
5603status_t Camera3Device::PreparerThread::resume() {
5604 ATRACE_CALL();
5605 status_t res;
5606
5607 Mutex::Autolock l(mLock);
5608 sp<NotificationListener> listener = mListener.promote();
5609
5610 if (mActive) {
5611 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5612 return NO_INIT;
5613 }
5614
5615 auto it = mPendingStreams.begin();
5616 for (; it != mPendingStreams.end();) {
5617 res = it->second->startPrepare(it->first);
5618 if (res == OK) {
5619 if (listener != NULL) {
5620 listener->notifyPrepared(it->second->getId());
5621 }
5622 it = mPendingStreams.erase(it);
5623 } else if (res != NOT_ENOUGH_DATA) {
5624 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5625 res, strerror(-res));
5626 it = mPendingStreams.erase(it);
5627 } else {
5628 it++;
5629 }
5630 }
5631
5632 if (mPendingStreams.empty()) {
5633 return OK;
5634 }
5635
5636 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5637 if (res != OK) {
5638 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5639 __FUNCTION__, res, strerror(-res));
5640 return res;
5641 }
5642 mCancelNow = false;
5643 mActive = true;
5644 ALOGV("%s: Preparer stream started", __FUNCTION__);
5645
5646 return OK;
5647}
5648
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005649status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005650 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005651 Mutex::Autolock l(mLock);
5652
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005653 for (const auto& it : mPendingStreams) {
5654 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005655 }
5656 mPendingStreams.clear();
5657 mCancelNow = true;
5658
5659 return OK;
5660}
5661
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005662void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005663 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005664 Mutex::Autolock l(mLock);
5665 mListener = listener;
5666}
5667
5668bool Camera3Device::PreparerThread::threadLoop() {
5669 status_t res;
5670 {
5671 Mutex::Autolock l(mLock);
5672 if (mCurrentStream == nullptr) {
5673 // End thread if done with work
5674 if (mPendingStreams.empty()) {
5675 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5676 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5677 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5678 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005679 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005680 return false;
5681 }
5682
5683 // Get next stream to prepare
5684 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005685 mCurrentStream = it->second;
5686 mCurrentMaxCount = it->first;
5687 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005688 mPendingStreams.erase(it);
5689 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5690 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5691 } else if (mCancelNow) {
5692 mCurrentStream->cancelPrepare();
5693 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5694 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5695 mCurrentStream.clear();
5696 mCancelNow = false;
5697 return true;
5698 }
5699 }
5700
5701 res = mCurrentStream->prepareNextBuffer();
5702 if (res == NOT_ENOUGH_DATA) return true;
5703 if (res != OK) {
5704 // Something bad happened; try to recover by cancelling prepare and
5705 // signalling listener anyway
5706 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5707 mCurrentStream->getId(), res, strerror(-res));
5708 mCurrentStream->cancelPrepare();
5709 }
5710
5711 // This stream has finished, notify listener
5712 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005713 sp<NotificationListener> listener = mListener.promote();
5714 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005715 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5716 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005717 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005718 }
5719
5720 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5721 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005722 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005723
5724 return true;
5725}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005726
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005727/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005728 * Static callback forwarding methods from HAL to instance
5729 */
5730
5731void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5732 const camera3_capture_result *result) {
5733 Camera3Device *d =
5734 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005735
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005736 d->processCaptureResult(result);
5737}
5738
5739void Camera3Device::sNotify(const camera3_callback_ops *cb,
5740 const camera3_notify_msg *msg) {
5741 Camera3Device *d =
5742 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5743 d->notify(msg);
5744}
5745
5746}; // namespace android