blob: 9acbf0a22e1bf7251e6762b1ce96927b909d1665 [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),
80 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080081{
82 ATRACE_CALL();
83 camera3_callback_ops::notify = &sNotify;
84 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092 disconnect();
93}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Emilian Peevbd8c5032018-02-14 23:05:40 +000099status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
123 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Yifan Hongf79b5542017-04-11 14:44:25 -0700128 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700129 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
130 [&queue](const auto& descriptor) {
131 queue = std::make_shared<RequestMetadataQueue>(descriptor);
132 if (!queue->isValid() || queue->availableToWrite() <= 0) {
133 ALOGE("HAL returns empty request metadata fmq, not use it");
134 queue = nullptr;
135 // don't use the queue onwards.
136 }
137 });
138 if (!requestQueueRet.isOk()) {
139 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
140 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700141 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700143
144 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700145 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700146 [&resQueue](const auto& descriptor) {
147 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
148 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700149 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700150 resQueue = nullptr;
151 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700152 }
153 });
154 if (!resultQueueRet.isOk()) {
155 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
156 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700157 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700158 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700159 IF_ALOGV() {
160 session->interfaceChain([](
161 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
162 ALOGV("Session interface chain:");
163 for (auto iface : interfaceChain) {
164 ALOGV(" %s", iface.c_str());
165 }
166 });
167 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700168
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700169 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000170 std::string providerType;
171 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000172 mTagMonitor.initialize(mVendorTagId);
173 if (!monitorTags.isEmpty()) {
174 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
175 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176
177 return initializeCommonLocked();
178}
179
180status_t Camera3Device::initializeCommonLocked() {
181
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700182 /** Start up status tracker thread */
183 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800184 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700185 if (res != OK) {
186 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
187 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700189 mStatusTracker.clear();
190 return res;
191 }
192
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700193 /** Register in-flight map to the status tracker */
194 mInFlightStatusId = mStatusTracker->addComponent();
195
Zhijun He125684a2015-12-26 15:07:30 -0800196 /** Create buffer manager */
197 mBufferManager = new Camera3BufferManager();
198
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000199 Vector<int32_t> sessionParamKeys;
200 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
201 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
202 if (sessionKeysEntry.count > 0) {
203 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
204 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700205 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000206 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800207 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800208 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700209 SET_ERR_L("Unable to start request queue thread: %s (%d)",
210 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800211 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800212 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800213 return res;
214 }
215
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700216 mPreparerThread = new PreparerThread();
217
Ruben Brunk183f0562015-08-12 12:55:02 -0700218 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800219 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700220 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700221 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700222 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800223
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800224 // Measure the clock domain offset between camera and video/hw_composer
225 camera_metadata_entry timestampSource =
226 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
227 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
228 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
229 mTimestampOffset = getMonoToBoottimeOffset();
230 }
231
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700232 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100233 camera_metadata_entry partialResultsCount =
234 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
235 if (partialResultsCount.count > 0) {
236 mNumPartialResults = partialResultsCount.data.i32[0];
237 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700238 }
239
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700240 camera_metadata_entry configs =
241 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
242 for (uint32_t i = 0; i < configs.count; i += 4) {
243 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
244 configs.data.i32[i + 3] ==
245 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
246 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
247 configs.data.i32[i + 2]));
248 }
249 }
250
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800251 return OK;
252}
253
254status_t Camera3Device::disconnect() {
255 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800257
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700258 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800259
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700260 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700261 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700262 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 {
264 Mutex::Autolock l(mLock);
265 if (mStatus == STATUS_UNINITIALIZED) return res;
266
267 if (mStatus == STATUS_ACTIVE ||
268 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
269 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700270 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700271 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700272 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700274 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700276 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
277 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 // Continue to close device even in case of error
279 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700280 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800281 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800282
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700283 if (mStatus == STATUS_ERROR) {
284 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700285 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700286
287 if (mStatusTracker != NULL) {
288 mStatusTracker->requestExit();
289 }
290
291 if (mRequestThread != NULL) {
292 mRequestThread->requestExit();
293 }
294
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700295 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
296 for (size_t i = 0; i < mOutputStreams.size(); i++) {
297 streams.push_back(mOutputStreams[i]);
298 }
299 if (mInputStream != nullptr) {
300 streams.push_back(mInputStream);
301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 }
303
304 // Joining done without holding mLock, otherwise deadlocks may ensue
305 // as the threads try to access parent state
306 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
307 // HAL may be in a bad state, so waiting for request thread
308 // (which may be stuck in the HAL processCaptureRequest call)
309 // could be dangerous.
310 mRequestThread->join();
311 }
312
313 if (mStatusTracker != NULL) {
314 mStatusTracker->join();
315 }
316
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800317 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 {
319 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800320 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700321 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800322 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700323 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700325 // Call close without internal mutex held, as the HAL close may need to
326 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800327 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700328
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 flushInflightRequests();
330
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700331 {
332 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800333 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700334 mOutputStreams.clear();
335 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700336 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700337 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700338 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700339 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800340
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700341 for (auto& weakStream : streams) {
342 sp<Camera3StreamInterface> stream = weakStream.promote();
343 if (stream != nullptr) {
344 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
345 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
346 }
347 }
348
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700349 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700350 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800351}
352
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700353// For dumping/debugging only -
354// try to acquire a lock a few times, eventually give up to proceed with
355// debug/dump operations
356bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
357 bool gotLock = false;
358 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
359 if (lock.tryLock() == NO_ERROR) {
360 gotLock = true;
361 break;
362 } else {
363 usleep(kDumpSleepDuration);
364 }
365 }
366 return gotLock;
367}
368
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700369Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
370 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100371 const int STREAM_CONFIGURATION_SIZE = 4;
372 const int STREAM_FORMAT_OFFSET = 0;
373 const int STREAM_WIDTH_OFFSET = 1;
374 const int STREAM_HEIGHT_OFFSET = 2;
375 const int STREAM_IS_INPUT_OFFSET = 3;
376 camera_metadata_ro_entry_t availableStreamConfigs =
377 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
378 if (availableStreamConfigs.count == 0 ||
379 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
380 return Size(0, 0);
381 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700382
Emilian Peev08dd2452017-04-06 16:55:14 +0100383 // Get max jpeg size (area-wise).
384 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
385 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
386 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
387 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
388 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
389 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
390 && format == HAL_PIXEL_FORMAT_BLOB &&
391 (width * height > maxJpegWidth * maxJpegHeight)) {
392 maxJpegWidth = width;
393 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700394 }
395 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100396
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700397 return Size(maxJpegWidth, maxJpegHeight);
398}
399
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800400nsecs_t Camera3Device::getMonoToBoottimeOffset() {
401 // try three times to get the clock offset, choose the one
402 // with the minimum gap in measurements.
403 const int tries = 3;
404 nsecs_t bestGap, measured;
405 for (int i = 0; i < tries; ++i) {
406 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
407 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
408 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
409 const nsecs_t gap = tmono2 - tmono;
410 if (i == 0 || gap < bestGap) {
411 bestGap = gap;
412 measured = tbase - ((tmono + tmono2) >> 1);
413 }
414 }
415 return measured;
416}
417
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800418hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
419 int frameworkFormat) {
420 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
421}
422
423DataspaceFlags Camera3Device::mapToHidlDataspace(
424 android_dataspace dataSpace) {
425 return dataSpace;
426}
427
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700428BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100429 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700430 return usage;
431}
432
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800433StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
434 switch (rotation) {
435 case CAMERA3_STREAM_ROTATION_0:
436 return StreamRotation::ROTATION_0;
437 case CAMERA3_STREAM_ROTATION_90:
438 return StreamRotation::ROTATION_90;
439 case CAMERA3_STREAM_ROTATION_180:
440 return StreamRotation::ROTATION_180;
441 case CAMERA3_STREAM_ROTATION_270:
442 return StreamRotation::ROTATION_270;
443 }
444 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
445 return StreamRotation::ROTATION_0;
446}
447
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800448status_t Camera3Device::mapToStreamConfigurationMode(
449 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
450 if (mode == nullptr) return BAD_VALUE;
451 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
452 switch(operationMode) {
453 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
454 *mode = StreamConfigurationMode::NORMAL_MODE;
455 break;
456 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
457 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
458 break;
459 default:
460 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
461 return BAD_VALUE;
462 }
463 } else {
464 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800465 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800466 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800467}
468
469camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
470 switch (status) {
471 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
472 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
473 }
474 return CAMERA3_BUFFER_STATUS_ERROR;
475}
476
477int Camera3Device::mapToFrameworkFormat(
478 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
479 return static_cast<uint32_t>(pixelFormat);
480}
481
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700482android_dataspace Camera3Device::mapToFrameworkDataspace(
483 DataspaceFlags dataSpace) {
484 return static_cast<android_dataspace>(dataSpace);
485}
486
Emilian Peev050f5dc2017-05-18 14:43:56 +0100487uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700488 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700489 return usage;
490}
491
Emilian Peev050f5dc2017-05-18 14:43:56 +0100492uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700493 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700494 return usage;
495}
496
Zhijun Hef7da0962014-04-24 13:27:56 -0700497ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700498 // Get max jpeg size (area-wise).
499 Size maxJpegResolution = getMaxJpegResolution();
500 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800501 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
502 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700503 return BAD_VALUE;
504 }
505
Zhijun Hef7da0962014-04-24 13:27:56 -0700506 // Get max jpeg buffer size
507 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700508 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
509 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800510 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
511 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700512 return BAD_VALUE;
513 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700514 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800515 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700516
517 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700518 float scaleFactor = ((float) (width * height)) /
519 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800520 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
521 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700522 if (jpegBufferSize > maxJpegBufferSize) {
523 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700524 }
525
526 return jpegBufferSize;
527}
528
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700529ssize_t Camera3Device::getPointCloudBufferSize() const {
530 const int FLOATS_PER_POINT=4;
531 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
532 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
534 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700535 return BAD_VALUE;
536 }
537 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
538 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
539 return maxBytesForPointCloud;
540}
541
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800542ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800543 const int PER_CONFIGURATION_SIZE = 3;
544 const int WIDTH_OFFSET = 0;
545 const int HEIGHT_OFFSET = 1;
546 const int SIZE_OFFSET = 2;
547 camera_metadata_ro_entry rawOpaqueSizes =
548 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800549 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800550 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
552 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800553 return BAD_VALUE;
554 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700555
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800556 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
557 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
558 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
559 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
560 }
561 }
562
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800563 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
564 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800565 return BAD_VALUE;
566}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700567
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800568status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
569 ATRACE_CALL();
570 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700571
572 // Try to lock, but continue in case of failure (to avoid blocking in
573 // deadlocks)
574 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
575 bool gotLock = tryLockSpinRightRound(mLock);
576
577 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800578 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
579 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700580 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
582 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700583
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800584 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700585
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 String16 templatesOption("-t");
587 int n = args.size();
588 for (int i = 0; i < n; i++) {
589 if (args[i] == templatesOption) {
590 dumpTemplates = true;
591 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000592 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700593 if (i + 1 < n) {
594 String8 monitorTags = String8(args[i + 1]);
595 if (monitorTags == "off") {
596 mTagMonitor.disableMonitoring();
597 } else {
598 mTagMonitor.parseTagsToMonitor(monitorTags);
599 }
600 } else {
601 mTagMonitor.disableMonitoring();
602 }
603 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800604 }
605
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800606 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800607
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800608 const char *status =
609 mStatus == STATUS_ERROR ? "ERROR" :
610 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700611 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
612 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800613 mStatus == STATUS_ACTIVE ? "ACTIVE" :
614 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700615
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800616 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700617 if (mStatus == STATUS_ERROR) {
618 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
619 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800620 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800621 const char *mode =
622 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
623 mOperatingMode == static_cast<int>(
624 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
625 "CUSTOM";
626 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800627
628 if (mInputStream != NULL) {
629 write(fd, lines.string(), lines.size());
630 mInputStream->dump(fd, args);
631 } else {
632 lines.appendFormat(" No input stream.\n");
633 write(fd, lines.string(), lines.size());
634 }
635 for (size_t i = 0; i < mOutputStreams.size(); i++) {
636 mOutputStreams[i]->dump(fd,args);
637 }
638
Zhijun He431503c2016-03-07 17:30:16 -0800639 if (mBufferManager != NULL) {
640 lines = String8(" Camera3 Buffer Manager:\n");
641 write(fd, lines.string(), lines.size());
642 mBufferManager->dump(fd, args);
643 }
Zhijun He125684a2015-12-26 15:07:30 -0800644
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700645 lines = String8(" In-flight requests:\n");
646 if (mInFlightMap.size() == 0) {
647 lines.append(" None\n");
648 } else {
649 for (size_t i = 0; i < mInFlightMap.size(); i++) {
650 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700651 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700652 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800653 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700654 r.numBuffersLeft);
655 }
656 }
657 write(fd, lines.string(), lines.size());
658
Shuzhen Wang686f6442017-06-20 16:16:04 -0700659 if (mRequestThread != NULL) {
660 mRequestThread->dumpCaptureRequestLatency(fd,
661 " ProcessCaptureRequest latency histogram:");
662 }
663
Igor Murashkin1e479c02013-09-06 16:55:14 -0700664 {
665 lines = String8(" Last request sent:\n");
666 write(fd, lines.string(), lines.size());
667
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700668 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700669 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
670 }
671
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800672 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800673 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800674 "TEMPLATE_PREVIEW",
675 "TEMPLATE_STILL_CAPTURE",
676 "TEMPLATE_VIDEO_RECORD",
677 "TEMPLATE_VIDEO_SNAPSHOT",
678 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800679 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800680 };
681
682 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800683 camera_metadata_t *templateRequest = nullptr;
684 mInterface->constructDefaultRequestSettings(
685 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800686 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800687 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800688 lines.append(" Not supported\n");
689 write(fd, lines.string(), lines.size());
690 } else {
691 write(fd, lines.string(), lines.size());
692 dump_indented_camera_metadata(templateRequest,
693 fd, /*verbosity*/2, /*indentation*/8);
694 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800695 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800696 }
697 }
698
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700699 mTagMonitor.dumpMonitoredMetadata(fd);
700
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800701 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800702 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800704 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800705 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800706
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700707 if (gotLock) mLock.unlock();
708 if (gotInterfaceLock) mInterfaceLock.unlock();
709
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800710 return OK;
711}
712
713const CameraMetadata& Camera3Device::info() const {
714 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
716 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700717 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800718 mStatus == STATUS_ERROR ?
719 "when in error state" : "before init");
720 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800721 return mDeviceInfo;
722}
723
Jianing Wei90e59c92014-03-12 18:29:36 -0700724status_t Camera3Device::checkStatusOkToCaptureLocked() {
725 switch (mStatus) {
726 case STATUS_ERROR:
727 CLOGE("Device has encountered a serious error");
728 return INVALID_OPERATION;
729 case STATUS_UNINITIALIZED:
730 CLOGE("Device not initialized");
731 return INVALID_OPERATION;
732 case STATUS_UNCONFIGURED:
733 case STATUS_CONFIGURED:
734 case STATUS_ACTIVE:
735 // OK
736 break;
737 default:
738 SET_ERR_L("Unexpected status: %d", mStatus);
739 return INVALID_OPERATION;
740 }
741 return OK;
742}
743
744status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000745 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 const std::list<const SurfaceMap> &surfaceMaps,
747 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700748 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700749 if (requestList == NULL) {
750 CLOGE("requestList cannot be NULL.");
751 return BAD_VALUE;
752 }
753
Jianing Weicb0652e2014-03-12 18:29:36 -0700754 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000755 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
757 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
758 ++metadataIt, ++surfaceMapIt) {
759 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700760 if (newRequest == 0) {
761 CLOGE("Can't create capture request");
762 return BAD_VALUE;
763 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700764
Shuzhen Wang9d066012016-09-30 11:30:20 -0700765 newRequest->mRepeating = repeating;
766
Jianing Weicb0652e2014-03-12 18:29:36 -0700767 // Setup burst Id and request Id
768 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000769 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
770 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700771 CLOGE("RequestID entry exists; but must not be empty in metadata");
772 return BAD_VALUE;
773 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000774 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
775 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700776 } else {
777 CLOGE("RequestID does not exist in metadata");
778 return BAD_VALUE;
779 }
780
Jianing Wei90e59c92014-03-12 18:29:36 -0700781 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700782
783 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700784 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
786 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
787 return BAD_VALUE;
788 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700789
790 // Setup batch size if this is a high speed video recording request.
791 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
792 auto firstRequest = requestList->begin();
793 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
794 if (outputStream->isVideoStream()) {
795 (*firstRequest)->mBatchSize = requestList->size();
796 break;
797 }
798 }
799 }
800
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 return OK;
802}
803
Jianing Weicb0652e2014-03-12 18:29:36 -0700804status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800805 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806
Emilian Peevaebbe412018-01-15 13:53:24 +0000807 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700808 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000809 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700810
Emilian Peevaebbe412018-01-15 13:53:24 +0000811 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700812}
813
Emilian Peevaebbe412018-01-15 13:53:24 +0000814void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700815 std::list<const SurfaceMap>& surfaceMaps,
816 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000817 PhysicalCameraSettingsList requestList;
818 requestList.push_back({std::string(getId().string()), request});
819 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820
821 SurfaceMap surfaceMap;
822 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
823 // With no surface list passed in, stream and surface will have 1-to-1
824 // mapping. So the surface index is 0 for each stream in the surfaceMap.
825 for (size_t i = 0; i < streams.count; i++) {
826 surfaceMap[streams.data.i32[i]].push_back(0);
827 }
828 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800829}
830
Jianing Wei90e59c92014-03-12 18:29:36 -0700831status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000832 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700833 const std::list<const SurfaceMap> &surfaceMaps,
834 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700835 /*out*/
836 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700837 ATRACE_CALL();
838 Mutex::Autolock il(mInterfaceLock);
839 Mutex::Autolock l(mLock);
840
841 status_t res = checkStatusOkToCaptureLocked();
842 if (res != OK) {
843 // error logged by previous call
844 return res;
845 }
846
847 RequestList requestList;
848
Shuzhen Wang0129d522016-10-30 22:43:41 -0700849 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
850 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 if (res != OK) {
852 // error logged by previous call
853 return res;
854 }
855
856 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700857 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700858 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700859 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700860 }
861
862 if (res == OK) {
863 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
864 if (res != OK) {
865 SET_ERR_L("Can't transition to active in %f seconds!",
866 kActiveTimeout/1e9);
867 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800868 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700869 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 } else {
871 CLOGE("Cannot queue request. Impossible.");
872 return BAD_VALUE;
873 }
874
875 return res;
876}
877
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800878hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800879 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800880 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700881 // Ideally we should grab mLock, but that can lead to deadlock, and
882 // it's not super important to get up to date value of mStatus for this
883 // warning print, hence skipping the lock here
884 if (mStatus == STATUS_ERROR) {
885 // Per API contract, HAL should act as closed after device error
886 // But mStatus can be set to error by framework as well, so just log
887 // a warning here.
888 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700889 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700890
891 if (mProcessCaptureResultLock.tryLock() != OK) {
892 // This should never happen; it indicates a wrong client implementation
893 // that doesn't follow the contract. But, we can be tolerant here.
894 ALOGE("%s: callback overlapped! waiting 1s...",
895 __FUNCTION__);
896 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
897 ALOGE("%s: cannot acquire lock in 1s, dropping results",
898 __FUNCTION__);
899 // really don't know what to do, so bail out.
900 return hardware::Void();
901 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800902 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700903 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800904 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700905 }
906 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800907 return hardware::Void();
908}
909
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800910// Only one processCaptureResult should be called at a time, so
911// the locks won't block. The locks are present here simply to enforce this.
912hardware::Return<void> Camera3Device::processCaptureResult(
913 const hardware::hidl_vec<
914 hardware::camera::device::V3_2::CaptureResult>& results) {
915 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
916
917 // Ideally we should grab mLock, but that can lead to deadlock, and
918 // it's not super important to get up to date value of mStatus for this
919 // warning print, hence skipping the lock here
920 if (mStatus == STATUS_ERROR) {
921 // Per API contract, HAL should act as closed after device error
922 // But mStatus can be set to error by framework as well, so just log
923 // a warning here.
924 ALOGW("%s: received capture result in error state.", __FUNCTION__);
925 }
926
927 if (mProcessCaptureResultLock.tryLock() != OK) {
928 // This should never happen; it indicates a wrong client implementation
929 // that doesn't follow the contract. But, we can be tolerant here.
930 ALOGE("%s: callback overlapped! waiting 1s...",
931 __FUNCTION__);
932 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
933 ALOGE("%s: cannot acquire lock in 1s, dropping results",
934 __FUNCTION__);
935 // really don't know what to do, so bail out.
936 return hardware::Void();
937 }
938 }
939 for (const auto& result : results) {
940 processOneCaptureResultLocked(result, noPhysMetadata);
941 }
942 mProcessCaptureResultLock.unlock();
943 return hardware::Void();
944}
945
946status_t Camera3Device::readOneCameraMetadataLocked(
947 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
948 const hardware::camera::device::V3_2::CameraMetadata& result) {
949 if (fmqResultSize > 0) {
950 resultMetadata.resize(fmqResultSize);
951 if (mResultMetadataQueue == nullptr) {
952 return NO_MEMORY; // logged in initialize()
953 }
954 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
955 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
956 __FUNCTION__, fmqResultSize);
957 return INVALID_OPERATION;
958 }
959 } else {
960 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
961 result.size());
962 }
963
964 if (resultMetadata.size() != 0) {
965 status_t res;
966 const camera_metadata_t* metadata =
967 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
968 size_t expected_metadata_size = resultMetadata.size();
969 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
970 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
971 __FUNCTION__, strerror(-res), res);
972 return INVALID_OPERATION;
973 }
974 }
975
976 return OK;
977}
978
Yifan Honga640c5a2017-04-12 16:30:31 -0700979void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800980 const hardware::camera::device::V3_2::CaptureResult& result,
981 const hardware::hidl_vec<
982 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800983 camera3_capture_result r;
984 status_t res;
985 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700986
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800987 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -0700988 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800989 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
990 if (res != OK) {
991 ALOGE("%s: Frame %d: Failed to read capture result metadata",
992 __FUNCTION__, result.frameNumber);
993 return;
Yifan Honga640c5a2017-04-12 16:30:31 -0700994 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800995 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -0700996
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800997 // Read and validate physical camera metadata
998 size_t physResultCount = physicalCameraMetadatas.size();
999 std::vector<const char*> physCamIds(physResultCount);
1000 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1001 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1002 physResultMetadata.resize(physResultCount);
1003 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1004 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1005 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1006 if (res != OK) {
1007 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1008 __FUNCTION__, result.frameNumber,
1009 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001010 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001011 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001012 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1013 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1014 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001015 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001016 r.num_physcam_metadata = physResultCount;
1017 r.physcam_ids = physCamIds.data();
1018 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001019
1020 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1021 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1022 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1023 auto& bDst = outputBuffers[i];
1024 const StreamBuffer &bSrc = result.outputBuffers[i];
1025
1026 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001027 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001028 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1029 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001030 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001031 }
1032 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1033
1034 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001035 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001036 if (res != OK) {
1037 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %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.buffer = buffer;
1042 bDst.status = mapHidlBufferStatus(bSrc.status);
1043 bDst.acquire_fence = -1;
1044 if (bSrc.releaseFence == nullptr) {
1045 bDst.release_fence = -1;
1046 } else if (bSrc.releaseFence->numFds == 1) {
1047 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1048 } else {
1049 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1050 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001051 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001052 }
1053 }
1054 r.num_output_buffers = outputBuffers.size();
1055 r.output_buffers = outputBuffers.data();
1056
1057 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001058 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001059 r.input_buffer = nullptr;
1060 } else {
1061 if (mInputStream->getId() != result.inputBuffer.streamId) {
1062 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1063 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001064 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001065 }
1066 inputBuffer.stream = mInputStream->asHalStream();
1067 buffer_handle_t *buffer;
1068 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1069 &buffer);
1070 if (res != OK) {
1071 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1072 __FUNCTION__, 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.buffer = buffer;
1076 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1077 inputBuffer.acquire_fence = -1;
1078 if (result.inputBuffer.releaseFence == nullptr) {
1079 inputBuffer.release_fence = -1;
1080 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1081 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1082 } else {
1083 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1084 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001085 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001086 }
1087 r.input_buffer = &inputBuffer;
1088 }
1089
1090 r.partial_result = result.partialResult;
1091
1092 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001093}
1094
1095hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001096 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001097 // Ideally we should grab mLock, but that can lead to deadlock, and
1098 // it's not super important to get up to date value of mStatus for this
1099 // warning print, hence skipping the lock here
1100 if (mStatus == STATUS_ERROR) {
1101 // Per API contract, HAL should act as closed after device error
1102 // But mStatus can be set to error by framework as well, so just log
1103 // a warning here.
1104 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001105 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001106
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001107 for (const auto& msg : msgs) {
1108 notify(msg);
1109 }
1110 return hardware::Void();
1111}
1112
1113void Camera3Device::notify(
1114 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001116 camera3_notify_msg m;
1117 switch (msg.type) {
1118 case MsgType::ERROR:
1119 m.type = CAMERA3_MSG_ERROR;
1120 m.message.error.frame_number = msg.msg.error.frameNumber;
1121 if (msg.msg.error.errorStreamId >= 0) {
1122 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001123 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001124 ALOGE("%s: Frame %d: Invalid error stream id %d",
1125 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001126 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001127 }
1128 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1129 } else {
1130 m.message.error.error_stream = nullptr;
1131 }
1132 switch (msg.msg.error.errorCode) {
1133 case ErrorCode::ERROR_DEVICE:
1134 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1135 break;
1136 case ErrorCode::ERROR_REQUEST:
1137 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1138 break;
1139 case ErrorCode::ERROR_RESULT:
1140 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1141 break;
1142 case ErrorCode::ERROR_BUFFER:
1143 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1144 break;
1145 }
1146 break;
1147 case MsgType::SHUTTER:
1148 m.type = CAMERA3_MSG_SHUTTER;
1149 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1150 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1151 break;
1152 }
1153 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001154}
1155
Emilian Peevaebbe412018-01-15 13:53:24 +00001156status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001157 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001158 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001159 ATRACE_CALL();
1160
Emilian Peevaebbe412018-01-15 13:53:24 +00001161 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001162}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001163
Jianing Weicb0652e2014-03-12 18:29:36 -07001164status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1165 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001166 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001167
Emilian Peevaebbe412018-01-15 13:53:24 +00001168 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001169 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001170 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171
Emilian Peevaebbe412018-01-15 13:53:24 +00001172 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001173 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174}
1175
Emilian Peevaebbe412018-01-15 13:53:24 +00001176status_t Camera3Device::setStreamingRequestList(
1177 const List<const PhysicalCameraSettingsList> &requestsList,
1178 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001179 ATRACE_CALL();
1180
Emilian Peevaebbe412018-01-15 13:53:24 +00001181 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001182}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183
1184sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001185 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 status_t res;
1187
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001188 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001189 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1190 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001191 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1192 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001193 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001195 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001197 } else if (mStatus == STATUS_UNCONFIGURED) {
1198 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 CLOGE("No streams configured");
1200 return NULL;
1201 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 }
1203
Shuzhen Wang0129d522016-10-30 22:43:41 -07001204 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206}
1207
Jianing Weicb0652e2014-03-12 18:29:36 -07001208status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 switch (mStatus) {
1214 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001215 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return INVALID_OPERATION;
1217 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 case STATUS_UNCONFIGURED:
1221 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 case STATUS_ACTIVE:
1223 // OK
1224 break;
1225 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001226 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 return INVALID_OPERATION;
1228 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001229 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001230
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001231 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001232}
1233
1234status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1235 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001238 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001239}
1240
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001241status_t Camera3Device::createInputStream(
1242 uint32_t width, uint32_t height, int format, int *id) {
1243 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001245 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001246 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001247 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1248 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001249
1250 status_t res;
1251 bool wasActive = false;
1252
1253 switch (mStatus) {
1254 case STATUS_ERROR:
1255 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1256 return INVALID_OPERATION;
1257 case STATUS_UNINITIALIZED:
1258 ALOGE("%s: Device not initialized", __FUNCTION__);
1259 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001260 case STATUS_UNCONFIGURED:
1261 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001262 // OK
1263 break;
1264 case STATUS_ACTIVE:
1265 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001266 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001267 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001268 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001269 return res;
1270 }
1271 wasActive = true;
1272 break;
1273 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275 return INVALID_OPERATION;
1276 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001278
1279 if (mInputStream != 0) {
1280 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1281 return INVALID_OPERATION;
1282 }
1283
1284 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1285 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287
1288 mInputStream = newStream;
1289
1290 *id = mNextStreamId++;
1291
1292 // Continue captures if active at start
1293 if (wasActive) {
1294 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001295 // Reuse current operating mode and session parameters for new stream config
1296 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001297 if (res != OK) {
1298 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1299 __FUNCTION__, mNextStreamId, strerror(-res), res);
1300 return res;
1301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001302 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303 }
1304
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001305 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 return OK;
1307}
1308
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001309status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001310 uint32_t width, uint32_t height, int format,
1311 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001312 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001313 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001314 ATRACE_CALL();
1315
1316 if (consumer == nullptr) {
1317 ALOGE("%s: consumer must not be null", __FUNCTION__);
1318 return BAD_VALUE;
1319 }
1320
1321 std::vector<sp<Surface>> consumers;
1322 consumers.push_back(consumer);
1323
1324 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001325 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1326 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001327}
1328
1329status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1330 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1331 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001332 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001333 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001334 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001335
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001336 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001337 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001339 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001340 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1341 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1342 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001343
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001344 status_t res;
1345 bool wasActive = false;
1346
1347 switch (mStatus) {
1348 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001349 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350 return INVALID_OPERATION;
1351 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001352 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001354 case STATUS_UNCONFIGURED:
1355 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 // OK
1357 break;
1358 case STATUS_ACTIVE:
1359 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001360 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001362 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 return res;
1364 }
1365 wasActive = true;
1366 break;
1367 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001368 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 return INVALID_OPERATION;
1370 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001371 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372
1373 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001374
Shuzhen Wang0129d522016-10-30 22:43:41 -07001375 if (consumers.size() == 0 && !hasDeferredConsumer) {
1376 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1377 return BAD_VALUE;
1378 }
Zhijun He5d677d12016-05-29 16:52:39 -07001379
Shuzhen Wang0129d522016-10-30 22:43:41 -07001380 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001381 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1382 return BAD_VALUE;
1383 }
1384
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001386 ssize_t blobBufferSize;
1387 if (dataSpace != HAL_DATASPACE_DEPTH) {
1388 blobBufferSize = getJpegBufferSize(width, height);
1389 if (blobBufferSize <= 0) {
1390 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1391 return BAD_VALUE;
1392 }
1393 } else {
1394 blobBufferSize = getPointCloudBufferSize();
1395 if (blobBufferSize <= 0) {
1396 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1397 return BAD_VALUE;
1398 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001399 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001400 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001401 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001402 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001403 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1404 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1405 if (rawOpaqueBufferSize <= 0) {
1406 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1407 return BAD_VALUE;
1408 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001409 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001410 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001411 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001412 } else if (isShared) {
1413 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1414 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001415 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001416 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001417 newStream = new Camera3OutputStream(mNextStreamId,
1418 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001419 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001421 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001422 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001423 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 }
Emilian Peev40ead602017-09-26 15:46:36 +01001425
1426 size_t consumerCount = consumers.size();
1427 for (size_t i = 0; i < consumerCount; i++) {
1428 int id = newStream->getSurfaceId(consumers[i]);
1429 if (id < 0) {
1430 SET_ERR_L("Invalid surface id");
1431 return BAD_VALUE;
1432 }
1433 if (surfaceIds != nullptr) {
1434 surfaceIds->push_back(id);
1435 }
1436 }
1437
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001438 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439
Emilian Peev08dd2452017-04-06 16:55:14 +01001440 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001441
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001442 res = mOutputStreams.add(mNextStreamId, newStream);
1443 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001444 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 return res;
1446 }
1447
1448 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001449 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450
1451 // Continue captures if active at start
1452 if (wasActive) {
1453 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001454 // Reuse current operating mode and session parameters for new stream config
1455 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001457 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1458 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 return res;
1460 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001463 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001465}
1466
Emilian Peev710c1422017-08-30 11:19:38 +01001467status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001468 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001469 if (nullptr == streamInfo) {
1470 return BAD_VALUE;
1471 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001472 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 switch (mStatus) {
1476 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001477 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 return INVALID_OPERATION;
1479 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001480 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 case STATUS_UNCONFIGURED:
1483 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 case STATUS_ACTIVE:
1485 // OK
1486 break;
1487 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001488 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 return INVALID_OPERATION;
1490 }
1491
1492 ssize_t idx = mOutputStreams.indexOfKey(id);
1493 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001494 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 return idx;
1496 }
1497
Emilian Peev710c1422017-08-30 11:19:38 +01001498 streamInfo->width = mOutputStreams[idx]->getWidth();
1499 streamInfo->height = mOutputStreams[idx]->getHeight();
1500 streamInfo->format = mOutputStreams[idx]->getFormat();
1501 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1502 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1503 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001504 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1505 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507}
1508
1509status_t Camera3Device::setStreamTransform(int id,
1510 int transform) {
1511 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001512 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 switch (mStatus) {
1516 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001517 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 return INVALID_OPERATION;
1519 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 case STATUS_UNCONFIGURED:
1523 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 case STATUS_ACTIVE:
1525 // OK
1526 break;
1527 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001528 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 return INVALID_OPERATION;
1530 }
1531
1532 ssize_t idx = mOutputStreams.indexOfKey(id);
1533 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001534 CLOGE("Stream %d does not exist",
1535 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 return BAD_VALUE;
1537 }
1538
1539 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540}
1541
1542status_t Camera3Device::deleteStream(int id) {
1543 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 Mutex::Autolock l(mLock);
1546 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001548 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001549
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 // CameraDevice semantics require device to already be idle before
1551 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001553 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001554 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 }
1556
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001557 if (mStatus == STATUS_ERROR) {
1558 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1559 __FUNCTION__, mId.string());
1560 return -EBUSY;
1561 }
1562
Igor Murashkin2fba5842013-04-22 14:03:54 -07001563 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001564 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 if (mInputStream != NULL && id == mInputStream->getId()) {
1566 deletedStream = mInputStream;
1567 mInputStream.clear();
1568 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001569 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001570 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 return BAD_VALUE;
1572 }
Zhijun He5f446352014-01-22 09:49:33 -08001573 }
1574
1575 // Delete output stream or the output part of a bi-directional stream.
1576 if (outputStreamIdx != NAME_NOT_FOUND) {
1577 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 mOutputStreams.removeItem(id);
1579 }
1580
1581 // Free up the stream endpoint so that it can be used by some other stream
1582 res = deletedStream->disconnect();
1583 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001584 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 // fall through since we want to still list the stream as deleted.
1586 }
1587 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001588 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589
1590 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001591}
1592
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001593status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001594 ATRACE_CALL();
1595 ALOGV("%s: E", __FUNCTION__);
1596
1597 Mutex::Autolock il(mInterfaceLock);
1598 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001599
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001600 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1601}
1602
1603status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1604 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001605 //Filter out any incoming session parameters
1606 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001607 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1608 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001609 CameraMetadata filteredParams(availableSessionKeys.count);
1610 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1611 filteredParams.getAndLock());
1612 set_camera_metadata_vendor_id(meta, mVendorTagId);
1613 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001614 if (availableSessionKeys.count > 0) {
1615 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1616 camera_metadata_ro_entry entry = params.find(
1617 availableSessionKeys.data.i32[i]);
1618 if (entry.count > 0) {
1619 filteredParams.update(entry);
1620 }
1621 }
1622 }
1623
1624 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001625}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001627status_t Camera3Device::getInputBufferProducer(
1628 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001629 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001630 Mutex::Autolock il(mInterfaceLock);
1631 Mutex::Autolock l(mLock);
1632
1633 if (producer == NULL) {
1634 return BAD_VALUE;
1635 } else if (mInputStream == NULL) {
1636 return INVALID_OPERATION;
1637 }
1638
1639 return mInputStream->getInputBufferProducer(producer);
1640}
1641
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642status_t Camera3Device::createDefaultRequest(int templateId,
1643 CameraMetadata *request) {
1644 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001645 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001646
1647 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1648 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1649 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1650 return BAD_VALUE;
1651 }
1652
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001653 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001654
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001655 {
1656 Mutex::Autolock l(mLock);
1657 switch (mStatus) {
1658 case STATUS_ERROR:
1659 CLOGE("Device has encountered a serious error");
1660 return INVALID_OPERATION;
1661 case STATUS_UNINITIALIZED:
1662 CLOGE("Device is not initialized!");
1663 return INVALID_OPERATION;
1664 case STATUS_UNCONFIGURED:
1665 case STATUS_CONFIGURED:
1666 case STATUS_ACTIVE:
1667 // OK
1668 break;
1669 default:
1670 SET_ERR_L("Unexpected status: %d", mStatus);
1671 return INVALID_OPERATION;
1672 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001674 if (!mRequestTemplateCache[templateId].isEmpty()) {
1675 *request = mRequestTemplateCache[templateId];
1676 return OK;
1677 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001678 }
1679
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001680 camera_metadata_t *rawRequest;
1681 status_t res = mInterface->constructDefaultRequestSettings(
1682 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001683
1684 {
1685 Mutex::Autolock l(mLock);
1686 if (res == BAD_VALUE) {
1687 ALOGI("%s: template %d is not supported on this camera device",
1688 __FUNCTION__, templateId);
1689 return res;
1690 } else if (res != OK) {
1691 CLOGE("Unable to construct request template %d: %s (%d)",
1692 templateId, strerror(-res), res);
1693 return res;
1694 }
1695
1696 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1697 mRequestTemplateCache[templateId].acquire(rawRequest);
1698
1699 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001700 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001701 return OK;
1702}
1703
1704status_t Camera3Device::waitUntilDrained() {
1705 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001707 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001708 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001709
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001711}
1712
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001713status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001714 switch (mStatus) {
1715 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001716 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001717 ALOGV("%s: Already idle", __FUNCTION__);
1718 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001719 case STATUS_CONFIGURED:
1720 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001721 case STATUS_ERROR:
1722 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001723 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001724 break;
1725 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001726 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001727 return INVALID_OPERATION;
1728 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001729 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1730 maxExpectedDuration);
1731 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001732 if (res != OK) {
1733 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1734 res);
1735 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001736 return res;
1737}
1738
Ruben Brunk183f0562015-08-12 12:55:02 -07001739
1740void Camera3Device::internalUpdateStatusLocked(Status status) {
1741 mStatus = status;
1742 mRecentStatusUpdates.add(mStatus);
1743 mStatusChanged.broadcast();
1744}
1745
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001746void Camera3Device::pauseStateNotify(bool enable) {
1747 Mutex::Autolock il(mInterfaceLock);
1748 Mutex::Autolock l(mLock);
1749
1750 mPauseStateNotify = enable;
1751}
1752
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001753// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001754status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001755 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001757 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1758 maxExpectedDuration);
1759 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 if (res != OK) {
1761 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001762 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001763 }
1764
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001765 return res;
1766}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768// Resume after internalPauseAndWaitLocked
1769status_t Camera3Device::internalResumeLocked() {
1770 status_t res;
1771
1772 mRequestThread->setPaused(false);
1773
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001774 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1775 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1777 if (res != OK) {
1778 SET_ERR_L("Can't transition to active in %f seconds!",
1779 kActiveTimeout/1e9);
1780 }
1781 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001782 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783}
1784
Ruben Brunk183f0562015-08-12 12:55:02 -07001785status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001786 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001787
1788 size_t startIndex = 0;
1789 if (mStatusWaiters == 0) {
1790 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1791 // this status list
1792 mRecentStatusUpdates.clear();
1793 } else {
1794 // If other threads are waiting on updates to this status list, set the position of the
1795 // first element that this list will check rather than clearing the list.
1796 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001797 }
1798
Ruben Brunk183f0562015-08-12 12:55:02 -07001799 mStatusWaiters++;
1800
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001801 bool stateSeen = false;
1802 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001803 if (active == (mStatus == STATUS_ACTIVE)) {
1804 // Desired state is current
1805 break;
1806 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807
1808 res = mStatusChanged.waitRelative(mLock, timeout);
1809 if (res != OK) break;
1810
Ruben Brunk183f0562015-08-12 12:55:02 -07001811 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1812 // transitions.
1813 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1814 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1815 __FUNCTION__);
1816
1817 // Encountered desired state since we began waiting
1818 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001819 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1820 stateSeen = true;
1821 break;
1822 }
1823 }
1824 } while (!stateSeen);
1825
Ruben Brunk183f0562015-08-12 12:55:02 -07001826 mStatusWaiters--;
1827
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 return res;
1829}
1830
1831
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001832status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001833 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001834 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001835
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001836 if (listener != NULL && mListener != NULL) {
1837 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1838 }
1839 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001840 mRequestThread->setNotificationListener(listener);
1841 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001842
1843 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001844}
1845
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001846bool Camera3Device::willNotify3A() {
1847 return false;
1848}
1849
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001850status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001851 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001852 status_t res;
1853 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001854
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001855 while (mResultQueue.empty()) {
1856 res = mResultSignal.waitRelative(mOutputLock, timeout);
1857 if (res == TIMED_OUT) {
1858 return res;
1859 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001860 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1861 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001862 return res;
1863 }
1864 }
1865 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001866}
1867
Jianing Weicb0652e2014-03-12 18:29:36 -07001868status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001869 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001870 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001871
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001872 if (mResultQueue.empty()) {
1873 return NOT_ENOUGH_DATA;
1874 }
1875
Jianing Weicb0652e2014-03-12 18:29:36 -07001876 if (frame == NULL) {
1877 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1878 return BAD_VALUE;
1879 }
1880
1881 CaptureResult &result = *(mResultQueue.begin());
1882 frame->mResultExtras = result.mResultExtras;
1883 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001884 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001885 mResultQueue.erase(mResultQueue.begin());
1886
1887 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001888}
1889
1890status_t Camera3Device::triggerAutofocus(uint32_t id) {
1891 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001894 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1895 // Mix-in this trigger into the next request and only the next request.
1896 RequestTrigger trigger[] = {
1897 {
1898 ANDROID_CONTROL_AF_TRIGGER,
1899 ANDROID_CONTROL_AF_TRIGGER_START
1900 },
1901 {
1902 ANDROID_CONTROL_AF_TRIGGER_ID,
1903 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001904 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001905 };
1906
1907 return mRequestThread->queueTrigger(trigger,
1908 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001909}
1910
1911status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1912 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001915 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1916 // Mix-in this trigger into the next request and only the next request.
1917 RequestTrigger trigger[] = {
1918 {
1919 ANDROID_CONTROL_AF_TRIGGER,
1920 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1921 },
1922 {
1923 ANDROID_CONTROL_AF_TRIGGER_ID,
1924 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001925 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001926 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001928 return mRequestThread->queueTrigger(trigger,
1929 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001930}
1931
1932status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1933 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001934 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001935
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001936 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1937 // Mix-in this trigger into the next request and only the next request.
1938 RequestTrigger trigger[] = {
1939 {
1940 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1941 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1942 },
1943 {
1944 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1945 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001946 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001947 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001948
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001949 return mRequestThread->queueTrigger(trigger,
1950 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951}
1952
Jianing Weicb0652e2014-03-12 18:29:36 -07001953status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001954 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001955 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001956 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001957
Zhijun He7ef20392014-04-21 16:04:17 -07001958 {
1959 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001960 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001961 }
1962
Emilian Peev08dd2452017-04-06 16:55:14 +01001963 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001964}
1965
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001966status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001967 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1968}
1969
1970status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001971 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001972 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001973 Mutex::Autolock il(mInterfaceLock);
1974 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001975
1976 sp<Camera3StreamInterface> stream;
1977 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1978 if (outputStreamIdx == NAME_NOT_FOUND) {
1979 CLOGE("Stream %d does not exist", streamId);
1980 return BAD_VALUE;
1981 }
1982
1983 stream = mOutputStreams.editValueAt(outputStreamIdx);
1984
1985 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001986 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001987 return BAD_VALUE;
1988 }
1989
1990 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001991 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001992 return BAD_VALUE;
1993 }
1994
Ruben Brunkc78ac262015-08-13 17:58:46 -07001995 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001996}
1997
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001998status_t Camera3Device::tearDown(int streamId) {
1999 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002000 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002001 Mutex::Autolock il(mInterfaceLock);
2002 Mutex::Autolock l(mLock);
2003
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002004 sp<Camera3StreamInterface> stream;
2005 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2006 if (outputStreamIdx == NAME_NOT_FOUND) {
2007 CLOGE("Stream %d does not exist", streamId);
2008 return BAD_VALUE;
2009 }
2010
2011 stream = mOutputStreams.editValueAt(outputStreamIdx);
2012
2013 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2014 CLOGE("Stream %d is a target of a in-progress request", streamId);
2015 return BAD_VALUE;
2016 }
2017
2018 return stream->tearDown();
2019}
2020
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002021status_t Camera3Device::addBufferListenerForStream(int streamId,
2022 wp<Camera3StreamBufferListener> listener) {
2023 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002024 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
2027
2028 sp<Camera3StreamInterface> stream;
2029 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2030 if (outputStreamIdx == NAME_NOT_FOUND) {
2031 CLOGE("Stream %d does not exist", streamId);
2032 return BAD_VALUE;
2033 }
2034
2035 stream = mOutputStreams.editValueAt(outputStreamIdx);
2036 stream->addBufferListener(listener);
2037
2038 return OK;
2039}
2040
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002042 * Methods called by subclasses
2043 */
2044
2045void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002046 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002047 {
2048 // Need mLock to safely update state and synchronize to current
2049 // state of methods in flight.
2050 Mutex::Autolock l(mLock);
2051 // We can get various system-idle notices from the status tracker
2052 // while starting up. Only care about them if we've actually sent
2053 // in some requests recently.
2054 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2055 return;
2056 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002057 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2058 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002059 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002060
2061 // Skip notifying listener if we're doing some user-transparent
2062 // state changes
2063 if (mPauseStateNotify) return;
2064 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002065
2066 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002067 {
2068 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002069 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002070 }
2071 if (idle && listener != NULL) {
2072 listener->notifyIdle();
2073 }
2074}
2075
Shuzhen Wang758c2152017-01-10 18:26:18 -08002076status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002077 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002078 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002079 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2080 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002081
2082 if (surfaceIds == nullptr) {
2083 return BAD_VALUE;
2084 }
2085
Zhijun He5d677d12016-05-29 16:52:39 -07002086 Mutex::Autolock il(mInterfaceLock);
2087 Mutex::Autolock l(mLock);
2088
Shuzhen Wang758c2152017-01-10 18:26:18 -08002089 if (consumers.size() == 0) {
2090 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002091 return BAD_VALUE;
2092 }
2093
2094 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2095 if (idx == NAME_NOT_FOUND) {
2096 CLOGE("Stream %d is unknown", streamId);
2097 return idx;
2098 }
2099 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002100 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002101 if (res != OK) {
2102 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2103 return res;
2104 }
2105
Emilian Peev40ead602017-09-26 15:46:36 +01002106 for (auto &consumer : consumers) {
2107 int id = stream->getSurfaceId(consumer);
2108 if (id < 0) {
2109 CLOGE("Invalid surface id!");
2110 return BAD_VALUE;
2111 }
2112 surfaceIds->push_back(id);
2113 }
2114
Shuzhen Wang0129d522016-10-30 22:43:41 -07002115 if (stream->isConsumerConfigurationDeferred()) {
2116 if (!stream->isConfiguring()) {
2117 CLOGE("Stream %d was already fully configured.", streamId);
2118 return INVALID_OPERATION;
2119 }
Zhijun He5d677d12016-05-29 16:52:39 -07002120
Shuzhen Wang0129d522016-10-30 22:43:41 -07002121 res = stream->finishConfiguration();
2122 if (res != OK) {
2123 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2124 stream->getId(), strerror(-res), res);
2125 return res;
2126 }
Zhijun He5d677d12016-05-29 16:52:39 -07002127 }
2128
2129 return OK;
2130}
2131
Emilian Peev40ead602017-09-26 15:46:36 +01002132status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2133 const std::vector<OutputStreamInfo> &outputInfo,
2134 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2135 Mutex::Autolock il(mInterfaceLock);
2136 Mutex::Autolock l(mLock);
2137
2138 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2139 if (idx == NAME_NOT_FOUND) {
2140 CLOGE("Stream %d is unknown", streamId);
2141 return idx;
2142 }
2143
2144 for (const auto &it : removedSurfaceIds) {
2145 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2146 CLOGE("Shared surface still part of a pending request!");
2147 return -EBUSY;
2148 }
2149 }
2150
2151 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2152 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2153 if (res != OK) {
2154 CLOGE("Stream %d failed to update stream (error %d %s) ",
2155 streamId, res, strerror(-res));
2156 if (res == UNKNOWN_ERROR) {
2157 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2158 __FUNCTION__);
2159 }
2160 return res;
2161 }
2162
2163 return res;
2164}
2165
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002166status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2167 Mutex::Autolock il(mInterfaceLock);
2168 Mutex::Autolock l(mLock);
2169
2170 int idx = mOutputStreams.indexOfKey(streamId);
2171 if (idx == NAME_NOT_FOUND) {
2172 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2173 return BAD_VALUE;
2174 }
2175
2176 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2177 return stream->dropBuffers(dropping);
2178}
2179
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002180/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181 * Camera3Device private methods
2182 */
2183
2184sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002185 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002186 ATRACE_CALL();
2187 status_t res;
2188
2189 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002190 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191
2192 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002193 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194 if (inputStreams.count > 0) {
2195 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002196 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002197 CLOGE("Request references unknown input stream %d",
2198 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002199 return NULL;
2200 }
2201 // Lazy completion of stream configuration (allocation/registration)
2202 // on first use
2203 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002204 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002206 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002207 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002208 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002209 return NULL;
2210 }
2211 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002212 // Check if stream is being prepared
2213 if (mInputStream->isPreparing()) {
2214 CLOGE("Request references an input stream that's being prepared!");
2215 return NULL;
2216 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002217
2218 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002219 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220 }
2221
2222 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002223 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002225 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002226 return NULL;
2227 }
2228
2229 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002230 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002232 CLOGE("Request references unknown stream %d",
2233 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 return NULL;
2235 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002236 sp<Camera3OutputStreamInterface> stream =
2237 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238
Zhijun He5d677d12016-05-29 16:52:39 -07002239 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002240 auto iter = surfaceMap.find(streams.data.i32[i]);
2241 if (iter != surfaceMap.end()) {
2242 const std::vector<size_t>& surfaces = iter->second;
2243 for (const auto& surface : surfaces) {
2244 if (stream->isConsumerConfigurationDeferred(surface)) {
2245 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2246 "due to deferred consumer", stream->getId(), surface);
2247 return NULL;
2248 }
2249 }
2250 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002251 }
2252
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 // Lazy completion of stream configuration (allocation/registration)
2254 // on first use
2255 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002256 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002257 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002258 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2259 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002260 return NULL;
2261 }
2262 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002263 // Check if stream is being prepared
2264 if (stream->isPreparing()) {
2265 CLOGE("Request references an output stream that's being prepared!");
2266 return NULL;
2267 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268
2269 newRequest->mOutputStreams.push(stream);
2270 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002271 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002272 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002273
2274 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002275}
2276
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002277bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2278 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2279 Size size = mSupportedOpaqueInputSizes[i];
2280 if (size.width == width && size.height == height) {
2281 return true;
2282 }
2283 }
2284
2285 return false;
2286}
2287
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002288void Camera3Device::cancelStreamsConfigurationLocked() {
2289 int res = OK;
2290 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2291 res = mInputStream->cancelConfiguration();
2292 if (res != OK) {
2293 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2294 mInputStream->getId(), strerror(-res), res);
2295 }
2296 }
2297
2298 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2299 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2300 if (outputStream->isConfiguring()) {
2301 res = outputStream->cancelConfiguration();
2302 if (res != OK) {
2303 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2304 outputStream->getId(), strerror(-res), res);
2305 }
2306 }
2307 }
2308
2309 // Return state to that at start of call, so that future configures
2310 // properly clean things up
2311 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2312 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002313
2314 res = mPreparerThread->resume();
2315 if (res != OK) {
2316 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2317 }
2318}
2319
2320bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2321 ATRACE_CALL();
2322 bool ret = false;
2323
2324 Mutex::Autolock il(mInterfaceLock);
2325 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2326
2327 Mutex::Autolock l(mLock);
2328 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2329 if (rc == NO_ERROR) {
2330 mNeedConfig = true;
2331 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2332 if (rc == NO_ERROR) {
2333 ret = true;
2334 mPauseStateNotify = false;
2335 //Moving to active state while holding 'mLock' is important.
2336 //There could be pending calls to 'create-/deleteStream' which
2337 //will trigger another stream configuration while the already
2338 //present streams end up with outstanding buffers that will
2339 //not get drained.
2340 internalUpdateStatusLocked(STATUS_ACTIVE);
2341 } else {
2342 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2343 __FUNCTION__, rc);
2344 }
2345 } else {
2346 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2347 }
2348
2349 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002350}
2351
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002352status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002353 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 ATRACE_CALL();
2355 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002356
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002357 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002358 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002359 return INVALID_OPERATION;
2360 }
2361
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002362 if (operatingMode < 0) {
2363 CLOGE("Invalid operating mode: %d", operatingMode);
2364 return BAD_VALUE;
2365 }
2366
2367 bool isConstrainedHighSpeed =
2368 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2369 operatingMode;
2370
2371 if (mOperatingMode != operatingMode) {
2372 mNeedConfig = true;
2373 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2374 mOperatingMode = operatingMode;
2375 }
2376
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002377 if (!mNeedConfig) {
2378 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2379 return OK;
2380 }
2381
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002382 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2383 // adding a dummy stream instead.
2384 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2385 if (mOutputStreams.size() == 0) {
2386 addDummyStreamLocked();
2387 } else {
2388 tryRemoveDummyStreamLocked();
2389 }
2390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002392 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002394 mPreparerThread->pause();
2395
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002396 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002397 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2399
2400 Vector<camera3_stream_t*> streams;
2401 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002402 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002403
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002404
2405 if (mInputStream != NULL) {
2406 camera3_stream_t *inputStream;
2407 inputStream = mInputStream->startConfiguration();
2408 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002409 CLOGE("Can't start input stream configuration");
2410 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 return INVALID_OPERATION;
2412 }
2413 streams.add(inputStream);
2414 }
2415
2416 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002417
2418 // Don't configure bidi streams twice, nor add them twice to the list
2419 if (mOutputStreams[i].get() ==
2420 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2421
2422 config.num_streams--;
2423 continue;
2424 }
2425
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426 camera3_stream_t *outputStream;
2427 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2428 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002429 CLOGE("Can't start output stream configuration");
2430 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002431 return INVALID_OPERATION;
2432 }
2433 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002434
2435 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2436 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002437 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2438 // always occupy the initial entry.
2439 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002440 getJpegBufferSize(outputStream->width, outputStream->height));
2441 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002442 }
2443
2444 config.streams = streams.editArray();
2445
2446 // Do the HAL configuration; will potentially touch stream
2447 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002448
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002449 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002450 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002451 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002453 if (res == BAD_VALUE) {
2454 // HAL rejected this set of streams as unsupported, clean up config
2455 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002456 CLOGE("Set of requested inputs/outputs not supported by HAL");
2457 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002458 return BAD_VALUE;
2459 } else if (res != OK) {
2460 // Some other kind of error from configure_streams - this is not
2461 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002462 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2463 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464 return res;
2465 }
2466
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002467 // Finish all stream configuration immediately.
2468 // TODO: Try to relax this later back to lazy completion, which should be
2469 // faster
2470
Igor Murashkin073f8572013-05-02 14:59:28 -07002471 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002472 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002473 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002474 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002475 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002476 cancelStreamsConfigurationLocked();
2477 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002478 }
2479 }
2480
2481 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002482 sp<Camera3OutputStreamInterface> outputStream =
2483 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002484 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002485 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002486 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002487 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002488 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002489 cancelStreamsConfigurationLocked();
2490 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002491 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002492 }
2493 }
2494
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495 // Request thread needs to know to avoid using repeat-last-settings protocol
2496 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002497 if (notifyRequestThread) {
2498 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2499 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002500
Zhijun He90f7c372016-08-16 16:19:43 -07002501 char value[PROPERTY_VALUE_MAX];
2502 property_get("camera.fifo.disable", value, "0");
2503 int32_t disableFifo = atoi(value);
2504 if (disableFifo != 1) {
2505 // Boost priority of request thread to SCHED_FIFO.
2506 pid_t requestThreadTid = mRequestThread->getTid();
2507 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002508 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002509 if (res != OK) {
2510 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2511 strerror(-res), res);
2512 } else {
2513 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2514 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002515 }
2516
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002517 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002518 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2519 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2520 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2521 sessionParams.unlock(newSessionParams);
2522 mSessionParams.unlock(currentSessionParams);
2523 if (updateSessionParams) {
2524 mSessionParams = sessionParams;
2525 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002527 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002528
Ruben Brunk183f0562015-08-12 12:55:02 -07002529 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2530 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002531
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002532 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002533
Zhijun He0a210512014-07-24 13:45:15 -07002534 // tear down the deleted streams after configure streams.
2535 mDeletedStreams.clear();
2536
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002537 auto rc = mPreparerThread->resume();
2538 if (rc != OK) {
2539 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2540 return rc;
2541 }
2542
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002543 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002544}
2545
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002546status_t Camera3Device::addDummyStreamLocked() {
2547 ATRACE_CALL();
2548 status_t res;
2549
2550 if (mDummyStreamId != NO_STREAM) {
2551 // Should never be adding a second dummy stream when one is already
2552 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002553 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2554 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002555 return INVALID_OPERATION;
2556 }
2557
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002558 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002559
2560 sp<Camera3OutputStreamInterface> dummyStream =
2561 new Camera3DummyStream(mNextStreamId);
2562
2563 res = mOutputStreams.add(mNextStreamId, dummyStream);
2564 if (res < 0) {
2565 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2566 return res;
2567 }
2568
2569 mDummyStreamId = mNextStreamId;
2570 mNextStreamId++;
2571
2572 return OK;
2573}
2574
2575status_t Camera3Device::tryRemoveDummyStreamLocked() {
2576 ATRACE_CALL();
2577 status_t res;
2578
2579 if (mDummyStreamId == NO_STREAM) return OK;
2580 if (mOutputStreams.size() == 1) return OK;
2581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002582 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002583
2584 // Ok, have a dummy stream and there's at least one other output stream,
2585 // so remove the dummy
2586
2587 sp<Camera3StreamInterface> deletedStream;
2588 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2589 if (outputStreamIdx == NAME_NOT_FOUND) {
2590 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2591 return INVALID_OPERATION;
2592 }
2593
2594 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2595 mOutputStreams.removeItemsAt(outputStreamIdx);
2596
2597 // Free up the stream endpoint so that it can be used by some other stream
2598 res = deletedStream->disconnect();
2599 if (res != OK) {
2600 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2601 // fall through since we want to still list the stream as deleted.
2602 }
2603 mDeletedStreams.add(deletedStream);
2604 mDummyStreamId = NO_STREAM;
2605
2606 return res;
2607}
2608
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002609void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002610 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002611 Mutex::Autolock l(mLock);
2612 va_list args;
2613 va_start(args, fmt);
2614
2615 setErrorStateLockedV(fmt, args);
2616
2617 va_end(args);
2618}
2619
2620void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002621 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002622 Mutex::Autolock l(mLock);
2623 setErrorStateLockedV(fmt, args);
2624}
2625
2626void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2627 va_list args;
2628 va_start(args, fmt);
2629
2630 setErrorStateLockedV(fmt, args);
2631
2632 va_end(args);
2633}
2634
2635void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002636 // Print out all error messages to log
2637 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002638 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002639
2640 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002641 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002642
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002643 mErrorCause = errorCause;
2644
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002645 if (mRequestThread != nullptr) {
2646 mRequestThread->setPaused(true);
2647 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002648 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002649
2650 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002651 sp<NotificationListener> listener = mListener.promote();
2652 if (listener != NULL) {
2653 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002654 CaptureResultExtras());
2655 }
2656
2657 // Save stack trace. View by dumping it later.
2658 CameraTraces::saveTrace();
2659 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002660}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661
2662/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002663 * In-flight request management
2664 */
2665
Jianing Weicb0652e2014-03-12 18:29:36 -07002666status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002667 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002668 bool hasAppCallback, nsecs_t maxExpectedDuration,
2669 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002670 ATRACE_CALL();
2671 Mutex::Autolock l(mInFlightLock);
2672
2673 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002674 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002675 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002676 if (res < 0) return res;
2677
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002678 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002679 // hold mLock to prevent race with disconnect
2680 Mutex::Autolock l(mLock);
2681 if (mStatusTracker != nullptr) {
2682 mStatusTracker->markComponentActive(mInFlightStatusId);
2683 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002684 }
2685
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002686 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002687 return OK;
2688}
2689
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002690void Camera3Device::returnOutputBuffers(
2691 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2692 nsecs_t timestamp) {
2693 for (size_t i = 0; i < numBuffers; i++)
2694 {
2695 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2696 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2697 // Note: stream may be deallocated at this point, if this buffer was
2698 // the last reference to it.
2699 if (res != OK) {
2700 ALOGE("Can't return buffer to its stream: %s (%d)",
2701 strerror(-res), res);
2702 }
2703 }
2704}
2705
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002706void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002707 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002708 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002709 mInFlightMap.removeItemsAt(idx, 1);
2710
2711 // Indicate idle inFlightMap to the status tracker
2712 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002713 // hold mLock to prevent race with disconnect
2714 Mutex::Autolock l(mLock);
2715 if (mStatusTracker != nullptr) {
2716 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2717 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002718 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002719 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002720}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002721
2722void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2723
2724 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2725 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2726
2727 nsecs_t sensorTimestamp = request.sensorTimestamp;
2728 nsecs_t shutterTimestamp = request.shutterTimestamp;
2729
2730 // Check if it's okay to remove the request from InFlightMap:
2731 // In the case of a successful request:
2732 // all input and output buffers, all result metadata, shutter callback
2733 // arrived.
2734 // In the case of a unsuccessful request:
2735 // all input and output buffers arrived.
2736 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002737 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002738 (request.haveResultMetadata && shutterTimestamp != 0))) {
2739 ATRACE_ASYNC_END("frame capture", frameNumber);
2740
Shuzhen Wang403044a2017-02-26 23:29:04 -08002741 // Sanity check - if sensor timestamp matches shutter timestamp in the
2742 // case of request having callback.
2743 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002744 sensorTimestamp != shutterTimestamp) {
2745 SET_ERR("sensor timestamp (%" PRId64
2746 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2747 sensorTimestamp, frameNumber, shutterTimestamp);
2748 }
2749
2750 // for an unsuccessful request, it may have pending output buffers to
2751 // return.
2752 assert(request.requestStatus != OK ||
2753 request.pendingOutputBuffers.size() == 0);
2754 returnOutputBuffers(request.pendingOutputBuffers.array(),
2755 request.pendingOutputBuffers.size(), 0);
2756
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002757 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002758 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2759 }
2760
2761 // Sanity check - if we have too many in-flight frames, something has
2762 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002763 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002764 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002765 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2766 kInFlightWarnLimitHighSpeed) {
2767 CLOGE("In-flight list too large for high speed configuration: %zu",
2768 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002769 }
2770}
2771
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002772void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002773 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002774 { // First return buffers cached in mInFlightMap
2775 Mutex::Autolock l(mInFlightLock);
2776 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2777 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2778 returnOutputBuffers(request.pendingOutputBuffers.array(),
2779 request.pendingOutputBuffers.size(), 0);
2780 }
2781 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002782 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002783 }
2784
2785 // Then return all inflight buffers not returned by HAL
2786 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2787 mInterface->getInflightBufferKeys(&inflightKeys);
2788
2789 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2790 for (auto& pair : inflightKeys) {
2791 int32_t frameNumber = pair.first;
2792 int32_t streamId = pair.second;
2793 buffer_handle_t* buffer;
2794 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2795 if (res != OK) {
2796 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2797 __FUNCTION__, frameNumber, streamId);
2798 continue;
2799 }
2800
2801 camera3_stream_buffer_t streamBuffer;
2802 streamBuffer.buffer = buffer;
2803 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2804 streamBuffer.acquire_fence = -1;
2805 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002806
2807 // First check if the buffer belongs to deleted stream
2808 bool streamDeleted = false;
2809 for (auto& stream : mDeletedStreams) {
2810 if (streamId == stream->getId()) {
2811 streamDeleted = true;
2812 // Return buffer to deleted stream
2813 camera3_stream* halStream = stream->asHalStream();
2814 streamBuffer.stream = halStream;
2815 switch (halStream->stream_type) {
2816 case CAMERA3_STREAM_OUTPUT:
2817 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2818 if (res != OK) {
2819 ALOGE("%s: Can't return output buffer for frame %d to"
2820 " stream %d: %s (%d)", __FUNCTION__,
2821 frameNumber, streamId, strerror(-res), res);
2822 }
2823 break;
2824 case CAMERA3_STREAM_INPUT:
2825 res = stream->returnInputBuffer(streamBuffer);
2826 if (res != OK) {
2827 ALOGE("%s: Can't return input buffer for frame %d to"
2828 " stream %d: %s (%d)", __FUNCTION__,
2829 frameNumber, streamId, strerror(-res), res);
2830 }
2831 break;
2832 default: // Bi-direcitonal stream is deprecated
2833 ALOGE("%s: stream %d has unknown stream type %d",
2834 __FUNCTION__, streamId, halStream->stream_type);
2835 break;
2836 }
2837 break;
2838 }
2839 }
2840 if (streamDeleted) {
2841 continue;
2842 }
2843
2844 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002845 if (streamId == inputStreamId) {
2846 streamBuffer.stream = mInputStream->asHalStream();
2847 res = mInputStream->returnInputBuffer(streamBuffer);
2848 if (res != OK) {
2849 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002850 " stream %d: %s (%d)", __FUNCTION__,
2851 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002852 }
2853 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002854 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2855 if (idx == NAME_NOT_FOUND) {
2856 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2857 continue;
2858 }
2859 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002860 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2861 }
2862 }
2863}
2864
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002865void Camera3Device::insertResultLocked(CaptureResult *result,
2866 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002867 if (result == nullptr) return;
2868
Emilian Peev71c73a22017-03-21 16:35:51 +00002869 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2870 result->mMetadata.getAndLock());
2871 set_camera_metadata_vendor_id(meta, mVendorTagId);
2872 result->mMetadata.unlock(meta);
2873
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002874 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2875 (int32_t*)&frameNumber, 1) != OK) {
2876 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2877 return;
2878 }
2879
2880 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2881 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2882 return;
2883 }
2884
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002885 // Valid result, insert into queue
2886 List<CaptureResult>::iterator queuedResult =
2887 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2888 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2889 ", burstId = %" PRId32, __FUNCTION__,
2890 queuedResult->mResultExtras.requestId,
2891 queuedResult->mResultExtras.frameNumber,
2892 queuedResult->mResultExtras.burstId);
2893
2894 mResultSignal.signal();
2895}
2896
2897
2898void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002899 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002900 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002901 Mutex::Autolock l(mOutputLock);
2902
2903 CaptureResult captureResult;
2904 captureResult.mResultExtras = resultExtras;
2905 captureResult.mMetadata = partialResult;
2906
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002907 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002908}
2909
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002910
2911void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2912 CaptureResultExtras &resultExtras,
2913 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002914 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002915 bool reprocess,
2916 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002917 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002918 if (pendingMetadata.isEmpty())
2919 return;
2920
2921 Mutex::Autolock l(mOutputLock);
2922
2923 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002924 if (reprocess) {
2925 if (frameNumber < mNextReprocessResultFrameNumber) {
2926 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002927 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002928 frameNumber, mNextReprocessResultFrameNumber);
2929 return;
2930 }
2931 mNextReprocessResultFrameNumber = frameNumber + 1;
2932 } else {
2933 if (frameNumber < mNextResultFrameNumber) {
2934 SET_ERR("Out-of-order capture result metadata submitted! "
2935 "(got frame number %d, expecting %d)",
2936 frameNumber, mNextResultFrameNumber);
2937 return;
2938 }
2939 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002940 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002941
2942 CaptureResult captureResult;
2943 captureResult.mResultExtras = resultExtras;
2944 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002945 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002946
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002947 // Append any previous partials to form a complete result
2948 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2949 captureResult.mMetadata.append(collectedPartialResult);
2950 }
2951
2952 captureResult.mMetadata.sort();
2953
2954 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002955 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2956 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002957 SET_ERR("No timestamp provided by HAL for frame %d!",
2958 frameNumber);
2959 return;
2960 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002961 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
2962 camera_metadata_entry timestamp =
2963 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2964 if (timestamp.count == 0) {
2965 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
2966 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
2967 return;
2968 }
2969 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002970
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002971 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2972 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2973
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002974 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002975}
2976
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002977/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978 * Camera HAL device callback methods
2979 */
2980
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002981void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002982 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002983
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002984 status_t res;
2985
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002986 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002987 if (result->result == NULL && result->num_output_buffers == 0 &&
2988 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989 SET_ERR("No result data provided by HAL for frame %d",
2990 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002991 return;
2992 }
Zhijun He204e3292014-07-14 17:09:23 -07002993
Zhijun He204e3292014-07-14 17:09:23 -07002994 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002995 result->result != NULL &&
2996 result->partial_result != 1) {
2997 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2998 " if partial result is not supported",
2999 frameNumber, result->partial_result);
3000 return;
3001 }
3002
3003 bool isPartialResult = false;
3004 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003005 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003006
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003007 // Get shutter timestamp and resultExtras from list of in-flight requests,
3008 // where it was added by the shutter notification for this frame. If the
3009 // shutter timestamp isn't received yet, append the output buffers to the
3010 // in-flight request and they will be returned when the shutter timestamp
3011 // arrives. Update the in-flight status and remove the in-flight entry if
3012 // all result data and shutter timestamp have been received.
3013 nsecs_t shutterTimestamp = 0;
3014
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003015 {
3016 Mutex::Autolock l(mInFlightLock);
3017 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3018 if (idx == NAME_NOT_FOUND) {
3019 SET_ERR("Unknown frame number for capture result: %d",
3020 frameNumber);
3021 return;
3022 }
3023 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003024 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3025 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003026 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003027 __FUNCTION__, request.resultExtras.requestId,
3028 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003029 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003030 // Always update the partial count to the latest one if it's not 0
3031 // (buffers only). When framework aggregates adjacent partial results
3032 // into one, the latest partial count will be used.
3033 if (result->partial_result != 0)
3034 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003035
3036 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003037 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003038 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3039 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3040 " the range of [1, %d] when metadata is included in the result",
3041 frameNumber, result->partial_result, mNumPartialResults);
3042 return;
3043 }
3044 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003045 if (isPartialResult && result->num_physcam_metadata) {
3046 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3047 " physical camera result", frameNumber);
3048 return;
3049 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003050 if (isPartialResult) {
3051 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003052 }
3053
Shuzhen Wang4a472662017-02-26 23:29:04 -08003054 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003055 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003056 sendPartialCaptureResult(result->result, request.resultExtras,
3057 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003058 }
3059 }
3060
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003061 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003062 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003063
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003064 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003065 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003066 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3067 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3068 request.physicalCameraIds.size(), result->num_physcam_metadata);
3069 return;
3070 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003071 if (request.haveResultMetadata) {
3072 SET_ERR("Called multiple times with metadata for frame %d",
3073 frameNumber);
3074 return;
3075 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003076 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3077 String8 physicalId(result->physcam_ids[i]);
3078 std::set<String8>::iterator cameraIdIter =
3079 request.physicalCameraIds.find(physicalId);
3080 if (cameraIdIter != request.physicalCameraIds.end()) {
3081 request.physicalCameraIds.erase(cameraIdIter);
3082 } else {
3083 SET_ERR("Total result for frame %d has already returned for camera %s",
3084 frameNumber, physicalId.c_str());
3085 return;
3086 }
3087 }
Zhijun He204e3292014-07-14 17:09:23 -07003088 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003089 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003090 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003091 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003092 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003093 request.haveResultMetadata = true;
3094 }
3095
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003096 uint32_t numBuffersReturned = result->num_output_buffers;
3097 if (result->input_buffer != NULL) {
3098 if (hasInputBufferInRequest) {
3099 numBuffersReturned += 1;
3100 } else {
3101 ALOGW("%s: Input buffer should be NULL if there is no input"
3102 " buffer sent in the request",
3103 __FUNCTION__);
3104 }
3105 }
3106 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003107 if (request.numBuffersLeft < 0) {
3108 SET_ERR("Too many buffers returned for frame %d",
3109 frameNumber);
3110 return;
3111 }
3112
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003113 camera_metadata_ro_entry_t entry;
3114 res = find_camera_metadata_ro_entry(result->result,
3115 ANDROID_SENSOR_TIMESTAMP, &entry);
3116 if (res == OK && entry.count == 1) {
3117 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003118 }
3119
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003120 // If shutter event isn't received yet, append the output buffers to
3121 // the in-flight request. Otherwise, return the output buffers to
3122 // streams.
3123 if (shutterTimestamp == 0) {
3124 request.pendingOutputBuffers.appendArray(result->output_buffers,
3125 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003126 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003127 returnOutputBuffers(result->output_buffers,
3128 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003129 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003130
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003131 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003132 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3133 CameraMetadata physicalMetadata;
3134 physicalMetadata.append(result->physcam_metadata[i]);
3135 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3136 physicalMetadata});
3137 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003138 if (shutterTimestamp == 0) {
3139 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003140 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003141 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003142 CameraMetadata metadata;
3143 metadata = result->result;
3144 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003145 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003146 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003147 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003148 }
3149
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003150 removeInFlightRequestIfReadyLocked(idx);
3151 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003152
Zhijun Hef0d962a2014-06-30 10:24:11 -07003153 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003154 if (hasInputBufferInRequest) {
3155 Camera3Stream *stream =
3156 Camera3Stream::cast(result->input_buffer->stream);
3157 res = stream->returnInputBuffer(*(result->input_buffer));
3158 // Note: stream may be deallocated at this point, if this buffer was the
3159 // last reference to it.
3160 if (res != OK) {
3161 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3162 " its stream:%s (%d)", __FUNCTION__,
3163 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003164 }
3165 } else {
3166 ALOGW("%s: Input buffer should be NULL if there is no input"
3167 " buffer sent in the request, skipping input buffer return.",
3168 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003169 }
3170 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003171}
3172
3173void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003174 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003175 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003176 {
3177 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003178 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003179 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003180
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003181 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003182 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003183 return;
3184 }
3185
3186 switch (msg->type) {
3187 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003188 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003189 break;
3190 }
3191 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003192 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003193 break;
3194 }
3195 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003196 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003197 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003198 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003199}
3200
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003201void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003202 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003203 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003204 // Map camera HAL error codes to ICameraDeviceCallback error codes
3205 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003207 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003208 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003209 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003210 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003211 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003212 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003213 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003214 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003215 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003216 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003217 };
3218
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003219 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003220 ((msg.error_code >= 0) &&
3221 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3222 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003223 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003224
3225 int streamId = 0;
3226 if (msg.error_stream != NULL) {
3227 Camera3Stream *stream =
3228 Camera3Stream::cast(msg.error_stream);
3229 streamId = stream->getId();
3230 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003231 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3232 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003233 streamId, msg.error_code);
3234
3235 CaptureResultExtras resultExtras;
3236 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003237 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003238 // SET_ERR calls notifyError
3239 SET_ERR("Camera HAL reported serious device error");
3240 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003241 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3242 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3243 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003244 {
3245 Mutex::Autolock l(mInFlightLock);
3246 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3247 if (idx >= 0) {
3248 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3249 r.requestStatus = msg.error_code;
3250 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003251 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3252 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3253 errorCode) {
3254 r.skipResultMetadata = true;
3255 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003256 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3257 errorCode) {
3258 // In case of missing result check whether the buffers
3259 // returned. If they returned, then remove inflight
3260 // request.
3261 removeInFlightRequestIfReadyLocked(idx);
3262 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003263 } else {
3264 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003265 ALOGE("Camera %s: %s: cannot find in-flight request on "
3266 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003267 resultExtras.frameNumber);
3268 }
3269 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003270 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003271 if (listener != NULL) {
3272 listener->notifyError(errorCode, resultExtras);
3273 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003274 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003275 }
3276 break;
3277 default:
3278 // SET_ERR calls notifyError
3279 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3280 break;
3281 }
3282}
3283
3284void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003285 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003286 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003287 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003289 // Set timestamp for the request in the in-flight tracking
3290 // and get the request ID to send upstream
3291 {
3292 Mutex::Autolock l(mInFlightLock);
3293 idx = mInFlightMap.indexOfKey(msg.frame_number);
3294 if (idx >= 0) {
3295 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003296
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003297 // Verify ordering of shutter notifications
3298 {
3299 Mutex::Autolock l(mOutputLock);
3300 // TODO: need to track errors for tighter bounds on expected frame number.
3301 if (r.hasInputBuffer) {
3302 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3303 SET_ERR("Shutter notification out-of-order. Expected "
3304 "notification for frame %d, got frame %d",
3305 mNextReprocessShutterFrameNumber, msg.frame_number);
3306 return;
3307 }
3308 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3309 } else {
3310 if (msg.frame_number < mNextShutterFrameNumber) {
3311 SET_ERR("Shutter notification out-of-order. Expected "
3312 "notification for frame %d, got frame %d",
3313 mNextShutterFrameNumber, msg.frame_number);
3314 return;
3315 }
3316 mNextShutterFrameNumber = msg.frame_number + 1;
3317 }
3318 }
3319
Shuzhen Wang4a472662017-02-26 23:29:04 -08003320 r.shutterTimestamp = msg.timestamp;
3321 if (r.hasCallback) {
3322 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003323 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003324 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003325 // Call listener, if any
3326 if (listener != NULL) {
3327 listener->notifyShutter(r.resultExtras, msg.timestamp);
3328 }
3329 // send pending result and buffers
3330 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3331 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003332 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003333 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003334 returnOutputBuffers(r.pendingOutputBuffers.array(),
3335 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3336 r.pendingOutputBuffers.clear();
3337
3338 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003339 }
3340 }
3341 if (idx < 0) {
3342 SET_ERR("Shutter notification for non-existent frame number %d",
3343 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003344 }
3345}
3346
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003347CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003348 ALOGV("%s", __FUNCTION__);
3349
Igor Murashkin1e479c02013-09-06 16:55:14 -07003350 CameraMetadata retVal;
3351
3352 if (mRequestThread != NULL) {
3353 retVal = mRequestThread->getLatestRequest();
3354 }
3355
Igor Murashkin1e479c02013-09-06 16:55:14 -07003356 return retVal;
3357}
3358
Jianing Weicb0652e2014-03-12 18:29:36 -07003359
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003360void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3361 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3362 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3363}
3364
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003365/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003366 * HalInterface inner class methods
3367 */
3368
Yifan Hongf79b5542017-04-11 14:44:25 -07003369Camera3Device::HalInterface::HalInterface(
3370 sp<ICameraDeviceSession> &session,
3371 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003372 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003373 mRequestMetadataQueue(queue) {
3374 // Check with hardware service manager if we can downcast these interfaces
3375 // Somewhat expensive, so cache the results at startup
3376 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3377 if (castResult_3_4.isOk()) {
3378 mHidlSession_3_4 = castResult_3_4;
3379 }
3380 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3381 if (castResult_3_3.isOk()) {
3382 mHidlSession_3_3 = castResult_3_3;
3383 }
3384}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003385
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003387
3388Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003389 mHidlSession(other.mHidlSession),
3390 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003391
3392bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003393 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003394}
3395
3396void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003397 mHidlSession_3_4.clear();
3398 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003399 mHidlSession.clear();
3400}
3401
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003402bool Camera3Device::HalInterface::supportBatchRequest() {
3403 return mHidlSession != nullptr;
3404}
3405
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003406status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3407 camera3_request_template_t templateId,
3408 /*out*/ camera_metadata_t **requestTemplate) {
3409 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3410 if (!valid()) return INVALID_OPERATION;
3411 status_t res = OK;
3412
Emilian Peev31abd0a2017-05-11 18:37:46 +01003413 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003414
3415 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003416 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003417 status = s;
3418 if (status == common::V1_0::Status::OK) {
3419 const camera_metadata *r =
3420 reinterpret_cast<const camera_metadata_t*>(request.data());
3421 size_t expectedSize = request.size();
3422 int ret = validate_camera_metadata_structure(r, &expectedSize);
3423 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3424 *requestTemplate = clone_camera_metadata(r);
3425 if (*requestTemplate == nullptr) {
3426 ALOGE("%s: Unable to clone camera metadata received from HAL",
3427 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003428 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003429 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003430 } else {
3431 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3432 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003433 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003434 }
3435 };
3436 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003437 RequestTemplate id;
3438 switch (templateId) {
3439 case CAMERA3_TEMPLATE_PREVIEW:
3440 id = RequestTemplate::PREVIEW;
3441 break;
3442 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3443 id = RequestTemplate::STILL_CAPTURE;
3444 break;
3445 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3446 id = RequestTemplate::VIDEO_RECORD;
3447 break;
3448 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3449 id = RequestTemplate::VIDEO_SNAPSHOT;
3450 break;
3451 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3452 id = RequestTemplate::ZERO_SHUTTER_LAG;
3453 break;
3454 case CAMERA3_TEMPLATE_MANUAL:
3455 id = RequestTemplate::MANUAL;
3456 break;
3457 default:
3458 // Unknown template ID, or this HAL is too old to support it
3459 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003460 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003461 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003462
Emilian Peev31abd0a2017-05-11 18:37:46 +01003463 if (!err.isOk()) {
3464 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3465 res = DEAD_OBJECT;
3466 } else {
3467 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003468 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003469
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003470 return res;
3471}
3472
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003473status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003474 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003475 ATRACE_NAME("CameraHal::configureStreams");
3476 if (!valid()) return INVALID_OPERATION;
3477 status_t res = OK;
3478
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 // Convert stream config to HIDL
3480 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003481 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3482 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3483 requestedConfiguration3_2.streams.resize(config->num_streams);
3484 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003485 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003486 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3487 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003488 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003489
Emilian Peev31abd0a2017-05-11 18:37:46 +01003490 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3491 cam3stream->setBufferFreedListener(this);
3492 int streamId = cam3stream->getId();
3493 StreamType streamType;
3494 switch (src->stream_type) {
3495 case CAMERA3_STREAM_OUTPUT:
3496 streamType = StreamType::OUTPUT;
3497 break;
3498 case CAMERA3_STREAM_INPUT:
3499 streamType = StreamType::INPUT;
3500 break;
3501 default:
3502 ALOGE("%s: Stream %d: Unsupported stream type %d",
3503 __FUNCTION__, streamId, config->streams[i]->stream_type);
3504 return BAD_VALUE;
3505 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003506 dst3_2.id = streamId;
3507 dst3_2.streamType = streamType;
3508 dst3_2.width = src->width;
3509 dst3_2.height = src->height;
3510 dst3_2.format = mapToPixelFormat(src->format);
3511 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3512 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3513 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3514 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003515 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003516 if (src->physical_camera_id != nullptr) {
3517 dst3_4.physicalCameraId = src->physical_camera_id;
3518 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519
3520 activeStreams.insert(streamId);
3521 // Create Buffer ID map if necessary
3522 if (mBufferIdMaps.count(streamId) == 0) {
3523 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3524 }
3525 }
3526 // remove BufferIdMap for deleted streams
3527 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3528 int streamId = it->first;
3529 bool active = activeStreams.count(streamId) > 0;
3530 if (!active) {
3531 it = mBufferIdMaps.erase(it);
3532 } else {
3533 ++it;
3534 }
3535 }
3536
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003537 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003538 res = mapToStreamConfigurationMode(
3539 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003540 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003541 if (res != OK) {
3542 return res;
3543 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003544 requestedConfiguration3_2.operationMode = operationMode;
3545 requestedConfiguration3_4.operationMode = operationMode;
3546 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003547 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3548 get_camera_metadata_size(sessionParams));
3549
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003551 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003553
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003554 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003555 if (mHidlSession_3_4 != nullptr) {
3556 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003557 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003558 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003559 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003560 [&status, &finalConfiguration3_4]
3561 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3562 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003563 status = s;
3564 });
3565 if (!err.isOk()) {
3566 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3567 return DEAD_OBJECT;
3568 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003569 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3570 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3571 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3572 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003573 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003574 // We do; use v3.3 for the call
3575 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003576 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003577 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003578 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003579 finalConfiguration = halConfiguration;
3580 status = s;
3581 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003582 if (!err.isOk()) {
3583 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3584 return DEAD_OBJECT;
3585 }
3586 } else {
3587 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3588 ALOGV("%s: v3.2 device found", __FUNCTION__);
3589 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003590 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003591 [&status, &finalConfiguration_3_2]
3592 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3593 finalConfiguration_3_2 = halConfiguration;
3594 status = s;
3595 });
3596 if (!err.isOk()) {
3597 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3598 return DEAD_OBJECT;
3599 }
3600 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3601 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3602 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3603 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003604 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003605 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003606 }
3607
3608 if (status != common::V1_0::Status::OK ) {
3609 return CameraProviderManager::mapToStatusT(status);
3610 }
3611
3612 // And convert output stream configuration from HIDL
3613
3614 for (size_t i = 0; i < config->num_streams; i++) {
3615 camera3_stream_t *dst = config->streams[i];
3616 int streamId = Camera3Stream::cast(dst)->getId();
3617
3618 // Start scan at i, with the assumption that the stream order matches
3619 size_t realIdx = i;
3620 bool found = false;
3621 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003622 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003623 found = true;
3624 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003625 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003626 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3627 }
3628 if (!found) {
3629 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3630 __FUNCTION__, streamId);
3631 return INVALID_OPERATION;
3632 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003633 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003634
Emilian Peev710c1422017-08-30 11:19:38 +01003635 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3636 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003637 dstStream->setDataSpaceOverride(false);
3638 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3639 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3640
Emilian Peev31abd0a2017-05-11 18:37:46 +01003641 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3642 if (dst->format != overrideFormat) {
3643 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3644 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003645 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003646 if (dst->data_space != overrideDataSpace) {
3647 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3648 streamId, dst->format);
3649 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003650 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003651 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003652 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3653
Emilian Peev31abd0a2017-05-11 18:37:46 +01003654 // Override allowed with IMPLEMENTATION_DEFINED
3655 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003656 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003657 }
3658
Emilian Peev31abd0a2017-05-11 18:37:46 +01003659 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003660 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003661 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003662 __FUNCTION__, streamId);
3663 return INVALID_OPERATION;
3664 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003665 dstStream->setUsage(
3666 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003667 } else {
3668 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003669 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003670 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3671 __FUNCTION__, streamId);
3672 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003673 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003674 dstStream->setUsage(
3675 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003676 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003677 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003678 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003679
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003680 return res;
3681}
3682
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003683void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3684 /*out*/device::V3_2::CaptureRequest* captureRequest,
3685 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003686 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003687 if (captureRequest == nullptr || handlesCreated == nullptr) {
3688 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3689 __FUNCTION__, captureRequest, handlesCreated);
3690 return;
3691 }
3692
3693 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003694
3695 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003696
3697 {
3698 std::lock_guard<std::mutex> lock(mInflightLock);
3699 if (request->input_buffer != nullptr) {
3700 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3701 buffer_handle_t buf = *(request->input_buffer->buffer);
3702 auto pair = getBufferId(buf, streamId);
3703 bool isNewBuffer = pair.first;
3704 uint64_t bufferId = pair.second;
3705 captureRequest->inputBuffer.streamId = streamId;
3706 captureRequest->inputBuffer.bufferId = bufferId;
3707 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3708 captureRequest->inputBuffer.status = BufferStatus::OK;
3709 native_handle_t *acquireFence = nullptr;
3710 if (request->input_buffer->acquire_fence != -1) {
3711 acquireFence = native_handle_create(1,0);
3712 acquireFence->data[0] = request->input_buffer->acquire_fence;
3713 handlesCreated->push_back(acquireFence);
3714 }
3715 captureRequest->inputBuffer.acquireFence = acquireFence;
3716 captureRequest->inputBuffer.releaseFence = nullptr;
3717
3718 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3719 request->input_buffer->buffer,
3720 request->input_buffer->acquire_fence);
3721 } else {
3722 captureRequest->inputBuffer.streamId = -1;
3723 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3724 }
3725
3726 captureRequest->outputBuffers.resize(request->num_output_buffers);
3727 for (size_t i = 0; i < request->num_output_buffers; i++) {
3728 const camera3_stream_buffer_t *src = request->output_buffers + i;
3729 StreamBuffer &dst = captureRequest->outputBuffers[i];
3730 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3731 buffer_handle_t buf = *(src->buffer);
3732 auto pair = getBufferId(buf, streamId);
3733 bool isNewBuffer = pair.first;
3734 dst.streamId = streamId;
3735 dst.bufferId = pair.second;
3736 dst.buffer = isNewBuffer ? buf : nullptr;
3737 dst.status = BufferStatus::OK;
3738 native_handle_t *acquireFence = nullptr;
3739 if (src->acquire_fence != -1) {
3740 acquireFence = native_handle_create(1,0);
3741 acquireFence->data[0] = src->acquire_fence;
3742 handlesCreated->push_back(acquireFence);
3743 }
3744 dst.acquireFence = acquireFence;
3745 dst.releaseFence = nullptr;
3746
3747 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3748 src->buffer, src->acquire_fence);
3749 }
3750 }
3751}
3752
3753status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3754 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3755 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3756 if (!valid()) return INVALID_OPERATION;
3757
Emilian Peevaebbe412018-01-15 13:53:24 +00003758 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3759 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3760 if (castResult_3_4.isOk()) {
3761 hidlSession_3_4 = castResult_3_4;
3762 }
3763
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003764 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003765 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003766 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003767 if (hidlSession_3_4 != nullptr) {
3768 captureRequests_3_4.resize(batchSize);
3769 } else {
3770 captureRequests.resize(batchSize);
3771 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003772 std::vector<native_handle_t*> handlesCreated;
3773
3774 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003775 if (hidlSession_3_4 != nullptr) {
3776 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3777 /*out*/&handlesCreated);
3778 } else {
3779 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3780 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003781 }
3782
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003783 std::vector<device::V3_2::BufferCache> cachesToRemove;
3784 {
3785 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3786 for (auto& pair : mFreedBuffers) {
3787 // The stream might have been removed since onBufferFreed
3788 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3789 cachesToRemove.push_back({pair.first, pair.second});
3790 }
3791 }
3792 mFreedBuffers.clear();
3793 }
3794
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003795 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3796 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003797
3798 // Write metadata to FMQ.
3799 for (size_t i = 0; i < batchSize; i++) {
3800 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003801 device::V3_2::CaptureRequest* captureRequest;
3802 if (hidlSession_3_4 != nullptr) {
3803 captureRequest = &captureRequests_3_4[i].v3_2;
3804 } else {
3805 captureRequest = &captureRequests[i];
3806 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003807
3808 if (request->settings != nullptr) {
3809 size_t settingsSize = get_camera_metadata_size(request->settings);
3810 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3811 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3812 captureRequest->settings.resize(0);
3813 captureRequest->fmqSettingsSize = settingsSize;
3814 } else {
3815 if (mRequestMetadataQueue != nullptr) {
3816 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3817 }
3818 captureRequest->settings.setToExternal(
3819 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3820 get_camera_metadata_size(request->settings));
3821 captureRequest->fmqSettingsSize = 0u;
3822 }
3823 } else {
3824 // A null request settings maps to a size-0 CameraMetadata
3825 captureRequest->settings.resize(0);
3826 captureRequest->fmqSettingsSize = 0u;
3827 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003828
3829 if (hidlSession_3_4 != nullptr) {
3830 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3831 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003832 if (request->physcam_settings != nullptr) {
3833 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3834 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3835 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3836 settingsSize)) {
3837 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3838 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3839 settingsSize;
3840 } else {
3841 if (mRequestMetadataQueue != nullptr) {
3842 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3843 }
3844 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3845 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3846 request->physcam_settings[j])),
3847 get_camera_metadata_size(request->physcam_settings[j]));
3848 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003849 }
Emilian Peev00420d22018-02-05 21:33:13 +00003850 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003852 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003853 }
3854 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3855 request->physcam_id[j];
3856 }
3857 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003858 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003859
3860 hardware::details::return_status err;
3861 if (hidlSession_3_4 != nullptr) {
3862 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003863 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3864 status = s;
3865 *numRequestProcessed = n;
3866 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003867 } else {
3868 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3869 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3870 status = s;
3871 *numRequestProcessed = n;
3872 });
3873 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003874 if (!err.isOk()) {
3875 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3876 return DEAD_OBJECT;
3877 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003878 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3879 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3880 __FUNCTION__, *numRequestProcessed, batchSize);
3881 status = common::V1_0::Status::INTERNAL_ERROR;
3882 }
3883
3884 for (auto& handle : handlesCreated) {
3885 native_handle_delete(handle);
3886 }
3887 return CameraProviderManager::mapToStatusT(status);
3888}
3889
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003890status_t Camera3Device::HalInterface::processCaptureRequest(
3891 camera3_capture_request_t *request) {
3892 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003893 if (!valid()) return INVALID_OPERATION;
3894 status_t res = OK;
3895
Emilian Peev31abd0a2017-05-11 18:37:46 +01003896 uint32_t numRequestProcessed = 0;
3897 std::vector<camera3_capture_request_t*> requests(1);
3898 requests[0] = request;
3899 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3900
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003901 return res;
3902}
3903
3904status_t Camera3Device::HalInterface::flush() {
3905 ATRACE_NAME("CameraHal::flush");
3906 if (!valid()) return INVALID_OPERATION;
3907 status_t res = OK;
3908
Emilian Peev31abd0a2017-05-11 18:37:46 +01003909 auto err = mHidlSession->flush();
3910 if (!err.isOk()) {
3911 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3912 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003913 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003914 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003915 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003916
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003917 return res;
3918}
3919
Emilian Peev31abd0a2017-05-11 18:37:46 +01003920status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003921 ATRACE_NAME("CameraHal::dump");
3922 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003923
Emilian Peev31abd0a2017-05-11 18:37:46 +01003924 // Handled by CameraProviderManager::dump
3925
3926 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003927}
3928
3929status_t Camera3Device::HalInterface::close() {
3930 ATRACE_NAME("CameraHal::close()");
3931 if (!valid()) return INVALID_OPERATION;
3932 status_t res = OK;
3933
Emilian Peev31abd0a2017-05-11 18:37:46 +01003934 auto err = mHidlSession->close();
3935 // Interface will be dead shortly anyway, so don't log errors
3936 if (!err.isOk()) {
3937 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003938 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003939
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003940 return res;
3941}
3942
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003943void Camera3Device::HalInterface::getInflightBufferKeys(
3944 std::vector<std::pair<int32_t, int32_t>>* out) {
3945 std::lock_guard<std::mutex> lock(mInflightLock);
3946 out->clear();
3947 out->reserve(mInflightBufferMap.size());
3948 for (auto& pair : mInflightBufferMap) {
3949 uint64_t key = pair.first;
3950 int32_t streamId = key & 0xFFFFFFFF;
3951 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3952 out->push_back(std::make_pair(frameNumber, streamId));
3953 }
3954 return;
3955}
3956
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003957status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003958 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003959 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003960 auto pair = std::make_pair(buffer, acquireFence);
3961 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003962 return OK;
3963}
3964
3965status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003966 int32_t frameNumber, int32_t streamId,
3967 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003968 std::lock_guard<std::mutex> lock(mInflightLock);
3969
3970 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3971 auto it = mInflightBufferMap.find(key);
3972 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003973 auto pair = it->second;
3974 *buffer = pair.first;
3975 int acquireFence = pair.second;
3976 if (acquireFence > 0) {
3977 ::close(acquireFence);
3978 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979 mInflightBufferMap.erase(it);
3980 return OK;
3981}
3982
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003983std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3984 const buffer_handle_t& buf, int streamId) {
3985 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3986
3987 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3988 auto it = bIdMap.find(buf);
3989 if (it == bIdMap.end()) {
3990 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003991 ALOGV("stream %d now have %zu buffer caches, buf %p",
3992 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003993 return std::make_pair(true, mNextBufferId - 1);
3994 } else {
3995 return std::make_pair(false, it->second);
3996 }
3997}
3998
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003999void Camera3Device::HalInterface::onBufferFreed(
4000 int streamId, const native_handle_t* handle) {
4001 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4002 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4003 auto mapIt = mBufferIdMaps.find(streamId);
4004 if (mapIt == mBufferIdMaps.end()) {
4005 // streamId might be from a deleted stream here
4006 ALOGI("%s: stream %d has been removed",
4007 __FUNCTION__, streamId);
4008 return;
4009 }
4010 BufferIdMap& bIdMap = mapIt->second;
4011 auto it = bIdMap.find(handle);
4012 if (it == bIdMap.end()) {
4013 ALOGW("%s: cannot find buffer %p in stream %d",
4014 __FUNCTION__, handle, streamId);
4015 return;
4016 } else {
4017 bufferId = it->second;
4018 bIdMap.erase(it);
4019 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4020 __FUNCTION__, streamId, bIdMap.size(), handle);
4021 }
4022 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4023}
4024
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004025/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004026 * RequestThread inner class methods
4027 */
4028
4029Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004030 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004031 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004032 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004033 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004034 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004035 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004036 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004037 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004038 mReconfigured(false),
4039 mDoPause(false),
4040 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004041 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004042 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004043 mCurrentAfTriggerId(0),
4044 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004045 mRepeatingLastFrameNumber(
4046 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004047 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004048 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004049 mRequestLatency(kRequestLatencyBinSize),
4050 mSessionParamKeys(sessionParamKeys),
4051 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004052 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004053}
4054
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004055Camera3Device::RequestThread::~RequestThread() {}
4056
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004057void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004058 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004059 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004060 Mutex::Autolock l(mRequestLock);
4061 mListener = listener;
4062}
4063
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004064void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4065 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004066 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004067 Mutex::Autolock l(mRequestLock);
4068 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004069 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004070 // Prepare video stream for high speed recording.
4071 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004072 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004073}
4074
Jianing Wei90e59c92014-03-12 18:29:36 -07004075status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004076 List<sp<CaptureRequest> > &requests,
4077 /*out*/
4078 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004079 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004080 Mutex::Autolock l(mRequestLock);
4081 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4082 ++it) {
4083 mRequestQueue.push_back(*it);
4084 }
4085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004086 if (lastFrameNumber != NULL) {
4087 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4088 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4089 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4090 *lastFrameNumber);
4091 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004092
Jianing Wei90e59c92014-03-12 18:29:36 -07004093 unpauseForNewRequests();
4094
4095 return OK;
4096}
4097
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004098
4099status_t Camera3Device::RequestThread::queueTrigger(
4100 RequestTrigger trigger[],
4101 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004102 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004103 Mutex::Autolock l(mTriggerMutex);
4104 status_t ret;
4105
4106 for (size_t i = 0; i < count; ++i) {
4107 ret = queueTriggerLocked(trigger[i]);
4108
4109 if (ret != OK) {
4110 return ret;
4111 }
4112 }
4113
4114 return OK;
4115}
4116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4118 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004119 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004120 if (d != nullptr) return d->mId;
4121 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004122}
4123
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004124status_t Camera3Device::RequestThread::queueTriggerLocked(
4125 RequestTrigger trigger) {
4126
4127 uint32_t tag = trigger.metadataTag;
4128 ssize_t index = mTriggerMap.indexOfKey(tag);
4129
4130 switch (trigger.getTagType()) {
4131 case TYPE_BYTE:
4132 // fall-through
4133 case TYPE_INT32:
4134 break;
4135 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004136 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4137 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004138 return INVALID_OPERATION;
4139 }
4140
4141 /**
4142 * Collect only the latest trigger, since we only have 1 field
4143 * in the request settings per trigger tag, and can't send more than 1
4144 * trigger per request.
4145 */
4146 if (index != NAME_NOT_FOUND) {
4147 mTriggerMap.editValueAt(index) = trigger;
4148 } else {
4149 mTriggerMap.add(tag, trigger);
4150 }
4151
4152 return OK;
4153}
4154
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004155status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004156 const RequestList &requests,
4157 /*out*/
4158 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004159 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004160 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004161 if (lastFrameNumber != NULL) {
4162 *lastFrameNumber = mRepeatingLastFrameNumber;
4163 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 mRepeatingRequests.clear();
4165 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4166 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004167
4168 unpauseForNewRequests();
4169
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004170 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004171 return OK;
4172}
4173
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004174bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004175 if (mRepeatingRequests.empty()) {
4176 return false;
4177 }
4178 int32_t requestId = requestIn->mResultExtras.requestId;
4179 const RequestList &repeatRequests = mRepeatingRequests;
4180 // All repeating requests are guaranteed to have same id so only check first quest
4181 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4182 return (firstRequest->mResultExtras.requestId == requestId);
4183}
4184
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004185status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004186 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004187 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004188 return clearRepeatingRequestsLocked(lastFrameNumber);
4189
4190}
4191
4192status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004193 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004194 if (lastFrameNumber != NULL) {
4195 *lastFrameNumber = mRepeatingLastFrameNumber;
4196 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004197 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004198 return OK;
4199}
4200
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004201status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004202 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004203 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004204 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004205 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004206
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004207 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004208
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004209 // Send errors for all requests pending in the request queue, including
4210 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004211 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004212 if (listener != NULL) {
4213 for (RequestList::iterator it = mRequestQueue.begin();
4214 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004215 // Abort the input buffers for reprocess requests.
4216 if ((*it)->mInputStream != NULL) {
4217 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004218 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4219 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004220 if (res != OK) {
4221 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4222 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4223 } else {
4224 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4225 if (res != OK) {
4226 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4227 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4228 }
4229 }
4230 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004231 // Set the frame number this request would have had, if it
4232 // had been submitted; this frame number will not be reused.
4233 // The requestId and burstId fields were set when the request was
4234 // submitted originally (in convertMetadataListToRequestListLocked)
4235 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004236 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004237 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004238 }
4239 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004240 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004241
4242 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004243 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004244 if (lastFrameNumber != NULL) {
4245 *lastFrameNumber = mRepeatingLastFrameNumber;
4246 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004247 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004248 return OK;
4249}
4250
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004251status_t Camera3Device::RequestThread::flush() {
4252 ATRACE_CALL();
4253 Mutex::Autolock l(mFlushLock);
4254
Emilian Peev08dd2452017-04-06 16:55:14 +01004255 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004256}
4257
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004259 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 Mutex::Autolock l(mPauseLock);
4261 mDoPause = paused;
4262 mDoPauseSignal.signal();
4263}
4264
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004265status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4266 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004267 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004268 Mutex::Autolock l(mLatestRequestMutex);
4269 status_t res;
4270 while (mLatestRequestId != requestId) {
4271 nsecs_t startTime = systemTime();
4272
4273 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4274 if (res != OK) return res;
4275
4276 timeout -= (systemTime() - startTime);
4277 }
4278
4279 return OK;
4280}
4281
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004282void Camera3Device::RequestThread::requestExit() {
4283 // Call parent to set up shutdown
4284 Thread::requestExit();
4285 // The exit from any possible waits
4286 mDoPauseSignal.signal();
4287 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004288
4289 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4290 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004291}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004292
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004293void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004294 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004295 bool surfaceAbandoned = false;
4296 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004297 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004298 {
4299 Mutex::Autolock l(mRequestLock);
4300 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4301 // repeating requests.
4302 for (const auto& request : mRepeatingRequests) {
4303 for (const auto& s : request->mOutputStreams) {
4304 if (s->isAbandoned()) {
4305 surfaceAbandoned = true;
4306 clearRepeatingRequestsLocked(&lastFrameNumber);
4307 break;
4308 }
4309 }
4310 if (surfaceAbandoned) {
4311 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004312 }
4313 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004314 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004315 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004316
4317 if (listener != NULL && surfaceAbandoned) {
4318 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004319 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004320}
4321
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004322bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004323 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004324 status_t res;
4325 size_t batchSize = mNextRequests.size();
4326 std::vector<camera3_capture_request_t*> requests(batchSize);
4327 uint32_t numRequestProcessed = 0;
4328 for (size_t i = 0; i < batchSize; i++) {
4329 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004330 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004331 }
4332
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004333 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4334
4335 bool triggerRemoveFailed = false;
4336 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4337 for (size_t i = 0; i < numRequestProcessed; i++) {
4338 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4339 nextRequest.submitted = true;
4340
4341
4342 // Update the latest request sent to HAL
4343 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4344 Mutex::Autolock al(mLatestRequestMutex);
4345
4346 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4347 mLatestRequest.acquire(cloned);
4348
4349 sp<Camera3Device> parent = mParent.promote();
4350 if (parent != NULL) {
4351 parent->monitorMetadata(TagMonitor::REQUEST,
4352 nextRequest.halRequest.frame_number,
4353 0, mLatestRequest);
4354 }
4355 }
4356
4357 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004358 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4359 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004360 }
4361
Emilian Peevaebbe412018-01-15 13:53:24 +00004362 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4363
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004364 if (!triggerRemoveFailed) {
4365 // Remove any previously queued triggers (after unlock)
4366 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4367 if (removeTriggerRes != OK) {
4368 triggerRemoveFailed = true;
4369 triggerFailedRequest = nextRequest;
4370 }
4371 }
4372 }
4373
4374 if (triggerRemoveFailed) {
4375 SET_ERR("RequestThread: Unable to remove triggers "
4376 "(capture request %d, HAL device: %s (%d)",
4377 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4378 cleanUpFailedRequests(/*sendRequestError*/ false);
4379 return false;
4380 }
4381
4382 if (res != OK) {
4383 // Should only get a failure here for malformed requests or device-level
4384 // errors, so consider all errors fatal. Bad metadata failures should
4385 // come through notify.
4386 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4387 mNextRequests[numRequestProcessed].halRequest.frame_number,
4388 strerror(-res), res);
4389 cleanUpFailedRequests(/*sendRequestError*/ false);
4390 return false;
4391 }
4392 return true;
4393}
4394
4395bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4396 status_t res;
4397
4398 for (auto& nextRequest : mNextRequests) {
4399 // Submit request and block until ready for next one
4400 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4401 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4402
4403 if (res != OK) {
4404 // Should only get a failure here for malformed requests or device-level
4405 // errors, so consider all errors fatal. Bad metadata failures should
4406 // come through notify.
4407 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4408 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4409 res);
4410 cleanUpFailedRequests(/*sendRequestError*/ false);
4411 return false;
4412 }
4413
4414 // Mark that the request has be submitted successfully.
4415 nextRequest.submitted = true;
4416
4417 // Update the latest request sent to HAL
4418 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4419 Mutex::Autolock al(mLatestRequestMutex);
4420
4421 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4422 mLatestRequest.acquire(cloned);
4423
4424 sp<Camera3Device> parent = mParent.promote();
4425 if (parent != NULL) {
4426 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4427 0, mLatestRequest);
4428 }
4429 }
4430
4431 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004432 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4433 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004434 }
4435
Emilian Peevaebbe412018-01-15 13:53:24 +00004436 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4437
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004438 // Remove any previously queued triggers (after unlock)
4439 res = removeTriggers(mPrevRequest);
4440 if (res != OK) {
4441 SET_ERR("RequestThread: Unable to remove triggers "
4442 "(capture request %d, HAL device: %s (%d)",
4443 nextRequest.halRequest.frame_number, strerror(-res), res);
4444 cleanUpFailedRequests(/*sendRequestError*/ false);
4445 return false;
4446 }
4447 }
4448 return true;
4449}
4450
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004451nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4452 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4453 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4454 find_camera_metadata_ro_entry(request,
4455 ANDROID_CONTROL_AE_MODE,
4456 &e);
4457 if (e.count == 0) return maxExpectedDuration;
4458
4459 switch (e.data.u8[0]) {
4460 case ANDROID_CONTROL_AE_MODE_OFF:
4461 find_camera_metadata_ro_entry(request,
4462 ANDROID_SENSOR_EXPOSURE_TIME,
4463 &e);
4464 if (e.count > 0) {
4465 maxExpectedDuration = e.data.i64[0];
4466 }
4467 find_camera_metadata_ro_entry(request,
4468 ANDROID_SENSOR_FRAME_DURATION,
4469 &e);
4470 if (e.count > 0) {
4471 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4472 }
4473 break;
4474 default:
4475 find_camera_metadata_ro_entry(request,
4476 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4477 &e);
4478 if (e.count > 1) {
4479 maxExpectedDuration = 1e9 / e.data.u8[0];
4480 }
4481 break;
4482 }
4483
4484 return maxExpectedDuration;
4485}
4486
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004487bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4488 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4489 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4490 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4491 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4492 return true;
4493 }
4494
4495 return false;
4496}
4497
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004498bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4499 ATRACE_CALL();
4500 bool updatesDetected = false;
4501
4502 for (auto tag : mSessionParamKeys) {
4503 camera_metadata_ro_entry entry = settings.find(tag);
4504 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4505
4506 if (entry.count > 0) {
4507 bool isDifferent = false;
4508 if (lastEntry.count > 0) {
4509 // Have a last value, compare to see if changed
4510 if (lastEntry.type == entry.type &&
4511 lastEntry.count == entry.count) {
4512 // Same type and count, compare values
4513 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4514 size_t entryBytes = bytesPerValue * lastEntry.count;
4515 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4516 if (cmp != 0) {
4517 isDifferent = true;
4518 }
4519 } else {
4520 // Count or type has changed
4521 isDifferent = true;
4522 }
4523 } else {
4524 // No last entry, so always consider to be different
4525 isDifferent = true;
4526 }
4527
4528 if (isDifferent) {
4529 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004530 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4531 updatesDetected = true;
4532 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004533 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004534 }
4535 } else if (lastEntry.count > 0) {
4536 // Value has been removed
4537 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4538 mLatestSessionParams.erase(tag);
4539 updatesDetected = true;
4540 }
4541 }
4542
4543 return updatesDetected;
4544}
4545
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004546bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004547 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004548 status_t res;
4549
4550 // Handle paused state.
4551 if (waitIfPaused()) {
4552 return true;
4553 }
4554
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004555 // Wait for the next batch of requests.
4556 waitForNextRequestBatch();
4557 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004558 return true;
4559 }
4560
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004561 // Get the latest request ID, if any
4562 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004563 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004564 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004565 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004566 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004567 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004568 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4569 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004570 }
4571
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004572 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4573 // or a single request from streaming or burst. In either case the first element
4574 // should contain the latest camera settings that we need to check for any session
4575 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004576 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004577 res = OK;
4578
4579 //Input stream buffers are already acquired at this point so an input stream
4580 //will not be able to move to idle state unless we force it.
4581 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4582 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4583 if (res != OK) {
4584 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4585 cleanUpFailedRequests(/*sendRequestError*/ false);
4586 return false;
4587 }
4588 }
4589
4590 if (res == OK) {
4591 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4592 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004593 sp<Camera3Device> parent = mParent.promote();
4594 if (parent != nullptr) {
4595 parent->pauseStateNotify(true);
4596 }
4597
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004598 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4599
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004600 if (parent != nullptr) {
4601 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4602 }
4603
4604 statusTracker->markComponentActive(mStatusId);
4605 setPaused(false);
4606 }
4607
4608 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4609 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4610 if (res != OK) {
4611 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4612 cleanUpFailedRequests(/*sendRequestError*/ false);
4613 return false;
4614 }
4615 }
4616 }
4617 }
4618
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004619 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004620 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004621 if (res == TIMED_OUT) {
4622 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004623 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004624 // Check if any stream is abandoned.
4625 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004626 return true;
4627 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004628 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004629 return false;
4630 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004631
Zhijun Hecc27e112013-10-03 16:12:43 -07004632 // Inform waitUntilRequestProcessed thread of a new request ID
4633 {
4634 Mutex::Autolock al(mLatestRequestMutex);
4635
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004636 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004637 mLatestRequestSignal.signal();
4638 }
4639
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004640 // Submit a batch of requests to HAL.
4641 // Use flush lock only when submitting multilple requests in a batch.
4642 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4643 // which may take a long time to finish so synchronizing flush() and
4644 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4645 // For now, only synchronize for high speed recording and we should figure something out for
4646 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004647 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004648
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004649 if (useFlushLock) {
4650 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004651 }
4652
Zhijun Hef0645c12016-08-02 00:58:11 -07004653 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004654 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004655
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004656 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004657 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004658 if (mInterface->supportBatchRequest()) {
4659 submitRequestSuccess = sendRequestsBatch();
4660 } else {
4661 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004662 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004663 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4664 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004665
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004666 if (useFlushLock) {
4667 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004668 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004669
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004670 // Unset as current request
4671 {
4672 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004673 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004674 }
4675
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004676 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004677}
4678
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004679status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004680 ATRACE_CALL();
4681
Shuzhen Wang4a472662017-02-26 23:29:04 -08004682 for (size_t i = 0; i < mNextRequests.size(); i++) {
4683 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004684 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4685 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4686 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4687
4688 // Prepare a request to HAL
4689 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4690
4691 // Insert any queued triggers (before metadata is locked)
4692 status_t res = insertTriggers(captureRequest);
4693
4694 if (res < 0) {
4695 SET_ERR("RequestThread: Unable to insert triggers "
4696 "(capture request %d, HAL device: %s (%d)",
4697 halRequest->frame_number, strerror(-res), res);
4698 return INVALID_OPERATION;
4699 }
4700 int triggerCount = res;
4701 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4702 mPrevTriggers = triggerCount;
4703
4704 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004705 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4706 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004707 /**
4708 * HAL workaround:
4709 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4710 */
4711 res = addDummyTriggerIds(captureRequest);
4712 if (res != OK) {
4713 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4714 "(capture request %d, HAL device: %s (%d)",
4715 halRequest->frame_number, strerror(-res), res);
4716 return INVALID_OPERATION;
4717 }
4718
4719 /**
4720 * The request should be presorted so accesses in HAL
4721 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4722 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004723 captureRequest->mSettingsList.begin()->metadata.sort();
4724 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004725 mPrevRequest = captureRequest;
4726 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4727
4728 IF_ALOGV() {
4729 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4730 find_camera_metadata_ro_entry(
4731 halRequest->settings,
4732 ANDROID_CONTROL_AF_TRIGGER,
4733 &e
4734 );
4735 if (e.count > 0) {
4736 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4737 __FUNCTION__,
4738 halRequest->frame_number,
4739 e.data.u8[0]);
4740 }
4741 }
4742 } else {
4743 // leave request.settings NULL to indicate 'reuse latest given'
4744 ALOGVV("%s: Request settings are REUSED",
4745 __FUNCTION__);
4746 }
4747
Emilian Peevaebbe412018-01-15 13:53:24 +00004748 if (captureRequest->mSettingsList.size() > 1) {
4749 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4750 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004751 if (newRequest) {
4752 halRequest->physcam_settings =
4753 new const camera_metadata* [halRequest->num_physcam_settings];
4754 } else {
4755 halRequest->physcam_settings = nullptr;
4756 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004757 auto it = ++captureRequest->mSettingsList.begin();
4758 size_t i = 0;
4759 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4760 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004761 if (newRequest) {
4762 it->metadata.sort();
4763 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4764 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004765 }
4766 }
4767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004768 uint32_t totalNumBuffers = 0;
4769
4770 // Fill in buffers
4771 if (captureRequest->mInputStream != NULL) {
4772 halRequest->input_buffer = &captureRequest->mInputBuffer;
4773 totalNumBuffers += 1;
4774 } else {
4775 halRequest->input_buffer = NULL;
4776 }
4777
4778 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4779 captureRequest->mOutputStreams.size());
4780 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004781 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004782 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4783 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004784
4785 // Prepare video buffers for high speed recording on the first video request.
4786 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4787 // Only try to prepare video stream on the first video request.
4788 mPrepareVideoStream = false;
4789
4790 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4791 while (res == NOT_ENOUGH_DATA) {
4792 res = outputStream->prepareNextBuffer();
4793 }
4794 if (res != OK) {
4795 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4796 __FUNCTION__, strerror(-res), res);
4797 outputStream->cancelPrepare();
4798 }
4799 }
4800
Shuzhen Wang4a472662017-02-26 23:29:04 -08004801 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4802 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004803 if (res != OK) {
4804 // Can't get output buffer from gralloc queue - this could be due to
4805 // abandoned queue or other consumer misbehavior, so not a fatal
4806 // error
4807 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4808 " %s (%d)", strerror(-res), res);
4809
4810 return TIMED_OUT;
4811 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004812
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004813 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4814
4815 if (!physicalCameraId.isEmpty()) {
4816 // Physical stream isn't supported for input request.
4817 if (halRequest->input_buffer) {
4818 CLOGE("Physical stream is not supported for input request");
4819 return INVALID_OPERATION;
4820 }
4821 requestedPhysicalCameras.insert(physicalCameraId);
4822 }
4823 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824 }
4825 totalNumBuffers += halRequest->num_output_buffers;
4826
4827 // Log request in the in-flight queue
4828 sp<Camera3Device> parent = mParent.promote();
4829 if (parent == NULL) {
4830 // Should not happen, and nowhere to send errors to, so just log it
4831 CLOGE("RequestThread: Parent is gone");
4832 return INVALID_OPERATION;
4833 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004834
4835 // If this request list is for constrained high speed recording (not
4836 // preview), and the current request is not the last one in the batch,
4837 // do not send callback to the app.
4838 bool hasCallback = true;
4839 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4840 hasCallback = false;
4841 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004842 res = parent->registerInFlight(halRequest->frame_number,
4843 totalNumBuffers, captureRequest->mResultExtras,
4844 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004845 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004846 calculateMaxExpectedDuration(halRequest->settings),
4847 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004848 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4849 ", burstId = %" PRId32 ".",
4850 __FUNCTION__,
4851 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4852 captureRequest->mResultExtras.burstId);
4853 if (res != OK) {
4854 SET_ERR("RequestThread: Unable to register new in-flight request:"
4855 " %s (%d)", strerror(-res), res);
4856 return INVALID_OPERATION;
4857 }
4858 }
4859
4860 return OK;
4861}
4862
Igor Murashkin1e479c02013-09-06 16:55:14 -07004863CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004864 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004865 Mutex::Autolock al(mLatestRequestMutex);
4866
4867 ALOGV("RequestThread::%s", __FUNCTION__);
4868
4869 return mLatestRequest;
4870}
4871
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004872bool Camera3Device::RequestThread::isStreamPending(
4873 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004874 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004875 Mutex::Autolock l(mRequestLock);
4876
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004877 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004878 if (!nextRequest.submitted) {
4879 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4880 if (stream == s) return true;
4881 }
4882 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004883 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004884 }
4885
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004886 for (const auto& request : mRequestQueue) {
4887 for (const auto& s : request->mOutputStreams) {
4888 if (stream == s) return true;
4889 }
4890 if (stream == request->mInputStream) return true;
4891 }
4892
4893 for (const auto& request : mRepeatingRequests) {
4894 for (const auto& s : request->mOutputStreams) {
4895 if (stream == s) return true;
4896 }
4897 if (stream == request->mInputStream) return true;
4898 }
4899
4900 return false;
4901}
Jianing Weicb0652e2014-03-12 18:29:36 -07004902
Emilian Peev40ead602017-09-26 15:46:36 +01004903bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4904 ATRACE_CALL();
4905 Mutex::Autolock l(mRequestLock);
4906
4907 for (const auto& nextRequest : mNextRequests) {
4908 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4909 if (s.first == streamId) {
4910 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4911 if (it != s.second.end()) {
4912 return true;
4913 }
4914 }
4915 }
4916 }
4917
4918 for (const auto& request : mRequestQueue) {
4919 for (const auto& s : request->mOutputSurfaces) {
4920 if (s.first == streamId) {
4921 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4922 if (it != s.second.end()) {
4923 return true;
4924 }
4925 }
4926 }
4927 }
4928
4929 for (const auto& request : mRepeatingRequests) {
4930 for (const auto& s : request->mOutputSurfaces) {
4931 if (s.first == streamId) {
4932 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4933 if (it != s.second.end()) {
4934 return true;
4935 }
4936 }
4937 }
4938 }
4939
4940 return false;
4941}
4942
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004943nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004944 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004945 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004946 return mExpectedInflightDuration > kMinInflightDuration ?
4947 mExpectedInflightDuration : kMinInflightDuration;
4948}
4949
Emilian Peevaebbe412018-01-15 13:53:24 +00004950void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4951 camera3_capture_request_t *halRequest) {
4952 if ((request == nullptr) || (halRequest == nullptr)) {
4953 ALOGE("%s: Invalid request!", __FUNCTION__);
4954 return;
4955 }
4956
4957 if (halRequest->num_physcam_settings > 0) {
4958 if (halRequest->physcam_id != nullptr) {
4959 delete [] halRequest->physcam_id;
4960 halRequest->physcam_id = nullptr;
4961 }
4962 if (halRequest->physcam_settings != nullptr) {
4963 auto it = ++(request->mSettingsList.begin());
4964 size_t i = 0;
4965 for (; it != request->mSettingsList.end(); it++, i++) {
4966 it->metadata.unlock(halRequest->physcam_settings[i]);
4967 }
4968 delete [] halRequest->physcam_settings;
4969 halRequest->physcam_settings = nullptr;
4970 }
4971 }
4972}
4973
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004974void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4975 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 return;
4977 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004978
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004979 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004980 // Skip the ones that have been submitted successfully.
4981 if (nextRequest.submitted) {
4982 continue;
4983 }
4984
4985 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4986 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4987 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4988
4989 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004990 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004991 }
4992
Emilian Peevaebbe412018-01-15 13:53:24 +00004993 cleanupPhysicalSettings(captureRequest, halRequest);
4994
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004995 if (captureRequest->mInputStream != NULL) {
4996 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4997 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4998 }
4999
5000 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005001 //Buffers that failed processing could still have
5002 //valid acquire fence.
5003 int acquireFence = (*outputBuffers)[i].acquire_fence;
5004 if (0 <= acquireFence) {
5005 close(acquireFence);
5006 outputBuffers->editItemAt(i).acquire_fence = -1;
5007 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005008 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5009 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5010 }
5011
5012 if (sendRequestError) {
5013 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005014 sp<NotificationListener> listener = mListener.promote();
5015 if (listener != NULL) {
5016 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005017 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005018 captureRequest->mResultExtras);
5019 }
5020 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005021
5022 // Remove yet-to-be submitted inflight request from inflightMap
5023 {
5024 sp<Camera3Device> parent = mParent.promote();
5025 if (parent != NULL) {
5026 Mutex::Autolock l(parent->mInFlightLock);
5027 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5028 if (idx >= 0) {
5029 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5030 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5031 parent->removeInFlightMapEntryLocked(idx);
5032 }
5033 }
5034 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005035 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005036
5037 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005038 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039}
5040
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005041void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005042 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005043 // Optimized a bit for the simple steady-state case (single repeating
5044 // request), to avoid putting that request in the queue temporarily.
5045 Mutex::Autolock l(mRequestLock);
5046
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005047 assert(mNextRequests.empty());
5048
5049 NextRequest nextRequest;
5050 nextRequest.captureRequest = waitForNextRequestLocked();
5051 if (nextRequest.captureRequest == nullptr) {
5052 return;
5053 }
5054
5055 nextRequest.halRequest = camera3_capture_request_t();
5056 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005057 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005058
5059 // Wait for additional requests
5060 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5061
5062 for (size_t i = 1; i < batchSize; i++) {
5063 NextRequest additionalRequest;
5064 additionalRequest.captureRequest = waitForNextRequestLocked();
5065 if (additionalRequest.captureRequest == nullptr) {
5066 break;
5067 }
5068
5069 additionalRequest.halRequest = camera3_capture_request_t();
5070 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005071 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005072 }
5073
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005074 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005075 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005076 mNextRequests.size(), batchSize);
5077 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078 }
5079
5080 return;
5081}
5082
5083sp<Camera3Device::CaptureRequest>
5084 Camera3Device::RequestThread::waitForNextRequestLocked() {
5085 status_t res;
5086 sp<CaptureRequest> nextRequest;
5087
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005088 while (mRequestQueue.empty()) {
5089 if (!mRepeatingRequests.empty()) {
5090 // Always atomically enqueue all requests in a repeating request
5091 // list. Guarantees a complete in-sequence set of captures to
5092 // application.
5093 const RequestList &requests = mRepeatingRequests;
5094 RequestList::const_iterator firstRequest =
5095 requests.begin();
5096 nextRequest = *firstRequest;
5097 mRequestQueue.insert(mRequestQueue.end(),
5098 ++firstRequest,
5099 requests.end());
5100 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005101
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005102 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005103
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104 break;
5105 }
5106
5107 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5108
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005109 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5110 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005111 Mutex::Autolock pl(mPauseLock);
5112 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005113 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005114 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005115 // Let the tracker know
5116 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5117 if (statusTracker != 0) {
5118 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5119 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005120 }
5121 // Stop waiting for now and let thread management happen
5122 return NULL;
5123 }
5124 }
5125
5126 if (nextRequest == NULL) {
5127 // Don't have a repeating request already in hand, so queue
5128 // must have an entry now.
5129 RequestList::iterator firstRequest =
5130 mRequestQueue.begin();
5131 nextRequest = *firstRequest;
5132 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005133 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5134 sp<NotificationListener> listener = mListener.promote();
5135 if (listener != NULL) {
5136 listener->notifyRequestQueueEmpty();
5137 }
5138 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005139 }
5140
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005141 // In case we've been unpaused by setPaused clearing mDoPause, need to
5142 // update internal pause state (capture/setRepeatingRequest unpause
5143 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005144 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005145 if (mPaused) {
5146 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5147 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5148 if (statusTracker != 0) {
5149 statusTracker->markComponentActive(mStatusId);
5150 }
5151 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005152 mPaused = false;
5153
5154 // Check if we've reconfigured since last time, and reset the preview
5155 // request if so. Can't use 'NULL request == repeat' across configure calls.
5156 if (mReconfigured) {
5157 mPrevRequest.clear();
5158 mReconfigured = false;
5159 }
5160
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005161 if (nextRequest != NULL) {
5162 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005163 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5164 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005165
5166 // Since RequestThread::clear() removes buffers from the input stream,
5167 // get the right buffer here before unlocking mRequestLock
5168 if (nextRequest->mInputStream != NULL) {
5169 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5170 if (res != OK) {
5171 // Can't get input buffer from gralloc queue - this could be due to
5172 // disconnected queue or other producer misbehavior, so not a fatal
5173 // error
5174 ALOGE("%s: Can't get input buffer, skipping request:"
5175 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005176
5177 sp<NotificationListener> listener = mListener.promote();
5178 if (listener != NULL) {
5179 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005180 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005181 nextRequest->mResultExtras);
5182 }
5183 return NULL;
5184 }
5185 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005186 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005188 return nextRequest;
5189}
5190
5191bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005192 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005193 status_t res;
5194 Mutex::Autolock l(mPauseLock);
5195 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005196 if (mPaused == false) {
5197 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005198 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5199 // Let the tracker know
5200 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5201 if (statusTracker != 0) {
5202 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5203 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005204 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005205
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005206 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005207 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005208 return true;
5209 }
5210 }
5211 // We don't set mPaused to false here, because waitForNextRequest needs
5212 // to further manage the paused state in case of starvation.
5213 return false;
5214}
5215
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005216void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005217 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005218 // With work to do, mark thread as unpaused.
5219 // If paused by request (setPaused), don't resume, to avoid
5220 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005221 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005222 Mutex::Autolock p(mPauseLock);
5223 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005224 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5225 if (mPaused) {
5226 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5227 if (statusTracker != 0) {
5228 statusTracker->markComponentActive(mStatusId);
5229 }
5230 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005231 mPaused = false;
5232 }
5233}
5234
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005235void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5236 sp<Camera3Device> parent = mParent.promote();
5237 if (parent != NULL) {
5238 va_list args;
5239 va_start(args, fmt);
5240
5241 parent->setErrorStateV(fmt, args);
5242
5243 va_end(args);
5244 }
5245}
5246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005247status_t Camera3Device::RequestThread::insertTriggers(
5248 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005249 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005250 Mutex::Autolock al(mTriggerMutex);
5251
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005252 sp<Camera3Device> parent = mParent.promote();
5253 if (parent == NULL) {
5254 CLOGE("RequestThread: Parent is gone");
5255 return DEAD_OBJECT;
5256 }
5257
Emilian Peevaebbe412018-01-15 13:53:24 +00005258 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005259 size_t count = mTriggerMap.size();
5260
5261 for (size_t i = 0; i < count; ++i) {
5262 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005263 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005264
5265 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5266 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5267 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005268 if (isAeTrigger) {
5269 request->mResultExtras.precaptureTriggerId = triggerId;
5270 mCurrentPreCaptureTriggerId = triggerId;
5271 } else {
5272 request->mResultExtras.afTriggerId = triggerId;
5273 mCurrentAfTriggerId = triggerId;
5274 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005275 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005276 }
5277
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005278 camera_metadata_entry entry = metadata.find(tag);
5279
5280 if (entry.count > 0) {
5281 /**
5282 * Already has an entry for this trigger in the request.
5283 * Rewrite it with our requested trigger value.
5284 */
5285 RequestTrigger oldTrigger = trigger;
5286
5287 oldTrigger.entryValue = entry.data.u8[0];
5288
5289 mTriggerReplacedMap.add(tag, oldTrigger);
5290 } else {
5291 /**
5292 * More typical, no trigger entry, so we just add it
5293 */
5294 mTriggerRemovedMap.add(tag, trigger);
5295 }
5296
5297 status_t res;
5298
5299 switch (trigger.getTagType()) {
5300 case TYPE_BYTE: {
5301 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5302 res = metadata.update(tag,
5303 &entryValue,
5304 /*count*/1);
5305 break;
5306 }
5307 case TYPE_INT32:
5308 res = metadata.update(tag,
5309 &trigger.entryValue,
5310 /*count*/1);
5311 break;
5312 default:
5313 ALOGE("%s: Type not supported: 0x%x",
5314 __FUNCTION__,
5315 trigger.getTagType());
5316 return INVALID_OPERATION;
5317 }
5318
5319 if (res != OK) {
5320 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5321 ", value %d", __FUNCTION__, trigger.getTagName(),
5322 trigger.entryValue);
5323 return res;
5324 }
5325
5326 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5327 trigger.getTagName(),
5328 trigger.entryValue);
5329 }
5330
5331 mTriggerMap.clear();
5332
5333 return count;
5334}
5335
5336status_t Camera3Device::RequestThread::removeTriggers(
5337 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005338 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005339 Mutex::Autolock al(mTriggerMutex);
5340
Emilian Peevaebbe412018-01-15 13:53:24 +00005341 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005342
5343 /**
5344 * Replace all old entries with their old values.
5345 */
5346 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5347 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5348
5349 status_t res;
5350
5351 uint32_t tag = trigger.metadataTag;
5352 switch (trigger.getTagType()) {
5353 case TYPE_BYTE: {
5354 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5355 res = metadata.update(tag,
5356 &entryValue,
5357 /*count*/1);
5358 break;
5359 }
5360 case TYPE_INT32:
5361 res = metadata.update(tag,
5362 &trigger.entryValue,
5363 /*count*/1);
5364 break;
5365 default:
5366 ALOGE("%s: Type not supported: 0x%x",
5367 __FUNCTION__,
5368 trigger.getTagType());
5369 return INVALID_OPERATION;
5370 }
5371
5372 if (res != OK) {
5373 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5374 ", trigger value %d", __FUNCTION__,
5375 trigger.getTagName(), trigger.entryValue);
5376 return res;
5377 }
5378 }
5379 mTriggerReplacedMap.clear();
5380
5381 /**
5382 * Remove all new entries.
5383 */
5384 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5385 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5386 status_t res = metadata.erase(trigger.metadataTag);
5387
5388 if (res != OK) {
5389 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5390 ", trigger value %d", __FUNCTION__,
5391 trigger.getTagName(), trigger.entryValue);
5392 return res;
5393 }
5394 }
5395 mTriggerRemovedMap.clear();
5396
5397 return OK;
5398}
5399
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005400status_t Camera3Device::RequestThread::addDummyTriggerIds(
5401 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005402 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005403 static const int32_t dummyTriggerId = 1;
5404 status_t res;
5405
Emilian Peevaebbe412018-01-15 13:53:24 +00005406 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005407
5408 // If AF trigger is active, insert a dummy AF trigger ID if none already
5409 // exists
5410 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5411 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5412 if (afTrigger.count > 0 &&
5413 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5414 afId.count == 0) {
5415 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5416 if (res != OK) return res;
5417 }
5418
5419 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5420 // if none already exists
5421 camera_metadata_entry pcTrigger =
5422 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5423 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5424 if (pcTrigger.count > 0 &&
5425 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5426 pcId.count == 0) {
5427 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5428 &dummyTriggerId, 1);
5429 if (res != OK) return res;
5430 }
5431
5432 return OK;
5433}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005434
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005435/**
5436 * PreparerThread inner class methods
5437 */
5438
5439Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005440 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005441 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005442}
5443
5444Camera3Device::PreparerThread::~PreparerThread() {
5445 Thread::requestExitAndWait();
5446 if (mCurrentStream != nullptr) {
5447 mCurrentStream->cancelPrepare();
5448 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5449 mCurrentStream.clear();
5450 }
5451 clear();
5452}
5453
Ruben Brunkc78ac262015-08-13 17:58:46 -07005454status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005455 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005456 status_t res;
5457
5458 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005459 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005460
Ruben Brunkc78ac262015-08-13 17:58:46 -07005461 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005462 if (res == OK) {
5463 // No preparation needed, fire listener right off
5464 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005465 if (listener != NULL) {
5466 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005467 }
5468 return OK;
5469 } else if (res != NOT_ENOUGH_DATA) {
5470 return res;
5471 }
5472
5473 // Need to prepare, start up thread if necessary
5474 if (!mActive) {
5475 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5476 // isn't running
5477 Thread::requestExitAndWait();
5478 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5479 if (res != OK) {
5480 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005481 if (listener != NULL) {
5482 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005483 }
5484 return res;
5485 }
5486 mCancelNow = false;
5487 mActive = true;
5488 ALOGV("%s: Preparer stream started", __FUNCTION__);
5489 }
5490
5491 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005492 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005493 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5494
5495 return OK;
5496}
5497
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005498void Camera3Device::PreparerThread::pause() {
5499 ATRACE_CALL();
5500
5501 Mutex::Autolock l(mLock);
5502
5503 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5504 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5505 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5506 int currentMaxCount = mCurrentMaxCount;
5507 mPendingStreams.clear();
5508 mCancelNow = true;
5509 while (mActive) {
5510 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5511 if (res == TIMED_OUT) {
5512 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5513 return;
5514 } else if (res != OK) {
5515 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5516 return;
5517 }
5518 }
5519
5520 //Check whether the prepare thread was able to complete the current
5521 //stream. In case work is still pending emplace it along with the rest
5522 //of the streams in the pending list.
5523 if (currentStream != nullptr) {
5524 if (!mCurrentPrepareComplete) {
5525 pendingStreams.emplace(currentMaxCount, currentStream);
5526 }
5527 }
5528
5529 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5530 for (const auto& it : mPendingStreams) {
5531 it.second->cancelPrepare();
5532 }
5533}
5534
5535status_t Camera3Device::PreparerThread::resume() {
5536 ATRACE_CALL();
5537 status_t res;
5538
5539 Mutex::Autolock l(mLock);
5540 sp<NotificationListener> listener = mListener.promote();
5541
5542 if (mActive) {
5543 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5544 return NO_INIT;
5545 }
5546
5547 auto it = mPendingStreams.begin();
5548 for (; it != mPendingStreams.end();) {
5549 res = it->second->startPrepare(it->first);
5550 if (res == OK) {
5551 if (listener != NULL) {
5552 listener->notifyPrepared(it->second->getId());
5553 }
5554 it = mPendingStreams.erase(it);
5555 } else if (res != NOT_ENOUGH_DATA) {
5556 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5557 res, strerror(-res));
5558 it = mPendingStreams.erase(it);
5559 } else {
5560 it++;
5561 }
5562 }
5563
5564 if (mPendingStreams.empty()) {
5565 return OK;
5566 }
5567
5568 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5569 if (res != OK) {
5570 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5571 __FUNCTION__, res, strerror(-res));
5572 return res;
5573 }
5574 mCancelNow = false;
5575 mActive = true;
5576 ALOGV("%s: Preparer stream started", __FUNCTION__);
5577
5578 return OK;
5579}
5580
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005581status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005582 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005583 Mutex::Autolock l(mLock);
5584
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005585 for (const auto& it : mPendingStreams) {
5586 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005587 }
5588 mPendingStreams.clear();
5589 mCancelNow = true;
5590
5591 return OK;
5592}
5593
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005594void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005595 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596 Mutex::Autolock l(mLock);
5597 mListener = listener;
5598}
5599
5600bool Camera3Device::PreparerThread::threadLoop() {
5601 status_t res;
5602 {
5603 Mutex::Autolock l(mLock);
5604 if (mCurrentStream == nullptr) {
5605 // End thread if done with work
5606 if (mPendingStreams.empty()) {
5607 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5608 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5609 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5610 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005611 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005612 return false;
5613 }
5614
5615 // Get next stream to prepare
5616 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005617 mCurrentStream = it->second;
5618 mCurrentMaxCount = it->first;
5619 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005620 mPendingStreams.erase(it);
5621 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5622 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5623 } else if (mCancelNow) {
5624 mCurrentStream->cancelPrepare();
5625 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5626 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5627 mCurrentStream.clear();
5628 mCancelNow = false;
5629 return true;
5630 }
5631 }
5632
5633 res = mCurrentStream->prepareNextBuffer();
5634 if (res == NOT_ENOUGH_DATA) return true;
5635 if (res != OK) {
5636 // Something bad happened; try to recover by cancelling prepare and
5637 // signalling listener anyway
5638 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5639 mCurrentStream->getId(), res, strerror(-res));
5640 mCurrentStream->cancelPrepare();
5641 }
5642
5643 // This stream has finished, notify listener
5644 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005645 sp<NotificationListener> listener = mListener.promote();
5646 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005647 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5648 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005649 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005650 }
5651
5652 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5653 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005654 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005655
5656 return true;
5657}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005658
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005659/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005660 * Static callback forwarding methods from HAL to instance
5661 */
5662
5663void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5664 const camera3_capture_result *result) {
5665 Camera3Device *d =
5666 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005667
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005668 d->processCaptureResult(result);
5669}
5670
5671void Camera3Device::sNotify(const camera3_callback_ops *cb,
5672 const camera3_notify_msg *msg) {
5673 Camera3Device *d =
5674 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5675 d->notify(msg);
5676}
5677
5678}; // namespace android