blob: 2d77b2ea8812b6acd70eda308931d0d311a9e0b7 [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
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
Emilian Peev5fbe0ba2017-10-20 15:45:45 +010058#include <android/hardware/camera/device/3.4/ICameraDeviceSession.h>
59
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060using 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
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
100 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());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172
173 return initializeCommonLocked();
174}
175
176status_t Camera3Device::initializeCommonLocked() {
177
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700178 /** Start up status tracker thread */
179 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800180 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700181 if (res != OK) {
182 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
183 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800184 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700185 mStatusTracker.clear();
186 return res;
187 }
188
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700189 /** Register in-flight map to the status tracker */
190 mInFlightStatusId = mStatusTracker->addComponent();
191
Zhijun He125684a2015-12-26 15:07:30 -0800192 /** Create buffer manager */
193 mBufferManager = new Camera3BufferManager();
194
Emilian Peev71c73a22017-03-21 16:35:51 +0000195 mTagMonitor.initialize(mVendorTagId);
196
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000197 Vector<int32_t> sessionParamKeys;
198 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
199 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
200 if (sessionKeysEntry.count > 0) {
201 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
202 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700203 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000204 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800205 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800206 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700207 SET_ERR_L("Unable to start request queue thread: %s (%d)",
208 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800209 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800210 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800211 return res;
212 }
213
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700214 mPreparerThread = new PreparerThread();
215
Ruben Brunk183f0562015-08-12 12:55:02 -0700216 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800217 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700218 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700219 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700220 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800221
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800222 // Measure the clock domain offset between camera and video/hw_composer
223 camera_metadata_entry timestampSource =
224 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
225 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
226 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
227 mTimestampOffset = getMonoToBoottimeOffset();
228 }
229
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700230 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100231 camera_metadata_entry partialResultsCount =
232 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
233 if (partialResultsCount.count > 0) {
234 mNumPartialResults = partialResultsCount.data.i32[0];
235 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700236 }
237
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700238 camera_metadata_entry configs =
239 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
240 for (uint32_t i = 0; i < configs.count; i += 4) {
241 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
242 configs.data.i32[i + 3] ==
243 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
244 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
245 configs.data.i32[i + 2]));
246 }
247 }
248
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800249 return OK;
250}
251
252status_t Camera3Device::disconnect() {
253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800255
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700256 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800257
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700258 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700259 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700260 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 {
262 Mutex::Autolock l(mLock);
263 if (mStatus == STATUS_UNINITIALIZED) return res;
264
265 if (mStatus == STATUS_ACTIVE ||
266 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
267 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700268 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700270 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700271 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700272 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700274 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
275 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 // Continue to close device even in case of error
277 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700278 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800279 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800280
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 if (mStatus == STATUS_ERROR) {
282 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700283 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284
285 if (mStatusTracker != NULL) {
286 mStatusTracker->requestExit();
287 }
288
289 if (mRequestThread != NULL) {
290 mRequestThread->requestExit();
291 }
292
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700293 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
294 for (size_t i = 0; i < mOutputStreams.size(); i++) {
295 streams.push_back(mOutputStreams[i]);
296 }
297 if (mInputStream != nullptr) {
298 streams.push_back(mInputStream);
299 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 }
301
302 // Joining done without holding mLock, otherwise deadlocks may ensue
303 // as the threads try to access parent state
304 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
305 // HAL may be in a bad state, so waiting for request thread
306 // (which may be stuck in the HAL processCaptureRequest call)
307 // could be dangerous.
308 mRequestThread->join();
309 }
310
311 if (mStatusTracker != NULL) {
312 mStatusTracker->join();
313 }
314
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800315 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 {
317 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800318 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800320 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700321 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700323 // Call close without internal mutex held, as the HAL close may need to
324 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800325 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700326
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700327 flushInflightRequests();
328
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700329 {
330 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800331 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700332 mOutputStreams.clear();
333 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700334 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700335 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700336 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700337 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800338
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 for (auto& weakStream : streams) {
340 sp<Camera3StreamInterface> stream = weakStream.promote();
341 if (stream != nullptr) {
342 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
343 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
344 }
345 }
346
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700347 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700348 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800349}
350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700351// For dumping/debugging only -
352// try to acquire a lock a few times, eventually give up to proceed with
353// debug/dump operations
354bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
355 bool gotLock = false;
356 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
357 if (lock.tryLock() == NO_ERROR) {
358 gotLock = true;
359 break;
360 } else {
361 usleep(kDumpSleepDuration);
362 }
363 }
364 return gotLock;
365}
366
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700367Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
368 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100369 const int STREAM_CONFIGURATION_SIZE = 4;
370 const int STREAM_FORMAT_OFFSET = 0;
371 const int STREAM_WIDTH_OFFSET = 1;
372 const int STREAM_HEIGHT_OFFSET = 2;
373 const int STREAM_IS_INPUT_OFFSET = 3;
374 camera_metadata_ro_entry_t availableStreamConfigs =
375 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
376 if (availableStreamConfigs.count == 0 ||
377 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
378 return Size(0, 0);
379 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700380
Emilian Peev08dd2452017-04-06 16:55:14 +0100381 // Get max jpeg size (area-wise).
382 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
383 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
384 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
385 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
386 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
387 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
388 && format == HAL_PIXEL_FORMAT_BLOB &&
389 (width * height > maxJpegWidth * maxJpegHeight)) {
390 maxJpegWidth = width;
391 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700392 }
393 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100394
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700395 return Size(maxJpegWidth, maxJpegHeight);
396}
397
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800398nsecs_t Camera3Device::getMonoToBoottimeOffset() {
399 // try three times to get the clock offset, choose the one
400 // with the minimum gap in measurements.
401 const int tries = 3;
402 nsecs_t bestGap, measured;
403 for (int i = 0; i < tries; ++i) {
404 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
405 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
406 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
407 const nsecs_t gap = tmono2 - tmono;
408 if (i == 0 || gap < bestGap) {
409 bestGap = gap;
410 measured = tbase - ((tmono + tmono2) >> 1);
411 }
412 }
413 return measured;
414}
415
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
417 int frameworkFormat) {
418 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
419}
420
421DataspaceFlags Camera3Device::mapToHidlDataspace(
422 android_dataspace dataSpace) {
423 return dataSpace;
424}
425
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700426BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100427 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700428 return usage;
429}
430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800431StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
432 switch (rotation) {
433 case CAMERA3_STREAM_ROTATION_0:
434 return StreamRotation::ROTATION_0;
435 case CAMERA3_STREAM_ROTATION_90:
436 return StreamRotation::ROTATION_90;
437 case CAMERA3_STREAM_ROTATION_180:
438 return StreamRotation::ROTATION_180;
439 case CAMERA3_STREAM_ROTATION_270:
440 return StreamRotation::ROTATION_270;
441 }
442 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
443 return StreamRotation::ROTATION_0;
444}
445
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800446status_t Camera3Device::mapToStreamConfigurationMode(
447 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
448 if (mode == nullptr) return BAD_VALUE;
449 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
450 switch(operationMode) {
451 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
452 *mode = StreamConfigurationMode::NORMAL_MODE;
453 break;
454 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
455 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
456 break;
457 default:
458 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
459 return BAD_VALUE;
460 }
461 } else {
462 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800463 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800464 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800465}
466
467camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
468 switch (status) {
469 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
470 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
471 }
472 return CAMERA3_BUFFER_STATUS_ERROR;
473}
474
475int Camera3Device::mapToFrameworkFormat(
476 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
477 return static_cast<uint32_t>(pixelFormat);
478}
479
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700480android_dataspace Camera3Device::mapToFrameworkDataspace(
481 DataspaceFlags dataSpace) {
482 return static_cast<android_dataspace>(dataSpace);
483}
484
Emilian Peev050f5dc2017-05-18 14:43:56 +0100485uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700486 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700487 return usage;
488}
489
Emilian Peev050f5dc2017-05-18 14:43:56 +0100490uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700491 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700492 return usage;
493}
494
Zhijun Hef7da0962014-04-24 13:27:56 -0700495ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700496 // Get max jpeg size (area-wise).
497 Size maxJpegResolution = getMaxJpegResolution();
498 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800499 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
500 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700501 return BAD_VALUE;
502 }
503
Zhijun Hef7da0962014-04-24 13:27:56 -0700504 // Get max jpeg buffer size
505 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700506 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
507 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800508 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
509 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700510 return BAD_VALUE;
511 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800513 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700514
515 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700516 float scaleFactor = ((float) (width * height)) /
517 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800518 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
519 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700520 if (jpegBufferSize > maxJpegBufferSize) {
521 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700522 }
523
524 return jpegBufferSize;
525}
526
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700527ssize_t Camera3Device::getPointCloudBufferSize() const {
528 const int FLOATS_PER_POINT=4;
529 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
530 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800531 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
532 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700533 return BAD_VALUE;
534 }
535 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
536 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
537 return maxBytesForPointCloud;
538}
539
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800540ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800541 const int PER_CONFIGURATION_SIZE = 3;
542 const int WIDTH_OFFSET = 0;
543 const int HEIGHT_OFFSET = 1;
544 const int SIZE_OFFSET = 2;
545 camera_metadata_ro_entry rawOpaqueSizes =
546 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800547 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800548 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
550 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800551 return BAD_VALUE;
552 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700553
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800554 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
555 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
556 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
557 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
558 }
559 }
560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800561 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
562 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800563 return BAD_VALUE;
564}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700565
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800566status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
567 ATRACE_CALL();
568 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700569
570 // Try to lock, but continue in case of failure (to avoid blocking in
571 // deadlocks)
572 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
573 bool gotLock = tryLockSpinRightRound(mLock);
574
575 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800576 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
577 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700578 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
580 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700581
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800582 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700583
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800584 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700585 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 int n = args.size();
587 for (int i = 0; i < n; i++) {
588 if (args[i] == templatesOption) {
589 dumpTemplates = true;
590 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700591 if (args[i] == monitorOption) {
592 if (i + 1 < n) {
593 String8 monitorTags = String8(args[i + 1]);
594 if (monitorTags == "off") {
595 mTagMonitor.disableMonitoring();
596 } else {
597 mTagMonitor.parseTagsToMonitor(monitorTags);
598 }
599 } else {
600 mTagMonitor.disableMonitoring();
601 }
602 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800603 }
604
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800605 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800607 const char *status =
608 mStatus == STATUS_ERROR ? "ERROR" :
609 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700610 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
611 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800612 mStatus == STATUS_ACTIVE ? "ACTIVE" :
613 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700614
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800615 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700616 if (mStatus == STATUS_ERROR) {
617 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
618 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800620 const char *mode =
621 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
622 mOperatingMode == static_cast<int>(
623 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
624 "CUSTOM";
625 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800626
627 if (mInputStream != NULL) {
628 write(fd, lines.string(), lines.size());
629 mInputStream->dump(fd, args);
630 } else {
631 lines.appendFormat(" No input stream.\n");
632 write(fd, lines.string(), lines.size());
633 }
634 for (size_t i = 0; i < mOutputStreams.size(); i++) {
635 mOutputStreams[i]->dump(fd,args);
636 }
637
Zhijun He431503c2016-03-07 17:30:16 -0800638 if (mBufferManager != NULL) {
639 lines = String8(" Camera3 Buffer Manager:\n");
640 write(fd, lines.string(), lines.size());
641 mBufferManager->dump(fd, args);
642 }
Zhijun He125684a2015-12-26 15:07:30 -0800643
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700644 lines = String8(" In-flight requests:\n");
645 if (mInFlightMap.size() == 0) {
646 lines.append(" None\n");
647 } else {
648 for (size_t i = 0; i < mInFlightMap.size(); i++) {
649 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700650 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700651 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800652 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700653 r.numBuffersLeft);
654 }
655 }
656 write(fd, lines.string(), lines.size());
657
Shuzhen Wang686f6442017-06-20 16:16:04 -0700658 if (mRequestThread != NULL) {
659 mRequestThread->dumpCaptureRequestLatency(fd,
660 " ProcessCaptureRequest latency histogram:");
661 }
662
Igor Murashkin1e479c02013-09-06 16:55:14 -0700663 {
664 lines = String8(" Last request sent:\n");
665 write(fd, lines.string(), lines.size());
666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700667 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700668 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
669 }
670
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800671 if (dumpTemplates) {
672 const char *templateNames[] = {
673 "TEMPLATE_PREVIEW",
674 "TEMPLATE_STILL_CAPTURE",
675 "TEMPLATE_VIDEO_RECORD",
676 "TEMPLATE_VIDEO_SNAPSHOT",
677 "TEMPLATE_ZERO_SHUTTER_LAG",
678 "TEMPLATE_MANUAL"
679 };
680
681 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800682 camera_metadata_t *templateRequest = nullptr;
683 mInterface->constructDefaultRequestSettings(
684 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800685 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800687 lines.append(" Not supported\n");
688 write(fd, lines.string(), lines.size());
689 } else {
690 write(fd, lines.string(), lines.size());
691 dump_indented_camera_metadata(templateRequest,
692 fd, /*verbosity*/2, /*indentation*/8);
693 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800694 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 }
696 }
697
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700698 mTagMonitor.dumpMonitoredMetadata(fd);
699
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800700 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800701 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800702 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800703 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800704 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800705
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700706 if (gotLock) mLock.unlock();
707 if (gotInterfaceLock) mInterfaceLock.unlock();
708
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800709 return OK;
710}
711
712const CameraMetadata& Camera3Device::info() const {
713 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
715 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700716 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800717 mStatus == STATUS_ERROR ?
718 "when in error state" : "before init");
719 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800720 return mDeviceInfo;
721}
722
Jianing Wei90e59c92014-03-12 18:29:36 -0700723status_t Camera3Device::checkStatusOkToCaptureLocked() {
724 switch (mStatus) {
725 case STATUS_ERROR:
726 CLOGE("Device has encountered a serious error");
727 return INVALID_OPERATION;
728 case STATUS_UNINITIALIZED:
729 CLOGE("Device not initialized");
730 return INVALID_OPERATION;
731 case STATUS_UNCONFIGURED:
732 case STATUS_CONFIGURED:
733 case STATUS_ACTIVE:
734 // OK
735 break;
736 default:
737 SET_ERR_L("Unexpected status: %d", mStatus);
738 return INVALID_OPERATION;
739 }
740 return OK;
741}
742
743status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000744 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700745 const std::list<const SurfaceMap> &surfaceMaps,
746 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700747 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700748 if (requestList == NULL) {
749 CLOGE("requestList cannot be NULL.");
750 return BAD_VALUE;
751 }
752
Jianing Weicb0652e2014-03-12 18:29:36 -0700753 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000754 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700755 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
756 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
757 ++metadataIt, ++surfaceMapIt) {
758 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700759 if (newRequest == 0) {
760 CLOGE("Can't create capture request");
761 return BAD_VALUE;
762 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700763
Shuzhen Wang9d066012016-09-30 11:30:20 -0700764 newRequest->mRepeating = repeating;
765
Jianing Weicb0652e2014-03-12 18:29:36 -0700766 // Setup burst Id and request Id
767 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000768 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
769 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700770 CLOGE("RequestID entry exists; but must not be empty in metadata");
771 return BAD_VALUE;
772 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
774 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700775 } else {
776 CLOGE("RequestID does not exist in metadata");
777 return BAD_VALUE;
778 }
779
Jianing Wei90e59c92014-03-12 18:29:36 -0700780 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700781
782 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700783 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
785 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
786 return BAD_VALUE;
787 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700788
789 // Setup batch size if this is a high speed video recording request.
790 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
791 auto firstRequest = requestList->begin();
792 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
793 if (outputStream->isVideoStream()) {
794 (*firstRequest)->mBatchSize = requestList->size();
795 break;
796 }
797 }
798 }
799
Jianing Wei90e59c92014-03-12 18:29:36 -0700800 return OK;
801}
802
Jianing Weicb0652e2014-03-12 18:29:36 -0700803status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800804 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800805
Emilian Peevaebbe412018-01-15 13:53:24 +0000806 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700807 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000808 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700809
Emilian Peevaebbe412018-01-15 13:53:24 +0000810 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811}
812
Emilian Peevaebbe412018-01-15 13:53:24 +0000813void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700814 std::list<const SurfaceMap>& surfaceMaps,
815 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000816 PhysicalCameraSettingsList requestList;
817 requestList.push_back({std::string(getId().string()), request});
818 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700819
820 SurfaceMap surfaceMap;
821 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
822 // With no surface list passed in, stream and surface will have 1-to-1
823 // mapping. So the surface index is 0 for each stream in the surfaceMap.
824 for (size_t i = 0; i < streams.count; i++) {
825 surfaceMap[streams.data.i32[i]].push_back(0);
826 }
827 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828}
829
Jianing Wei90e59c92014-03-12 18:29:36 -0700830status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000831 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 const std::list<const SurfaceMap> &surfaceMaps,
833 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700834 /*out*/
835 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700836 ATRACE_CALL();
837 Mutex::Autolock il(mInterfaceLock);
838 Mutex::Autolock l(mLock);
839
840 status_t res = checkStatusOkToCaptureLocked();
841 if (res != OK) {
842 // error logged by previous call
843 return res;
844 }
845
846 RequestList requestList;
847
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
849 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850 if (res != OK) {
851 // error logged by previous call
852 return res;
853 }
854
855 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700856 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700857 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700858 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 }
860
861 if (res == OK) {
862 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
863 if (res != OK) {
864 SET_ERR_L("Can't transition to active in %f seconds!",
865 kActiveTimeout/1e9);
866 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800867 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700868 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700869 } else {
870 CLOGE("Cannot queue request. Impossible.");
871 return BAD_VALUE;
872 }
873
874 return res;
875}
876
Yifan Honga640c5a2017-04-12 16:30:31 -0700877// Only one processCaptureResult should be called at a time, so
878// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800879hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800880 const hardware::hidl_vec<
881 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700882 // Ideally we should grab mLock, but that can lead to deadlock, and
883 // it's not super important to get up to date value of mStatus for this
884 // warning print, hence skipping the lock here
885 if (mStatus == STATUS_ERROR) {
886 // Per API contract, HAL should act as closed after device error
887 // But mStatus can be set to error by framework as well, so just log
888 // a warning here.
889 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700890 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700891
892 if (mProcessCaptureResultLock.tryLock() != OK) {
893 // This should never happen; it indicates a wrong client implementation
894 // that doesn't follow the contract. But, we can be tolerant here.
895 ALOGE("%s: callback overlapped! waiting 1s...",
896 __FUNCTION__);
897 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
898 ALOGE("%s: cannot acquire lock in 1s, dropping results",
899 __FUNCTION__);
900 // really don't know what to do, so bail out.
901 return hardware::Void();
902 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800903 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700904 for (const auto& result : results) {
905 processOneCaptureResultLocked(result);
906 }
907 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800908 return hardware::Void();
909}
910
Yifan Honga640c5a2017-04-12 16:30:31 -0700911void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800912 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800913 camera3_capture_result r;
914 status_t res;
915 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700916
917 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
918 if (result.fmqResultSize > 0) {
919 resultMetadata.resize(result.fmqResultSize);
920 if (mResultMetadataQueue == nullptr) {
921 return; // logged in initialize()
922 }
923 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
924 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
925 __FUNCTION__, result.frameNumber, result.fmqResultSize);
926 return;
927 }
928 } else {
929 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
930 result.result.size());
931 }
932
933 if (resultMetadata.size() != 0) {
934 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
935 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800936 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
937 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
938 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800939 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800940 }
941 } else {
942 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800943 }
944
945 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
946 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
947 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
948 auto& bDst = outputBuffers[i];
949 const StreamBuffer &bSrc = result.outputBuffers[i];
950
951 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100952 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800953 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
954 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800955 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800956 }
957 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
958
959 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800960 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800961 if (res != OK) {
962 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
963 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800964 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800965 }
966 bDst.buffer = buffer;
967 bDst.status = mapHidlBufferStatus(bSrc.status);
968 bDst.acquire_fence = -1;
969 if (bSrc.releaseFence == nullptr) {
970 bDst.release_fence = -1;
971 } else if (bSrc.releaseFence->numFds == 1) {
972 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
973 } else {
974 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
975 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800976 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800977 }
978 }
979 r.num_output_buffers = outputBuffers.size();
980 r.output_buffers = outputBuffers.data();
981
982 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800983 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800984 r.input_buffer = nullptr;
985 } else {
986 if (mInputStream->getId() != result.inputBuffer.streamId) {
987 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
988 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800989 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 }
991 inputBuffer.stream = mInputStream->asHalStream();
992 buffer_handle_t *buffer;
993 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
994 &buffer);
995 if (res != OK) {
996 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
997 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800998 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800999 }
1000 inputBuffer.buffer = buffer;
1001 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1002 inputBuffer.acquire_fence = -1;
1003 if (result.inputBuffer.releaseFence == nullptr) {
1004 inputBuffer.release_fence = -1;
1005 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1006 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1007 } else {
1008 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1009 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001010 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001011 }
1012 r.input_buffer = &inputBuffer;
1013 }
1014
1015 r.partial_result = result.partialResult;
1016
1017 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001018}
1019
1020hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001021 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001022 // Ideally we should grab mLock, but that can lead to deadlock, and
1023 // it's not super important to get up to date value of mStatus for this
1024 // warning print, hence skipping the lock here
1025 if (mStatus == STATUS_ERROR) {
1026 // Per API contract, HAL should act as closed after device error
1027 // But mStatus can be set to error by framework as well, so just log
1028 // a warning here.
1029 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001030 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001031
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001032 for (const auto& msg : msgs) {
1033 notify(msg);
1034 }
1035 return hardware::Void();
1036}
1037
1038void Camera3Device::notify(
1039 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1040
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001041 camera3_notify_msg m;
1042 switch (msg.type) {
1043 case MsgType::ERROR:
1044 m.type = CAMERA3_MSG_ERROR;
1045 m.message.error.frame_number = msg.msg.error.frameNumber;
1046 if (msg.msg.error.errorStreamId >= 0) {
1047 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001048 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001049 ALOGE("%s: Frame %d: Invalid error stream id %d",
1050 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001051 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001052 }
1053 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1054 } else {
1055 m.message.error.error_stream = nullptr;
1056 }
1057 switch (msg.msg.error.errorCode) {
1058 case ErrorCode::ERROR_DEVICE:
1059 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1060 break;
1061 case ErrorCode::ERROR_REQUEST:
1062 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1063 break;
1064 case ErrorCode::ERROR_RESULT:
1065 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1066 break;
1067 case ErrorCode::ERROR_BUFFER:
1068 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1069 break;
1070 }
1071 break;
1072 case MsgType::SHUTTER:
1073 m.type = CAMERA3_MSG_SHUTTER;
1074 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1075 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1076 break;
1077 }
1078 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001079}
1080
Emilian Peevaebbe412018-01-15 13:53:24 +00001081status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001082 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001083 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001084 ATRACE_CALL();
1085
Emilian Peevaebbe412018-01-15 13:53:24 +00001086 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001087}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001088
Jianing Weicb0652e2014-03-12 18:29:36 -07001089status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1090 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001091 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001092
Emilian Peevaebbe412018-01-15 13:53:24 +00001093 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001094 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001095 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001096
Emilian Peevaebbe412018-01-15 13:53:24 +00001097 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001098 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001099}
1100
Emilian Peevaebbe412018-01-15 13:53:24 +00001101status_t Camera3Device::setStreamingRequestList(
1102 const List<const PhysicalCameraSettingsList> &requestsList,
1103 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001104 ATRACE_CALL();
1105
Emilian Peevaebbe412018-01-15 13:53:24 +00001106 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001107}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001108
1109sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001110 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001111 status_t res;
1112
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001113 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001114 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1115 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001116 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1117 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001118 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001119 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001120 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001122 } else if (mStatus == STATUS_UNCONFIGURED) {
1123 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001124 CLOGE("No streams configured");
1125 return NULL;
1126 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001127 }
1128
Shuzhen Wang0129d522016-10-30 22:43:41 -07001129 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001130 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001131}
1132
Jianing Weicb0652e2014-03-12 18:29:36 -07001133status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001134 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001136 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001137
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001138 switch (mStatus) {
1139 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001140 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001141 return INVALID_OPERATION;
1142 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001143 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001144 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001145 case STATUS_UNCONFIGURED:
1146 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001147 case STATUS_ACTIVE:
1148 // OK
1149 break;
1150 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001151 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 return INVALID_OPERATION;
1153 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001154 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001155
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001156 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001157}
1158
1159status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1160 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001161 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001162
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001163 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001164}
1165
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001166status_t Camera3Device::createInputStream(
1167 uint32_t width, uint32_t height, int format, int *id) {
1168 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001169 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001170 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001171 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001172 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1173 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001174
1175 status_t res;
1176 bool wasActive = false;
1177
1178 switch (mStatus) {
1179 case STATUS_ERROR:
1180 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1181 return INVALID_OPERATION;
1182 case STATUS_UNINITIALIZED:
1183 ALOGE("%s: Device not initialized", __FUNCTION__);
1184 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 case STATUS_UNCONFIGURED:
1186 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001187 // OK
1188 break;
1189 case STATUS_ACTIVE:
1190 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001191 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001192 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001193 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001194 return res;
1195 }
1196 wasActive = true;
1197 break;
1198 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001200 return INVALID_OPERATION;
1201 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001203
1204 if (mInputStream != 0) {
1205 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1206 return INVALID_OPERATION;
1207 }
1208
1209 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1210 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001212
1213 mInputStream = newStream;
1214
1215 *id = mNextStreamId++;
1216
1217 // Continue captures if active at start
1218 if (wasActive) {
1219 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001220 // Reuse current operating mode and session parameters for new stream config
1221 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001222 if (res != OK) {
1223 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1224 __FUNCTION__, mNextStreamId, strerror(-res), res);
1225 return res;
1226 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001228 }
1229
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001230 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001231 return OK;
1232}
1233
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001234status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001235 uint32_t width, uint32_t height, int format,
1236 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001237 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001238 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001239 ATRACE_CALL();
1240
1241 if (consumer == nullptr) {
1242 ALOGE("%s: consumer must not be null", __FUNCTION__);
1243 return BAD_VALUE;
1244 }
1245
1246 std::vector<sp<Surface>> consumers;
1247 consumers.push_back(consumer);
1248
1249 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001250 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1251 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001252}
1253
1254status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1255 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1256 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001257 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001258 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001262 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001264 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001265 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1266 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1267 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 status_t res;
1270 bool wasActive = false;
1271
1272 switch (mStatus) {
1273 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001274 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return INVALID_OPERATION;
1276 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001277 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 case STATUS_UNCONFIGURED:
1280 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 // OK
1282 break;
1283 case STATUS_ACTIVE:
1284 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001285 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 return res;
1289 }
1290 wasActive = true;
1291 break;
1292 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001293 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 return INVALID_OPERATION;
1295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001296 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297
1298 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001299
Shuzhen Wang0129d522016-10-30 22:43:41 -07001300 if (consumers.size() == 0 && !hasDeferredConsumer) {
1301 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1302 return BAD_VALUE;
1303 }
Zhijun He5d677d12016-05-29 16:52:39 -07001304
Shuzhen Wang0129d522016-10-30 22:43:41 -07001305 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001306 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1307 return BAD_VALUE;
1308 }
1309
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001311 ssize_t blobBufferSize;
1312 if (dataSpace != HAL_DATASPACE_DEPTH) {
1313 blobBufferSize = getJpegBufferSize(width, height);
1314 if (blobBufferSize <= 0) {
1315 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1316 return BAD_VALUE;
1317 }
1318 } else {
1319 blobBufferSize = getPointCloudBufferSize();
1320 if (blobBufferSize <= 0) {
1321 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1322 return BAD_VALUE;
1323 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001324 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001326 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001327 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001328 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1329 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1330 if (rawOpaqueBufferSize <= 0) {
1331 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1332 return BAD_VALUE;
1333 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001334 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001335 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001336 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001337 } else if (isShared) {
1338 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1339 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001340 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001342 newStream = new Camera3OutputStream(mNextStreamId,
1343 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001344 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001346 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001347 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001348 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001349 }
Emilian Peev40ead602017-09-26 15:46:36 +01001350
1351 size_t consumerCount = consumers.size();
1352 for (size_t i = 0; i < consumerCount; i++) {
1353 int id = newStream->getSurfaceId(consumers[i]);
1354 if (id < 0) {
1355 SET_ERR_L("Invalid surface id");
1356 return BAD_VALUE;
1357 }
1358 if (surfaceIds != nullptr) {
1359 surfaceIds->push_back(id);
1360 }
1361 }
1362
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001363 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364
Emilian Peev08dd2452017-04-06 16:55:14 +01001365 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001366
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 res = mOutputStreams.add(mNextStreamId, newStream);
1368 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001369 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return res;
1371 }
1372
1373 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001374 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375
1376 // Continue captures if active at start
1377 if (wasActive) {
1378 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001379 // Reuse current operating mode and session parameters for new stream config
1380 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001382 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1383 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 return res;
1385 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001390}
1391
Emilian Peev710c1422017-08-30 11:19:38 +01001392status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001393 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001394 if (nullptr == streamInfo) {
1395 return BAD_VALUE;
1396 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001397 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001399
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 switch (mStatus) {
1401 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001402 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 return INVALID_OPERATION;
1404 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001405 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001407 case STATUS_UNCONFIGURED:
1408 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001409 case STATUS_ACTIVE:
1410 // OK
1411 break;
1412 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001413 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 return INVALID_OPERATION;
1415 }
1416
1417 ssize_t idx = mOutputStreams.indexOfKey(id);
1418 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001419 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 return idx;
1421 }
1422
Emilian Peev710c1422017-08-30 11:19:38 +01001423 streamInfo->width = mOutputStreams[idx]->getWidth();
1424 streamInfo->height = mOutputStreams[idx]->getHeight();
1425 streamInfo->format = mOutputStreams[idx]->getFormat();
1426 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1427 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1428 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001429 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1430 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001432}
1433
1434status_t Camera3Device::setStreamTransform(int id,
1435 int transform) {
1436 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001437 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001439
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440 switch (mStatus) {
1441 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001442 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 return INVALID_OPERATION;
1444 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 case STATUS_UNCONFIGURED:
1448 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 case STATUS_ACTIVE:
1450 // OK
1451 break;
1452 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001453 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 return INVALID_OPERATION;
1455 }
1456
1457 ssize_t idx = mOutputStreams.indexOfKey(id);
1458 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 CLOGE("Stream %d does not exist",
1460 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 return BAD_VALUE;
1462 }
1463
1464 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001465}
1466
1467status_t Camera3Device::deleteStream(int id) {
1468 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 Mutex::Autolock l(mLock);
1471 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001472
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001474
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 // CameraDevice semantics require device to already be idle before
1476 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001477 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001478 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001479 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 }
1481
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001482 if (mStatus == STATUS_ERROR) {
1483 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1484 __FUNCTION__, mId.string());
1485 return -EBUSY;
1486 }
1487
Igor Murashkin2fba5842013-04-22 14:03:54 -07001488 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001489 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 if (mInputStream != NULL && id == mInputStream->getId()) {
1491 deletedStream = mInputStream;
1492 mInputStream.clear();
1493 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001494 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 return BAD_VALUE;
1497 }
Zhijun He5f446352014-01-22 09:49:33 -08001498 }
1499
1500 // Delete output stream or the output part of a bi-directional stream.
1501 if (outputStreamIdx != NAME_NOT_FOUND) {
1502 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 mOutputStreams.removeItem(id);
1504 }
1505
1506 // Free up the stream endpoint so that it can be used by some other stream
1507 res = deletedStream->disconnect();
1508 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 // fall through since we want to still list the stream as deleted.
1511 }
1512 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001513 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514
1515 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516}
1517
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001518status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001519 ATRACE_CALL();
1520 ALOGV("%s: E", __FUNCTION__);
1521
1522 Mutex::Autolock il(mInterfaceLock);
1523 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001524
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001525 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1526}
1527
1528status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1529 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001530 //Filter out any incoming session parameters
1531 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001532 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1533 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001534 CameraMetadata filteredParams(availableSessionKeys.count);
1535 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1536 filteredParams.getAndLock());
1537 set_camera_metadata_vendor_id(meta, mVendorTagId);
1538 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001539 if (availableSessionKeys.count > 0) {
1540 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1541 camera_metadata_ro_entry entry = params.find(
1542 availableSessionKeys.data.i32[i]);
1543 if (entry.count > 0) {
1544 filteredParams.update(entry);
1545 }
1546 }
1547 }
1548
1549 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001550}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001551
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001552status_t Camera3Device::getInputBufferProducer(
1553 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001554 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001555 Mutex::Autolock il(mInterfaceLock);
1556 Mutex::Autolock l(mLock);
1557
1558 if (producer == NULL) {
1559 return BAD_VALUE;
1560 } else if (mInputStream == NULL) {
1561 return INVALID_OPERATION;
1562 }
1563
1564 return mInputStream->getInputBufferProducer(producer);
1565}
1566
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001567status_t Camera3Device::createDefaultRequest(int templateId,
1568 CameraMetadata *request) {
1569 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001570 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001571
1572 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1573 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1574 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1575 return BAD_VALUE;
1576 }
1577
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001580 {
1581 Mutex::Autolock l(mLock);
1582 switch (mStatus) {
1583 case STATUS_ERROR:
1584 CLOGE("Device has encountered a serious error");
1585 return INVALID_OPERATION;
1586 case STATUS_UNINITIALIZED:
1587 CLOGE("Device is not initialized!");
1588 return INVALID_OPERATION;
1589 case STATUS_UNCONFIGURED:
1590 case STATUS_CONFIGURED:
1591 case STATUS_ACTIVE:
1592 // OK
1593 break;
1594 default:
1595 SET_ERR_L("Unexpected status: %d", mStatus);
1596 return INVALID_OPERATION;
1597 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001598
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001599 if (!mRequestTemplateCache[templateId].isEmpty()) {
1600 *request = mRequestTemplateCache[templateId];
1601 return OK;
1602 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001603 }
1604
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001605 camera_metadata_t *rawRequest;
1606 status_t res = mInterface->constructDefaultRequestSettings(
1607 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001608
1609 {
1610 Mutex::Autolock l(mLock);
1611 if (res == BAD_VALUE) {
1612 ALOGI("%s: template %d is not supported on this camera device",
1613 __FUNCTION__, templateId);
1614 return res;
1615 } else if (res != OK) {
1616 CLOGE("Unable to construct request template %d: %s (%d)",
1617 templateId, strerror(-res), res);
1618 return res;
1619 }
1620
1621 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1622 mRequestTemplateCache[templateId].acquire(rawRequest);
1623
1624 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001625 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626 return OK;
1627}
1628
1629status_t Camera3Device::waitUntilDrained() {
1630 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001632 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001634
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001635 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001636}
1637
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001638status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 switch (mStatus) {
1640 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001642 ALOGV("%s: Already idle", __FUNCTION__);
1643 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 case STATUS_CONFIGURED:
1645 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 case STATUS_ERROR:
1647 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001648 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 break;
1650 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001651 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001652 return INVALID_OPERATION;
1653 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001654 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1655 maxExpectedDuration);
1656 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001657 if (res != OK) {
1658 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1659 res);
1660 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 return res;
1662}
1663
Ruben Brunk183f0562015-08-12 12:55:02 -07001664
1665void Camera3Device::internalUpdateStatusLocked(Status status) {
1666 mStatus = status;
1667 mRecentStatusUpdates.add(mStatus);
1668 mStatusChanged.broadcast();
1669}
1670
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001671// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001672status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 mRequestThread->setPaused(true);
1674 mPauseStateNotify = true;
1675
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001676 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1677 maxExpectedDuration);
1678 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679 if (res != OK) {
1680 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001681 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001682 }
1683
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 return res;
1685}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001686
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001687// Resume after internalPauseAndWaitLocked
1688status_t Camera3Device::internalResumeLocked() {
1689 status_t res;
1690
1691 mRequestThread->setPaused(false);
1692
1693 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1694 if (res != OK) {
1695 SET_ERR_L("Can't transition to active in %f seconds!",
1696 kActiveTimeout/1e9);
1697 }
1698 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001699 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700}
1701
Ruben Brunk183f0562015-08-12 12:55:02 -07001702status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001703 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001704
1705 size_t startIndex = 0;
1706 if (mStatusWaiters == 0) {
1707 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1708 // this status list
1709 mRecentStatusUpdates.clear();
1710 } else {
1711 // If other threads are waiting on updates to this status list, set the position of the
1712 // first element that this list will check rather than clearing the list.
1713 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001714 }
1715
Ruben Brunk183f0562015-08-12 12:55:02 -07001716 mStatusWaiters++;
1717
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001718 bool stateSeen = false;
1719 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001720 if (active == (mStatus == STATUS_ACTIVE)) {
1721 // Desired state is current
1722 break;
1723 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001724
1725 res = mStatusChanged.waitRelative(mLock, timeout);
1726 if (res != OK) break;
1727
Ruben Brunk183f0562015-08-12 12:55:02 -07001728 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1729 // transitions.
1730 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1731 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1732 __FUNCTION__);
1733
1734 // Encountered desired state since we began waiting
1735 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001736 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1737 stateSeen = true;
1738 break;
1739 }
1740 }
1741 } while (!stateSeen);
1742
Ruben Brunk183f0562015-08-12 12:55:02 -07001743 mStatusWaiters--;
1744
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001745 return res;
1746}
1747
1748
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001749status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001751 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001753 if (listener != NULL && mListener != NULL) {
1754 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1755 }
1756 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001757 mRequestThread->setNotificationListener(listener);
1758 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001759
1760 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761}
1762
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001763bool Camera3Device::willNotify3A() {
1764 return false;
1765}
1766
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001768 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001769 status_t res;
1770 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001771
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001772 while (mResultQueue.empty()) {
1773 res = mResultSignal.waitRelative(mOutputLock, timeout);
1774 if (res == TIMED_OUT) {
1775 return res;
1776 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001777 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1778 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001779 return res;
1780 }
1781 }
1782 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783}
1784
Jianing Weicb0652e2014-03-12 18:29:36 -07001785status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001786 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001787 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001788
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001789 if (mResultQueue.empty()) {
1790 return NOT_ENOUGH_DATA;
1791 }
1792
Jianing Weicb0652e2014-03-12 18:29:36 -07001793 if (frame == NULL) {
1794 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1795 return BAD_VALUE;
1796 }
1797
1798 CaptureResult &result = *(mResultQueue.begin());
1799 frame->mResultExtras = result.mResultExtras;
1800 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001801 mResultQueue.erase(mResultQueue.begin());
1802
1803 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001804}
1805
1806status_t Camera3Device::triggerAutofocus(uint32_t id) {
1807 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001810 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1811 // Mix-in this trigger into the next request and only the next request.
1812 RequestTrigger trigger[] = {
1813 {
1814 ANDROID_CONTROL_AF_TRIGGER,
1815 ANDROID_CONTROL_AF_TRIGGER_START
1816 },
1817 {
1818 ANDROID_CONTROL_AF_TRIGGER_ID,
1819 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001820 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001821 };
1822
1823 return mRequestThread->queueTrigger(trigger,
1824 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825}
1826
1827status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1828 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001830
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001831 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1832 // Mix-in this trigger into the next request and only the next request.
1833 RequestTrigger trigger[] = {
1834 {
1835 ANDROID_CONTROL_AF_TRIGGER,
1836 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1837 },
1838 {
1839 ANDROID_CONTROL_AF_TRIGGER_ID,
1840 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001841 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001842 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001843
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001844 return mRequestThread->queueTrigger(trigger,
1845 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846}
1847
1848status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1849 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001851
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001852 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1853 // Mix-in this trigger into the next request and only the next request.
1854 RequestTrigger trigger[] = {
1855 {
1856 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1857 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1858 },
1859 {
1860 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1861 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001862 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001863 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001864
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001865 return mRequestThread->queueTrigger(trigger,
1866 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867}
1868
Jianing Weicb0652e2014-03-12 18:29:36 -07001869status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001870 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001871 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001873
Zhijun He7ef20392014-04-21 16:04:17 -07001874 {
1875 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001876 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001877 }
1878
Emilian Peev08dd2452017-04-06 16:55:14 +01001879 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001880}
1881
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001882status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001883 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1884}
1885
1886status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001887 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001888 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001889 Mutex::Autolock il(mInterfaceLock);
1890 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001891
1892 sp<Camera3StreamInterface> stream;
1893 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1894 if (outputStreamIdx == NAME_NOT_FOUND) {
1895 CLOGE("Stream %d does not exist", streamId);
1896 return BAD_VALUE;
1897 }
1898
1899 stream = mOutputStreams.editValueAt(outputStreamIdx);
1900
1901 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001902 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001903 return BAD_VALUE;
1904 }
1905
1906 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001907 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001908 return BAD_VALUE;
1909 }
1910
Ruben Brunkc78ac262015-08-13 17:58:46 -07001911 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001912}
1913
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001914status_t Camera3Device::tearDown(int streamId) {
1915 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001916 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001917 Mutex::Autolock il(mInterfaceLock);
1918 Mutex::Autolock l(mLock);
1919
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001920 sp<Camera3StreamInterface> stream;
1921 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1922 if (outputStreamIdx == NAME_NOT_FOUND) {
1923 CLOGE("Stream %d does not exist", streamId);
1924 return BAD_VALUE;
1925 }
1926
1927 stream = mOutputStreams.editValueAt(outputStreamIdx);
1928
1929 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1930 CLOGE("Stream %d is a target of a in-progress request", streamId);
1931 return BAD_VALUE;
1932 }
1933
1934 return stream->tearDown();
1935}
1936
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001937status_t Camera3Device::addBufferListenerForStream(int streamId,
1938 wp<Camera3StreamBufferListener> listener) {
1939 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001940 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001941 Mutex::Autolock il(mInterfaceLock);
1942 Mutex::Autolock l(mLock);
1943
1944 sp<Camera3StreamInterface> stream;
1945 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1946 if (outputStreamIdx == NAME_NOT_FOUND) {
1947 CLOGE("Stream %d does not exist", streamId);
1948 return BAD_VALUE;
1949 }
1950
1951 stream = mOutputStreams.editValueAt(outputStreamIdx);
1952 stream->addBufferListener(listener);
1953
1954 return OK;
1955}
1956
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001957/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001958 * Methods called by subclasses
1959 */
1960
1961void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001962 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001963 {
1964 // Need mLock to safely update state and synchronize to current
1965 // state of methods in flight.
1966 Mutex::Autolock l(mLock);
1967 // We can get various system-idle notices from the status tracker
1968 // while starting up. Only care about them if we've actually sent
1969 // in some requests recently.
1970 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1971 return;
1972 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001973 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001974 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001975 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001976
1977 // Skip notifying listener if we're doing some user-transparent
1978 // state changes
1979 if (mPauseStateNotify) return;
1980 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001981
1982 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001983 {
1984 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001985 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001986 }
1987 if (idle && listener != NULL) {
1988 listener->notifyIdle();
1989 }
1990}
1991
Shuzhen Wang758c2152017-01-10 18:26:18 -08001992status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001993 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001994 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001995 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1996 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001997
1998 if (surfaceIds == nullptr) {
1999 return BAD_VALUE;
2000 }
2001
Zhijun He5d677d12016-05-29 16:52:39 -07002002 Mutex::Autolock il(mInterfaceLock);
2003 Mutex::Autolock l(mLock);
2004
Shuzhen Wang758c2152017-01-10 18:26:18 -08002005 if (consumers.size() == 0) {
2006 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002007 return BAD_VALUE;
2008 }
2009
2010 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2011 if (idx == NAME_NOT_FOUND) {
2012 CLOGE("Stream %d is unknown", streamId);
2013 return idx;
2014 }
2015 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002016 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002017 if (res != OK) {
2018 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2019 return res;
2020 }
2021
Emilian Peev40ead602017-09-26 15:46:36 +01002022 for (auto &consumer : consumers) {
2023 int id = stream->getSurfaceId(consumer);
2024 if (id < 0) {
2025 CLOGE("Invalid surface id!");
2026 return BAD_VALUE;
2027 }
2028 surfaceIds->push_back(id);
2029 }
2030
Shuzhen Wang0129d522016-10-30 22:43:41 -07002031 if (stream->isConsumerConfigurationDeferred()) {
2032 if (!stream->isConfiguring()) {
2033 CLOGE("Stream %d was already fully configured.", streamId);
2034 return INVALID_OPERATION;
2035 }
Zhijun He5d677d12016-05-29 16:52:39 -07002036
Shuzhen Wang0129d522016-10-30 22:43:41 -07002037 res = stream->finishConfiguration();
2038 if (res != OK) {
2039 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2040 stream->getId(), strerror(-res), res);
2041 return res;
2042 }
Zhijun He5d677d12016-05-29 16:52:39 -07002043 }
2044
2045 return OK;
2046}
2047
Emilian Peev40ead602017-09-26 15:46:36 +01002048status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2049 const std::vector<OutputStreamInfo> &outputInfo,
2050 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2051 Mutex::Autolock il(mInterfaceLock);
2052 Mutex::Autolock l(mLock);
2053
2054 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2055 if (idx == NAME_NOT_FOUND) {
2056 CLOGE("Stream %d is unknown", streamId);
2057 return idx;
2058 }
2059
2060 for (const auto &it : removedSurfaceIds) {
2061 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2062 CLOGE("Shared surface still part of a pending request!");
2063 return -EBUSY;
2064 }
2065 }
2066
2067 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2068 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2069 if (res != OK) {
2070 CLOGE("Stream %d failed to update stream (error %d %s) ",
2071 streamId, res, strerror(-res));
2072 if (res == UNKNOWN_ERROR) {
2073 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2074 __FUNCTION__);
2075 }
2076 return res;
2077 }
2078
2079 return res;
2080}
2081
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002082status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2083 Mutex::Autolock il(mInterfaceLock);
2084 Mutex::Autolock l(mLock);
2085
2086 int idx = mOutputStreams.indexOfKey(streamId);
2087 if (idx == NAME_NOT_FOUND) {
2088 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2089 return BAD_VALUE;
2090 }
2091
2092 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2093 return stream->dropBuffers(dropping);
2094}
2095
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002096/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097 * Camera3Device private methods
2098 */
2099
2100sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002101 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 ATRACE_CALL();
2103 status_t res;
2104
2105 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002106 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107
2108 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002109 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110 if (inputStreams.count > 0) {
2111 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002112 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002113 CLOGE("Request references unknown input stream %d",
2114 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 return NULL;
2116 }
2117 // Lazy completion of stream configuration (allocation/registration)
2118 // on first use
2119 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002120 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002121 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002122 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002124 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 return NULL;
2126 }
2127 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002128 // Check if stream is being prepared
2129 if (mInputStream->isPreparing()) {
2130 CLOGE("Request references an input stream that's being prepared!");
2131 return NULL;
2132 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133
2134 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002135 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 }
2137
2138 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002139 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002140 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002141 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 return NULL;
2143 }
2144
2145 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002146 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002147 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002148 CLOGE("Request references unknown stream %d",
2149 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 return NULL;
2151 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002152 sp<Camera3OutputStreamInterface> stream =
2153 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002154
Zhijun He5d677d12016-05-29 16:52:39 -07002155 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002156 auto iter = surfaceMap.find(streams.data.i32[i]);
2157 if (iter != surfaceMap.end()) {
2158 const std::vector<size_t>& surfaces = iter->second;
2159 for (const auto& surface : surfaces) {
2160 if (stream->isConsumerConfigurationDeferred(surface)) {
2161 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2162 "due to deferred consumer", stream->getId(), surface);
2163 return NULL;
2164 }
2165 }
2166 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002167 }
2168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169 // Lazy completion of stream configuration (allocation/registration)
2170 // on first use
2171 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002172 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002173 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002174 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2175 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002176 return NULL;
2177 }
2178 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002179 // Check if stream is being prepared
2180 if (stream->isPreparing()) {
2181 CLOGE("Request references an output stream that's being prepared!");
2182 return NULL;
2183 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002184
2185 newRequest->mOutputStreams.push(stream);
2186 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002187 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002188 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002189
2190 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002191}
2192
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002193bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2194 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2195 Size size = mSupportedOpaqueInputSizes[i];
2196 if (size.width == width && size.height == height) {
2197 return true;
2198 }
2199 }
2200
2201 return false;
2202}
2203
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002204void Camera3Device::cancelStreamsConfigurationLocked() {
2205 int res = OK;
2206 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2207 res = mInputStream->cancelConfiguration();
2208 if (res != OK) {
2209 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2210 mInputStream->getId(), strerror(-res), res);
2211 }
2212 }
2213
2214 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2215 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2216 if (outputStream->isConfiguring()) {
2217 res = outputStream->cancelConfiguration();
2218 if (res != OK) {
2219 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2220 outputStream->getId(), strerror(-res), res);
2221 }
2222 }
2223 }
2224
2225 // Return state to that at start of call, so that future configures
2226 // properly clean things up
2227 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2228 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002229
2230 res = mPreparerThread->resume();
2231 if (res != OK) {
2232 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2233 }
2234}
2235
2236bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2237 ATRACE_CALL();
2238 bool ret = false;
2239
2240 Mutex::Autolock il(mInterfaceLock);
2241 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2242
2243 Mutex::Autolock l(mLock);
2244 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2245 if (rc == NO_ERROR) {
2246 mNeedConfig = true;
2247 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2248 if (rc == NO_ERROR) {
2249 ret = true;
2250 mPauseStateNotify = false;
2251 //Moving to active state while holding 'mLock' is important.
2252 //There could be pending calls to 'create-/deleteStream' which
2253 //will trigger another stream configuration while the already
2254 //present streams end up with outstanding buffers that will
2255 //not get drained.
2256 internalUpdateStatusLocked(STATUS_ACTIVE);
2257 } else {
2258 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2259 __FUNCTION__, rc);
2260 }
2261 } else {
2262 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2263 }
2264
2265 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002266}
2267
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002268status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002269 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270 ATRACE_CALL();
2271 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002272
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002273 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002274 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275 return INVALID_OPERATION;
2276 }
2277
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002278 if (operatingMode < 0) {
2279 CLOGE("Invalid operating mode: %d", operatingMode);
2280 return BAD_VALUE;
2281 }
2282
2283 bool isConstrainedHighSpeed =
2284 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2285 operatingMode;
2286
2287 if (mOperatingMode != operatingMode) {
2288 mNeedConfig = true;
2289 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2290 mOperatingMode = operatingMode;
2291 }
2292
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002293 if (!mNeedConfig) {
2294 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2295 return OK;
2296 }
2297
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002298 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2299 // adding a dummy stream instead.
2300 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2301 if (mOutputStreams.size() == 0) {
2302 addDummyStreamLocked();
2303 } else {
2304 tryRemoveDummyStreamLocked();
2305 }
2306
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002308 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002309
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002310 mPreparerThread->pause();
2311
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002313 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002314 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2315
2316 Vector<camera3_stream_t*> streams;
2317 streams.setCapacity(config.num_streams);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002318 std::vector<uint32_t> outBufSizes(mOutputStreams.size(), 0);
2319
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320
2321 if (mInputStream != NULL) {
2322 camera3_stream_t *inputStream;
2323 inputStream = mInputStream->startConfiguration();
2324 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002325 CLOGE("Can't start input stream configuration");
2326 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002327 return INVALID_OPERATION;
2328 }
2329 streams.add(inputStream);
2330 }
2331
2332 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002333
2334 // Don't configure bidi streams twice, nor add them twice to the list
2335 if (mOutputStreams[i].get() ==
2336 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2337
2338 config.num_streams--;
2339 continue;
2340 }
2341
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002342 camera3_stream_t *outputStream;
2343 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2344 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002345 CLOGE("Can't start output stream configuration");
2346 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002347 return INVALID_OPERATION;
2348 }
2349 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002350
2351 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2352 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2353 outBufSizes[i] = static_cast<uint32_t>(
2354 getJpegBufferSize(outputStream->width, outputStream->height));
2355 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356 }
2357
2358 config.streams = streams.editArray();
2359
2360 // Do the HAL configuration; will potentially touch stream
2361 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002362
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002363 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002364 res = mInterface->configureStreams(sessionBuffer, &config, outBufSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002365 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002367 if (res == BAD_VALUE) {
2368 // HAL rejected this set of streams as unsupported, clean up config
2369 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002370 CLOGE("Set of requested inputs/outputs not supported by HAL");
2371 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002372 return BAD_VALUE;
2373 } else if (res != OK) {
2374 // Some other kind of error from configure_streams - this is not
2375 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002376 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2377 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 return res;
2379 }
2380
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002381 // Finish all stream configuration immediately.
2382 // TODO: Try to relax this later back to lazy completion, which should be
2383 // faster
2384
Igor Murashkin073f8572013-05-02 14:59:28 -07002385 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002386 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002387 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002388 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002389 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002390 cancelStreamsConfigurationLocked();
2391 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002392 }
2393 }
2394
2395 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002396 sp<Camera3OutputStreamInterface> outputStream =
2397 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002398 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002399 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002400 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002401 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002402 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002403 cancelStreamsConfigurationLocked();
2404 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002405 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002406 }
2407 }
2408
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409 // Request thread needs to know to avoid using repeat-last-settings protocol
2410 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002411 if (notifyRequestThread) {
2412 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2413 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414
Zhijun He90f7c372016-08-16 16:19:43 -07002415 char value[PROPERTY_VALUE_MAX];
2416 property_get("camera.fifo.disable", value, "0");
2417 int32_t disableFifo = atoi(value);
2418 if (disableFifo != 1) {
2419 // Boost priority of request thread to SCHED_FIFO.
2420 pid_t requestThreadTid = mRequestThread->getTid();
2421 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002422 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002423 if (res != OK) {
2424 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2425 strerror(-res), res);
2426 } else {
2427 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2428 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002429 }
2430
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002431 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002432 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2433 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2434 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2435 sessionParams.unlock(newSessionParams);
2436 mSessionParams.unlock(currentSessionParams);
2437 if (updateSessionParams) {
2438 mSessionParams = sessionParams;
2439 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002441 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002442
Ruben Brunk183f0562015-08-12 12:55:02 -07002443 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2444 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002445
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002446 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002447
Zhijun He0a210512014-07-24 13:45:15 -07002448 // tear down the deleted streams after configure streams.
2449 mDeletedStreams.clear();
2450
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002451 auto rc = mPreparerThread->resume();
2452 if (rc != OK) {
2453 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2454 return rc;
2455 }
2456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002458}
2459
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002460status_t Camera3Device::addDummyStreamLocked() {
2461 ATRACE_CALL();
2462 status_t res;
2463
2464 if (mDummyStreamId != NO_STREAM) {
2465 // Should never be adding a second dummy stream when one is already
2466 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002467 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2468 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002469 return INVALID_OPERATION;
2470 }
2471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002472 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002473
2474 sp<Camera3OutputStreamInterface> dummyStream =
2475 new Camera3DummyStream(mNextStreamId);
2476
2477 res = mOutputStreams.add(mNextStreamId, dummyStream);
2478 if (res < 0) {
2479 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2480 return res;
2481 }
2482
2483 mDummyStreamId = mNextStreamId;
2484 mNextStreamId++;
2485
2486 return OK;
2487}
2488
2489status_t Camera3Device::tryRemoveDummyStreamLocked() {
2490 ATRACE_CALL();
2491 status_t res;
2492
2493 if (mDummyStreamId == NO_STREAM) return OK;
2494 if (mOutputStreams.size() == 1) return OK;
2495
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002496 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002497
2498 // Ok, have a dummy stream and there's at least one other output stream,
2499 // so remove the dummy
2500
2501 sp<Camera3StreamInterface> deletedStream;
2502 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2503 if (outputStreamIdx == NAME_NOT_FOUND) {
2504 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2505 return INVALID_OPERATION;
2506 }
2507
2508 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2509 mOutputStreams.removeItemsAt(outputStreamIdx);
2510
2511 // Free up the stream endpoint so that it can be used by some other stream
2512 res = deletedStream->disconnect();
2513 if (res != OK) {
2514 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2515 // fall through since we want to still list the stream as deleted.
2516 }
2517 mDeletedStreams.add(deletedStream);
2518 mDummyStreamId = NO_STREAM;
2519
2520 return res;
2521}
2522
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002523void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002524 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002525 Mutex::Autolock l(mLock);
2526 va_list args;
2527 va_start(args, fmt);
2528
2529 setErrorStateLockedV(fmt, args);
2530
2531 va_end(args);
2532}
2533
2534void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002535 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002536 Mutex::Autolock l(mLock);
2537 setErrorStateLockedV(fmt, args);
2538}
2539
2540void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2541 va_list args;
2542 va_start(args, fmt);
2543
2544 setErrorStateLockedV(fmt, args);
2545
2546 va_end(args);
2547}
2548
2549void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002550 // Print out all error messages to log
2551 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002552 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002553
2554 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002555 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002556
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002557 mErrorCause = errorCause;
2558
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002559 if (mRequestThread != nullptr) {
2560 mRequestThread->setPaused(true);
2561 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002562 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002563
2564 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002565 sp<NotificationListener> listener = mListener.promote();
2566 if (listener != NULL) {
2567 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002568 CaptureResultExtras());
2569 }
2570
2571 // Save stack trace. View by dumping it later.
2572 CameraTraces::saveTrace();
2573 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002574}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002575
2576/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002577 * In-flight request management
2578 */
2579
Jianing Weicb0652e2014-03-12 18:29:36 -07002580status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002581 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002582 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002583 ATRACE_CALL();
2584 Mutex::Autolock l(mInFlightLock);
2585
2586 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002587 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002588 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002589 if (res < 0) return res;
2590
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002591 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002592 // hold mLock to prevent race with disconnect
2593 Mutex::Autolock l(mLock);
2594 if (mStatusTracker != nullptr) {
2595 mStatusTracker->markComponentActive(mInFlightStatusId);
2596 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002597 }
2598
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002599 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002600 return OK;
2601}
2602
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002603void Camera3Device::returnOutputBuffers(
2604 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2605 nsecs_t timestamp) {
2606 for (size_t i = 0; i < numBuffers; i++)
2607 {
2608 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2609 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2610 // Note: stream may be deallocated at this point, if this buffer was
2611 // the last reference to it.
2612 if (res != OK) {
2613 ALOGE("Can't return buffer to its stream: %s (%d)",
2614 strerror(-res), res);
2615 }
2616 }
2617}
2618
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002619void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002620 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002621 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002622 mInFlightMap.removeItemsAt(idx, 1);
2623
2624 // Indicate idle inFlightMap to the status tracker
2625 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002626 // hold mLock to prevent race with disconnect
2627 Mutex::Autolock l(mLock);
2628 if (mStatusTracker != nullptr) {
2629 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2630 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002631 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002632 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002633}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002634
2635void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2636
2637 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2638 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2639
2640 nsecs_t sensorTimestamp = request.sensorTimestamp;
2641 nsecs_t shutterTimestamp = request.shutterTimestamp;
2642
2643 // Check if it's okay to remove the request from InFlightMap:
2644 // In the case of a successful request:
2645 // all input and output buffers, all result metadata, shutter callback
2646 // arrived.
2647 // In the case of a unsuccessful request:
2648 // all input and output buffers arrived.
2649 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002650 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002651 (request.haveResultMetadata && shutterTimestamp != 0))) {
2652 ATRACE_ASYNC_END("frame capture", frameNumber);
2653
Shuzhen Wang403044a2017-02-26 23:29:04 -08002654 // Sanity check - if sensor timestamp matches shutter timestamp in the
2655 // case of request having callback.
2656 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002657 sensorTimestamp != shutterTimestamp) {
2658 SET_ERR("sensor timestamp (%" PRId64
2659 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2660 sensorTimestamp, frameNumber, shutterTimestamp);
2661 }
2662
2663 // for an unsuccessful request, it may have pending output buffers to
2664 // return.
2665 assert(request.requestStatus != OK ||
2666 request.pendingOutputBuffers.size() == 0);
2667 returnOutputBuffers(request.pendingOutputBuffers.array(),
2668 request.pendingOutputBuffers.size(), 0);
2669
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002670 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002671 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2672 }
2673
2674 // Sanity check - if we have too many in-flight frames, something has
2675 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002676 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002677 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002678 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2679 kInFlightWarnLimitHighSpeed) {
2680 CLOGE("In-flight list too large for high speed configuration: %zu",
2681 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002682 }
2683}
2684
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002685void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002686 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002687 { // First return buffers cached in mInFlightMap
2688 Mutex::Autolock l(mInFlightLock);
2689 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2690 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2691 returnOutputBuffers(request.pendingOutputBuffers.array(),
2692 request.pendingOutputBuffers.size(), 0);
2693 }
2694 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002695 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002696 }
2697
2698 // Then return all inflight buffers not returned by HAL
2699 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2700 mInterface->getInflightBufferKeys(&inflightKeys);
2701
2702 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2703 for (auto& pair : inflightKeys) {
2704 int32_t frameNumber = pair.first;
2705 int32_t streamId = pair.second;
2706 buffer_handle_t* buffer;
2707 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2708 if (res != OK) {
2709 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2710 __FUNCTION__, frameNumber, streamId);
2711 continue;
2712 }
2713
2714 camera3_stream_buffer_t streamBuffer;
2715 streamBuffer.buffer = buffer;
2716 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2717 streamBuffer.acquire_fence = -1;
2718 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002719
2720 // First check if the buffer belongs to deleted stream
2721 bool streamDeleted = false;
2722 for (auto& stream : mDeletedStreams) {
2723 if (streamId == stream->getId()) {
2724 streamDeleted = true;
2725 // Return buffer to deleted stream
2726 camera3_stream* halStream = stream->asHalStream();
2727 streamBuffer.stream = halStream;
2728 switch (halStream->stream_type) {
2729 case CAMERA3_STREAM_OUTPUT:
2730 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2731 if (res != OK) {
2732 ALOGE("%s: Can't return output buffer for frame %d to"
2733 " stream %d: %s (%d)", __FUNCTION__,
2734 frameNumber, streamId, strerror(-res), res);
2735 }
2736 break;
2737 case CAMERA3_STREAM_INPUT:
2738 res = stream->returnInputBuffer(streamBuffer);
2739 if (res != OK) {
2740 ALOGE("%s: Can't return input buffer for frame %d to"
2741 " stream %d: %s (%d)", __FUNCTION__,
2742 frameNumber, streamId, strerror(-res), res);
2743 }
2744 break;
2745 default: // Bi-direcitonal stream is deprecated
2746 ALOGE("%s: stream %d has unknown stream type %d",
2747 __FUNCTION__, streamId, halStream->stream_type);
2748 break;
2749 }
2750 break;
2751 }
2752 }
2753 if (streamDeleted) {
2754 continue;
2755 }
2756
2757 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002758 if (streamId == inputStreamId) {
2759 streamBuffer.stream = mInputStream->asHalStream();
2760 res = mInputStream->returnInputBuffer(streamBuffer);
2761 if (res != OK) {
2762 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002763 " stream %d: %s (%d)", __FUNCTION__,
2764 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002765 }
2766 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002767 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2768 if (idx == NAME_NOT_FOUND) {
2769 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2770 continue;
2771 }
2772 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002773 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2774 }
2775 }
2776}
2777
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002778void Camera3Device::insertResultLocked(CaptureResult *result,
2779 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002780 if (result == nullptr) return;
2781
Emilian Peev71c73a22017-03-21 16:35:51 +00002782 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2783 result->mMetadata.getAndLock());
2784 set_camera_metadata_vendor_id(meta, mVendorTagId);
2785 result->mMetadata.unlock(meta);
2786
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002787 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2788 (int32_t*)&frameNumber, 1) != OK) {
2789 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2790 return;
2791 }
2792
2793 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2794 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2795 return;
2796 }
2797
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002798 // Valid result, insert into queue
2799 List<CaptureResult>::iterator queuedResult =
2800 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2801 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2802 ", burstId = %" PRId32, __FUNCTION__,
2803 queuedResult->mResultExtras.requestId,
2804 queuedResult->mResultExtras.frameNumber,
2805 queuedResult->mResultExtras.burstId);
2806
2807 mResultSignal.signal();
2808}
2809
2810
2811void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002812 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002813 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002814 Mutex::Autolock l(mOutputLock);
2815
2816 CaptureResult captureResult;
2817 captureResult.mResultExtras = resultExtras;
2818 captureResult.mMetadata = partialResult;
2819
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002820 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002821}
2822
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002823
2824void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2825 CaptureResultExtras &resultExtras,
2826 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002827 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002828 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002829 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002830 if (pendingMetadata.isEmpty())
2831 return;
2832
2833 Mutex::Autolock l(mOutputLock);
2834
2835 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002836 if (reprocess) {
2837 if (frameNumber < mNextReprocessResultFrameNumber) {
2838 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002839 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002840 frameNumber, mNextReprocessResultFrameNumber);
2841 return;
2842 }
2843 mNextReprocessResultFrameNumber = frameNumber + 1;
2844 } else {
2845 if (frameNumber < mNextResultFrameNumber) {
2846 SET_ERR("Out-of-order capture result metadata submitted! "
2847 "(got frame number %d, expecting %d)",
2848 frameNumber, mNextResultFrameNumber);
2849 return;
2850 }
2851 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002852 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002853
2854 CaptureResult captureResult;
2855 captureResult.mResultExtras = resultExtras;
2856 captureResult.mMetadata = pendingMetadata;
2857
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002858 // Append any previous partials to form a complete result
2859 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2860 captureResult.mMetadata.append(collectedPartialResult);
2861 }
2862
2863 captureResult.mMetadata.sort();
2864
2865 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002866 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2867 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002868 SET_ERR("No timestamp provided by HAL for frame %d!",
2869 frameNumber);
2870 return;
2871 }
2872
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002873 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2874 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2875
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002876 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002877}
2878
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002879/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880 * Camera HAL device callback methods
2881 */
2882
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002883void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002884 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002885
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002886 status_t res;
2887
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002888 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002889 if (result->result == NULL && result->num_output_buffers == 0 &&
2890 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002891 SET_ERR("No result data provided by HAL for frame %d",
2892 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002893 return;
2894 }
Zhijun He204e3292014-07-14 17:09:23 -07002895
Zhijun He204e3292014-07-14 17:09:23 -07002896 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002897 result->result != NULL &&
2898 result->partial_result != 1) {
2899 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2900 " if partial result is not supported",
2901 frameNumber, result->partial_result);
2902 return;
2903 }
2904
2905 bool isPartialResult = false;
2906 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002907 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002908 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002909
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002910 // Get shutter timestamp and resultExtras from list of in-flight requests,
2911 // where it was added by the shutter notification for this frame. If the
2912 // shutter timestamp isn't received yet, append the output buffers to the
2913 // in-flight request and they will be returned when the shutter timestamp
2914 // arrives. Update the in-flight status and remove the in-flight entry if
2915 // all result data and shutter timestamp have been received.
2916 nsecs_t shutterTimestamp = 0;
2917
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002918 {
2919 Mutex::Autolock l(mInFlightLock);
2920 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2921 if (idx == NAME_NOT_FOUND) {
2922 SET_ERR("Unknown frame number for capture result: %d",
2923 frameNumber);
2924 return;
2925 }
2926 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002927 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2928 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002929 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002930 __FUNCTION__, request.resultExtras.requestId,
2931 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002932 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002933 // Always update the partial count to the latest one if it's not 0
2934 // (buffers only). When framework aggregates adjacent partial results
2935 // into one, the latest partial count will be used.
2936 if (result->partial_result != 0)
2937 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002938
2939 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002940 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002941 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2942 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2943 " the range of [1, %d] when metadata is included in the result",
2944 frameNumber, result->partial_result, mNumPartialResults);
2945 return;
2946 }
2947 isPartialResult = (result->partial_result < mNumPartialResults);
2948 if (isPartialResult) {
2949 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002950 }
2951
Shuzhen Wang4a472662017-02-26 23:29:04 -08002952 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002953 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002954 sendPartialCaptureResult(result->result, request.resultExtras,
2955 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002956 }
2957 }
2958
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002959 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002960 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002961
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002962 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002963 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002964 if (request.haveResultMetadata) {
2965 SET_ERR("Called multiple times with metadata for frame %d",
2966 frameNumber);
2967 return;
2968 }
Zhijun He204e3292014-07-14 17:09:23 -07002969 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002970 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002971 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002972 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002973 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002974 request.haveResultMetadata = true;
2975 }
2976
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002977 uint32_t numBuffersReturned = result->num_output_buffers;
2978 if (result->input_buffer != NULL) {
2979 if (hasInputBufferInRequest) {
2980 numBuffersReturned += 1;
2981 } else {
2982 ALOGW("%s: Input buffer should be NULL if there is no input"
2983 " buffer sent in the request",
2984 __FUNCTION__);
2985 }
2986 }
2987 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002988 if (request.numBuffersLeft < 0) {
2989 SET_ERR("Too many buffers returned for frame %d",
2990 frameNumber);
2991 return;
2992 }
2993
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002994 camera_metadata_ro_entry_t entry;
2995 res = find_camera_metadata_ro_entry(result->result,
2996 ANDROID_SENSOR_TIMESTAMP, &entry);
2997 if (res == OK && entry.count == 1) {
2998 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002999 }
3000
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003001 // If shutter event isn't received yet, append the output buffers to
3002 // the in-flight request. Otherwise, return the output buffers to
3003 // streams.
3004 if (shutterTimestamp == 0) {
3005 request.pendingOutputBuffers.appendArray(result->output_buffers,
3006 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003007 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003008 returnOutputBuffers(result->output_buffers,
3009 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003010 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003011
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012 if (result->result != NULL && !isPartialResult) {
3013 if (shutterTimestamp == 0) {
3014 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003015 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003016 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003017 CameraMetadata metadata;
3018 metadata = result->result;
3019 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003020 collectedPartialResult, frameNumber,
3021 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003022 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003023 }
3024
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025 removeInFlightRequestIfReadyLocked(idx);
3026 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003027
Zhijun Hef0d962a2014-06-30 10:24:11 -07003028 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003029 if (hasInputBufferInRequest) {
3030 Camera3Stream *stream =
3031 Camera3Stream::cast(result->input_buffer->stream);
3032 res = stream->returnInputBuffer(*(result->input_buffer));
3033 // Note: stream may be deallocated at this point, if this buffer was the
3034 // last reference to it.
3035 if (res != OK) {
3036 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3037 " its stream:%s (%d)", __FUNCTION__,
3038 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003039 }
3040 } else {
3041 ALOGW("%s: Input buffer should be NULL if there is no input"
3042 " buffer sent in the request, skipping input buffer return.",
3043 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003044 }
3045 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003046}
3047
3048void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003049 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003050 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003051 {
3052 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003053 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003054 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003055
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003056 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003057 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003058 return;
3059 }
3060
3061 switch (msg->type) {
3062 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003063 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003064 break;
3065 }
3066 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003067 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003068 break;
3069 }
3070 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003071 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003072 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003073 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003074}
3075
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003076void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003077 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003078 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003079 // Map camera HAL error codes to ICameraDeviceCallback error codes
3080 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003081 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003082 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003084 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003085 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003086 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003088 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003089 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003090 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003091 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003092 };
3093
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003095 ((msg.error_code >= 0) &&
3096 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3097 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003098 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003099
3100 int streamId = 0;
3101 if (msg.error_stream != NULL) {
3102 Camera3Stream *stream =
3103 Camera3Stream::cast(msg.error_stream);
3104 streamId = stream->getId();
3105 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003106 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3107 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003108 streamId, msg.error_code);
3109
3110 CaptureResultExtras resultExtras;
3111 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003112 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003113 // SET_ERR calls notifyError
3114 SET_ERR("Camera HAL reported serious device error");
3115 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3117 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3118 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119 {
3120 Mutex::Autolock l(mInFlightLock);
3121 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3122 if (idx >= 0) {
3123 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3124 r.requestStatus = msg.error_code;
3125 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003126 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3127 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3128 errorCode) {
3129 r.skipResultMetadata = true;
3130 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003131 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3132 errorCode) {
3133 // In case of missing result check whether the buffers
3134 // returned. If they returned, then remove inflight
3135 // request.
3136 removeInFlightRequestIfReadyLocked(idx);
3137 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003138 } else {
3139 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140 ALOGE("Camera %s: %s: cannot find in-flight request on "
3141 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003142 resultExtras.frameNumber);
3143 }
3144 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003145 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003146 if (listener != NULL) {
3147 listener->notifyError(errorCode, resultExtras);
3148 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003149 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003150 }
3151 break;
3152 default:
3153 // SET_ERR calls notifyError
3154 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3155 break;
3156 }
3157}
3158
3159void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003160 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003161 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003162 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003163
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003164 // Set timestamp for the request in the in-flight tracking
3165 // and get the request ID to send upstream
3166 {
3167 Mutex::Autolock l(mInFlightLock);
3168 idx = mInFlightMap.indexOfKey(msg.frame_number);
3169 if (idx >= 0) {
3170 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003171
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003172 // Verify ordering of shutter notifications
3173 {
3174 Mutex::Autolock l(mOutputLock);
3175 // TODO: need to track errors for tighter bounds on expected frame number.
3176 if (r.hasInputBuffer) {
3177 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3178 SET_ERR("Shutter notification out-of-order. Expected "
3179 "notification for frame %d, got frame %d",
3180 mNextReprocessShutterFrameNumber, msg.frame_number);
3181 return;
3182 }
3183 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3184 } else {
3185 if (msg.frame_number < mNextShutterFrameNumber) {
3186 SET_ERR("Shutter notification out-of-order. Expected "
3187 "notification for frame %d, got frame %d",
3188 mNextShutterFrameNumber, msg.frame_number);
3189 return;
3190 }
3191 mNextShutterFrameNumber = msg.frame_number + 1;
3192 }
3193 }
3194
Shuzhen Wang4a472662017-02-26 23:29:04 -08003195 r.shutterTimestamp = msg.timestamp;
3196 if (r.hasCallback) {
3197 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003198 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003199 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003200 // Call listener, if any
3201 if (listener != NULL) {
3202 listener->notifyShutter(r.resultExtras, msg.timestamp);
3203 }
3204 // send pending result and buffers
3205 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3206 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003207 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003208 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003209 returnOutputBuffers(r.pendingOutputBuffers.array(),
3210 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3211 r.pendingOutputBuffers.clear();
3212
3213 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003214 }
3215 }
3216 if (idx < 0) {
3217 SET_ERR("Shutter notification for non-existent frame number %d",
3218 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003219 }
3220}
3221
3222
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003223CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003224 ALOGV("%s", __FUNCTION__);
3225
Igor Murashkin1e479c02013-09-06 16:55:14 -07003226 CameraMetadata retVal;
3227
3228 if (mRequestThread != NULL) {
3229 retVal = mRequestThread->getLatestRequest();
3230 }
3231
Igor Murashkin1e479c02013-09-06 16:55:14 -07003232 return retVal;
3233}
3234
Jianing Weicb0652e2014-03-12 18:29:36 -07003235
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003236void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3237 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3238 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3239}
3240
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003241/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003242 * HalInterface inner class methods
3243 */
3244
Yifan Hongf79b5542017-04-11 14:44:25 -07003245Camera3Device::HalInterface::HalInterface(
3246 sp<ICameraDeviceSession> &session,
3247 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003248 mHidlSession(session),
3249 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003250
Emilian Peev31abd0a2017-05-11 18:37:46 +01003251Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003252
3253Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003254 mHidlSession(other.mHidlSession),
3255 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003256
3257bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003258 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003259}
3260
3261void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003262 mHidlSession.clear();
3263}
3264
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003265bool Camera3Device::HalInterface::supportBatchRequest() {
3266 return mHidlSession != nullptr;
3267}
3268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003269status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3270 camera3_request_template_t templateId,
3271 /*out*/ camera_metadata_t **requestTemplate) {
3272 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3273 if (!valid()) return INVALID_OPERATION;
3274 status_t res = OK;
3275
Emilian Peev31abd0a2017-05-11 18:37:46 +01003276 common::V1_0::Status status;
3277 RequestTemplate id;
3278 switch (templateId) {
3279 case CAMERA3_TEMPLATE_PREVIEW:
3280 id = RequestTemplate::PREVIEW;
3281 break;
3282 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3283 id = RequestTemplate::STILL_CAPTURE;
3284 break;
3285 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3286 id = RequestTemplate::VIDEO_RECORD;
3287 break;
3288 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3289 id = RequestTemplate::VIDEO_SNAPSHOT;
3290 break;
3291 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3292 id = RequestTemplate::ZERO_SHUTTER_LAG;
3293 break;
3294 case CAMERA3_TEMPLATE_MANUAL:
3295 id = RequestTemplate::MANUAL;
3296 break;
3297 default:
3298 // Unknown template ID
3299 return BAD_VALUE;
3300 }
3301 auto err = mHidlSession->constructDefaultRequestSettings(id,
3302 [&status, &requestTemplate]
3303 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3304 status = s;
3305 if (status == common::V1_0::Status::OK) {
3306 const camera_metadata *r =
3307 reinterpret_cast<const camera_metadata_t*>(request.data());
3308 size_t expectedSize = request.size();
3309 int ret = validate_camera_metadata_structure(r, &expectedSize);
3310 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3311 *requestTemplate = clone_camera_metadata(r);
3312 if (*requestTemplate == nullptr) {
3313 ALOGE("%s: Unable to clone camera metadata received from HAL",
3314 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003315 status = common::V1_0::Status::INTERNAL_ERROR;
3316 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003317 } else {
3318 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3319 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003320 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003321 }
3322 });
3323 if (!err.isOk()) {
3324 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3325 res = DEAD_OBJECT;
3326 } else {
3327 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003328 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003329
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003330 return res;
3331}
3332
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003333status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08003334 camera3_stream_configuration *config, const std::vector<uint32_t>& outputBufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003335 ATRACE_NAME("CameraHal::configureStreams");
3336 if (!valid()) return INVALID_OPERATION;
3337 status_t res = OK;
3338
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 // Convert stream config to HIDL
3340 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003341 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3342 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3343 requestedConfiguration3_2.streams.resize(config->num_streams);
3344 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003345 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003346 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3347 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003348 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003349
Emilian Peev31abd0a2017-05-11 18:37:46 +01003350 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3351 cam3stream->setBufferFreedListener(this);
3352 int streamId = cam3stream->getId();
3353 StreamType streamType;
3354 switch (src->stream_type) {
3355 case CAMERA3_STREAM_OUTPUT:
3356 streamType = StreamType::OUTPUT;
3357 break;
3358 case CAMERA3_STREAM_INPUT:
3359 streamType = StreamType::INPUT;
3360 break;
3361 default:
3362 ALOGE("%s: Stream %d: Unsupported stream type %d",
3363 __FUNCTION__, streamId, config->streams[i]->stream_type);
3364 return BAD_VALUE;
3365 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003366 dst3_2.id = streamId;
3367 dst3_2.streamType = streamType;
3368 dst3_2.width = src->width;
3369 dst3_2.height = src->height;
3370 dst3_2.format = mapToPixelFormat(src->format);
3371 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3372 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3373 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3374 dst3_4.v3_2 = dst3_2;
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08003375 dst3_4.bufferSize = outputBufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003376 if (src->physical_camera_id != nullptr) {
3377 dst3_4.physicalCameraId = src->physical_camera_id;
3378 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003379
3380 activeStreams.insert(streamId);
3381 // Create Buffer ID map if necessary
3382 if (mBufferIdMaps.count(streamId) == 0) {
3383 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3384 }
3385 }
3386 // remove BufferIdMap for deleted streams
3387 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3388 int streamId = it->first;
3389 bool active = activeStreams.count(streamId) > 0;
3390 if (!active) {
3391 it = mBufferIdMaps.erase(it);
3392 } else {
3393 ++it;
3394 }
3395 }
3396
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003397 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003398 res = mapToStreamConfigurationMode(
3399 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003400 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003401 if (res != OK) {
3402 return res;
3403 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003404 requestedConfiguration3_2.operationMode = operationMode;
3405 requestedConfiguration3_4.operationMode = operationMode;
3406 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003407 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3408 get_camera_metadata_size(sessionParams));
3409
Emilian Peev31abd0a2017-05-11 18:37:46 +01003410 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003411 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003412 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003413
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003414 // See if we have v3.4 or v3.3 HAL
3415 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003416 sp<device::V3_3::ICameraDeviceSession> hidlSession_3_3;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003417 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3418 if (castResult_3_4.isOk()) {
3419 hidlSession_3_4 = castResult_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003420 } else {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003421 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3422 if (castResult_3_3.isOk()) {
3423 hidlSession_3_3 = castResult_3_3;
3424 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003425 }
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003426
3427 if (hidlSession_3_4 != nullptr) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003428 // We do; use v3.4 for the call, and construct a v3.4
3429 // HalStreamConfiguration
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003430 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003431 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
3432 auto err = hidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
3433 [&status, &finalConfiguration3_4]
3434 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3435 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003436 status = s;
3437 });
3438 if (!err.isOk()) {
3439 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3440 return DEAD_OBJECT;
3441 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003442 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3443 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3444 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3445 }
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003446 } else if (hidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003447 // We do; use v3.3 for the call
3448 ALOGV("%s: v3.3 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003449 auto err = hidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003451 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003452 finalConfiguration = halConfiguration;
3453 status = s;
3454 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003455 if (!err.isOk()) {
3456 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3457 return DEAD_OBJECT;
3458 }
3459 } else {
3460 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3461 ALOGV("%s: v3.2 device found", __FUNCTION__);
3462 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003463 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003464 [&status, &finalConfiguration_3_2]
3465 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3466 finalConfiguration_3_2 = halConfiguration;
3467 status = s;
3468 });
3469 if (!err.isOk()) {
3470 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3471 return DEAD_OBJECT;
3472 }
3473 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3474 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3475 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3476 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003477 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003478 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 }
3480
3481 if (status != common::V1_0::Status::OK ) {
3482 return CameraProviderManager::mapToStatusT(status);
3483 }
3484
3485 // And convert output stream configuration from HIDL
3486
3487 for (size_t i = 0; i < config->num_streams; i++) {
3488 camera3_stream_t *dst = config->streams[i];
3489 int streamId = Camera3Stream::cast(dst)->getId();
3490
3491 // Start scan at i, with the assumption that the stream order matches
3492 size_t realIdx = i;
3493 bool found = false;
3494 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003495 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 found = true;
3497 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003498 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3500 }
3501 if (!found) {
3502 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3503 __FUNCTION__, streamId);
3504 return INVALID_OPERATION;
3505 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003506 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003507
Emilian Peev710c1422017-08-30 11:19:38 +01003508 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3509 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003510 dstStream->setDataSpaceOverride(false);
3511 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3512 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3513
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3515 if (dst->format != overrideFormat) {
3516 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3517 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003518 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003519 if (dst->data_space != overrideDataSpace) {
3520 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3521 streamId, dst->format);
3522 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003524 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003525 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3526
Emilian Peev31abd0a2017-05-11 18:37:46 +01003527 // Override allowed with IMPLEMENTATION_DEFINED
3528 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003530 }
3531
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003533 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003534 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003535 __FUNCTION__, streamId);
3536 return INVALID_OPERATION;
3537 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003538 dstStream->setUsage(
3539 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 } else {
3541 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003542 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003543 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3544 __FUNCTION__, streamId);
3545 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003546 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003547 dstStream->setUsage(
3548 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003551 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003553 return res;
3554}
3555
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003556void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3557 /*out*/device::V3_2::CaptureRequest* captureRequest,
3558 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003559 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003560 if (captureRequest == nullptr || handlesCreated == nullptr) {
3561 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3562 __FUNCTION__, captureRequest, handlesCreated);
3563 return;
3564 }
3565
3566 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003567
3568 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003569
3570 {
3571 std::lock_guard<std::mutex> lock(mInflightLock);
3572 if (request->input_buffer != nullptr) {
3573 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3574 buffer_handle_t buf = *(request->input_buffer->buffer);
3575 auto pair = getBufferId(buf, streamId);
3576 bool isNewBuffer = pair.first;
3577 uint64_t bufferId = pair.second;
3578 captureRequest->inputBuffer.streamId = streamId;
3579 captureRequest->inputBuffer.bufferId = bufferId;
3580 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3581 captureRequest->inputBuffer.status = BufferStatus::OK;
3582 native_handle_t *acquireFence = nullptr;
3583 if (request->input_buffer->acquire_fence != -1) {
3584 acquireFence = native_handle_create(1,0);
3585 acquireFence->data[0] = request->input_buffer->acquire_fence;
3586 handlesCreated->push_back(acquireFence);
3587 }
3588 captureRequest->inputBuffer.acquireFence = acquireFence;
3589 captureRequest->inputBuffer.releaseFence = nullptr;
3590
3591 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3592 request->input_buffer->buffer,
3593 request->input_buffer->acquire_fence);
3594 } else {
3595 captureRequest->inputBuffer.streamId = -1;
3596 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3597 }
3598
3599 captureRequest->outputBuffers.resize(request->num_output_buffers);
3600 for (size_t i = 0; i < request->num_output_buffers; i++) {
3601 const camera3_stream_buffer_t *src = request->output_buffers + i;
3602 StreamBuffer &dst = captureRequest->outputBuffers[i];
3603 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3604 buffer_handle_t buf = *(src->buffer);
3605 auto pair = getBufferId(buf, streamId);
3606 bool isNewBuffer = pair.first;
3607 dst.streamId = streamId;
3608 dst.bufferId = pair.second;
3609 dst.buffer = isNewBuffer ? buf : nullptr;
3610 dst.status = BufferStatus::OK;
3611 native_handle_t *acquireFence = nullptr;
3612 if (src->acquire_fence != -1) {
3613 acquireFence = native_handle_create(1,0);
3614 acquireFence->data[0] = src->acquire_fence;
3615 handlesCreated->push_back(acquireFence);
3616 }
3617 dst.acquireFence = acquireFence;
3618 dst.releaseFence = nullptr;
3619
3620 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3621 src->buffer, src->acquire_fence);
3622 }
3623 }
3624}
3625
3626status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3627 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3628 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3629 if (!valid()) return INVALID_OPERATION;
3630
Emilian Peevaebbe412018-01-15 13:53:24 +00003631 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3632 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3633 if (castResult_3_4.isOk()) {
3634 hidlSession_3_4 = castResult_3_4;
3635 }
3636
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003637 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003638 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003639 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003640 if (hidlSession_3_4 != nullptr) {
3641 captureRequests_3_4.resize(batchSize);
3642 } else {
3643 captureRequests.resize(batchSize);
3644 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003645 std::vector<native_handle_t*> handlesCreated;
3646
3647 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003648 if (hidlSession_3_4 != nullptr) {
3649 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3650 /*out*/&handlesCreated);
3651 } else {
3652 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3653 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003654 }
3655
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003656 std::vector<device::V3_2::BufferCache> cachesToRemove;
3657 {
3658 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3659 for (auto& pair : mFreedBuffers) {
3660 // The stream might have been removed since onBufferFreed
3661 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3662 cachesToRemove.push_back({pair.first, pair.second});
3663 }
3664 }
3665 mFreedBuffers.clear();
3666 }
3667
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003668 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3669 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003670
3671 // Write metadata to FMQ.
3672 for (size_t i = 0; i < batchSize; i++) {
3673 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003674 device::V3_2::CaptureRequest* captureRequest;
3675 if (hidlSession_3_4 != nullptr) {
3676 captureRequest = &captureRequests_3_4[i].v3_2;
3677 } else {
3678 captureRequest = &captureRequests[i];
3679 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003680
3681 if (request->settings != nullptr) {
3682 size_t settingsSize = get_camera_metadata_size(request->settings);
3683 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3684 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3685 captureRequest->settings.resize(0);
3686 captureRequest->fmqSettingsSize = settingsSize;
3687 } else {
3688 if (mRequestMetadataQueue != nullptr) {
3689 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3690 }
3691 captureRequest->settings.setToExternal(
3692 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3693 get_camera_metadata_size(request->settings));
3694 captureRequest->fmqSettingsSize = 0u;
3695 }
3696 } else {
3697 // A null request settings maps to a size-0 CameraMetadata
3698 captureRequest->settings.resize(0);
3699 captureRequest->fmqSettingsSize = 0u;
3700 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003701
3702 if (hidlSession_3_4 != nullptr) {
3703 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3704 for (size_t j = 0; j < request->num_physcam_settings; j++) {
3705 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3706 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3707 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3708 settingsSize)) {
3709 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3710 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = settingsSize;
3711 } else {
3712 if (mRequestMetadataQueue != nullptr) {
3713 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3714 }
3715 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3716 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3717 request->physcam_settings[j])),
3718 get_camera_metadata_size(request->physcam_settings[j]));
3719 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
3720 }
3721 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3722 request->physcam_id[j];
3723 }
3724 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003725 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003726
3727 hardware::details::return_status err;
3728 if (hidlSession_3_4 != nullptr) {
3729 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003730 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3731 status = s;
3732 *numRequestProcessed = n;
3733 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003734 } else {
3735 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3736 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3737 status = s;
3738 *numRequestProcessed = n;
3739 });
3740 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003741 if (!err.isOk()) {
3742 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3743 return DEAD_OBJECT;
3744 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003745 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3746 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3747 __FUNCTION__, *numRequestProcessed, batchSize);
3748 status = common::V1_0::Status::INTERNAL_ERROR;
3749 }
3750
3751 for (auto& handle : handlesCreated) {
3752 native_handle_delete(handle);
3753 }
3754 return CameraProviderManager::mapToStatusT(status);
3755}
3756
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003757status_t Camera3Device::HalInterface::processCaptureRequest(
3758 camera3_capture_request_t *request) {
3759 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003760 if (!valid()) return INVALID_OPERATION;
3761 status_t res = OK;
3762
Emilian Peev31abd0a2017-05-11 18:37:46 +01003763 uint32_t numRequestProcessed = 0;
3764 std::vector<camera3_capture_request_t*> requests(1);
3765 requests[0] = request;
3766 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3767
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003768 return res;
3769}
3770
3771status_t Camera3Device::HalInterface::flush() {
3772 ATRACE_NAME("CameraHal::flush");
3773 if (!valid()) return INVALID_OPERATION;
3774 status_t res = OK;
3775
Emilian Peev31abd0a2017-05-11 18:37:46 +01003776 auto err = mHidlSession->flush();
3777 if (!err.isOk()) {
3778 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3779 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003780 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003781 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003782 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003783
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003784 return res;
3785}
3786
Emilian Peev31abd0a2017-05-11 18:37:46 +01003787status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003788 ATRACE_NAME("CameraHal::dump");
3789 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003790
Emilian Peev31abd0a2017-05-11 18:37:46 +01003791 // Handled by CameraProviderManager::dump
3792
3793 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003794}
3795
3796status_t Camera3Device::HalInterface::close() {
3797 ATRACE_NAME("CameraHal::close()");
3798 if (!valid()) return INVALID_OPERATION;
3799 status_t res = OK;
3800
Emilian Peev31abd0a2017-05-11 18:37:46 +01003801 auto err = mHidlSession->close();
3802 // Interface will be dead shortly anyway, so don't log errors
3803 if (!err.isOk()) {
3804 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003805 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003806
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003807 return res;
3808}
3809
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003810void Camera3Device::HalInterface::getInflightBufferKeys(
3811 std::vector<std::pair<int32_t, int32_t>>* out) {
3812 std::lock_guard<std::mutex> lock(mInflightLock);
3813 out->clear();
3814 out->reserve(mInflightBufferMap.size());
3815 for (auto& pair : mInflightBufferMap) {
3816 uint64_t key = pair.first;
3817 int32_t streamId = key & 0xFFFFFFFF;
3818 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3819 out->push_back(std::make_pair(frameNumber, streamId));
3820 }
3821 return;
3822}
3823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003824status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003825 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003826 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003827 auto pair = std::make_pair(buffer, acquireFence);
3828 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003829 return OK;
3830}
3831
3832status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003833 int32_t frameNumber, int32_t streamId,
3834 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003835 std::lock_guard<std::mutex> lock(mInflightLock);
3836
3837 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3838 auto it = mInflightBufferMap.find(key);
3839 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003840 auto pair = it->second;
3841 *buffer = pair.first;
3842 int acquireFence = pair.second;
3843 if (acquireFence > 0) {
3844 ::close(acquireFence);
3845 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003846 mInflightBufferMap.erase(it);
3847 return OK;
3848}
3849
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003850std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3851 const buffer_handle_t& buf, int streamId) {
3852 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3853
3854 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3855 auto it = bIdMap.find(buf);
3856 if (it == bIdMap.end()) {
3857 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003858 ALOGV("stream %d now have %zu buffer caches, buf %p",
3859 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003860 return std::make_pair(true, mNextBufferId - 1);
3861 } else {
3862 return std::make_pair(false, it->second);
3863 }
3864}
3865
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003866void Camera3Device::HalInterface::onBufferFreed(
3867 int streamId, const native_handle_t* handle) {
3868 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3869 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3870 auto mapIt = mBufferIdMaps.find(streamId);
3871 if (mapIt == mBufferIdMaps.end()) {
3872 // streamId might be from a deleted stream here
3873 ALOGI("%s: stream %d has been removed",
3874 __FUNCTION__, streamId);
3875 return;
3876 }
3877 BufferIdMap& bIdMap = mapIt->second;
3878 auto it = bIdMap.find(handle);
3879 if (it == bIdMap.end()) {
3880 ALOGW("%s: cannot find buffer %p in stream %d",
3881 __FUNCTION__, handle, streamId);
3882 return;
3883 } else {
3884 bufferId = it->second;
3885 bIdMap.erase(it);
3886 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3887 __FUNCTION__, streamId, bIdMap.size(), handle);
3888 }
3889 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3890}
3891
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003892/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003893 * RequestThread inner class methods
3894 */
3895
3896Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003897 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003898 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003899 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003900 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003901 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003902 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003903 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003904 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003905 mReconfigured(false),
3906 mDoPause(false),
3907 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003908 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003909 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003910 mCurrentAfTriggerId(0),
3911 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003912 mRepeatingLastFrameNumber(
3913 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003914 mPrepareVideoStream(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003915 mRequestLatency(kRequestLatencyBinSize),
3916 mSessionParamKeys(sessionParamKeys),
3917 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003918 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003919}
3920
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003921Camera3Device::RequestThread::~RequestThread() {}
3922
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003923void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003924 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003925 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003926 Mutex::Autolock l(mRequestLock);
3927 mListener = listener;
3928}
3929
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003930void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3931 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003932 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003933 Mutex::Autolock l(mRequestLock);
3934 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003935 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003936 // Prepare video stream for high speed recording.
3937 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003938}
3939
Jianing Wei90e59c92014-03-12 18:29:36 -07003940status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003941 List<sp<CaptureRequest> > &requests,
3942 /*out*/
3943 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003944 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003945 Mutex::Autolock l(mRequestLock);
3946 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3947 ++it) {
3948 mRequestQueue.push_back(*it);
3949 }
3950
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003951 if (lastFrameNumber != NULL) {
3952 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3953 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3954 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3955 *lastFrameNumber);
3956 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003957
Jianing Wei90e59c92014-03-12 18:29:36 -07003958 unpauseForNewRequests();
3959
3960 return OK;
3961}
3962
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003963
3964status_t Camera3Device::RequestThread::queueTrigger(
3965 RequestTrigger trigger[],
3966 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003967 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003968 Mutex::Autolock l(mTriggerMutex);
3969 status_t ret;
3970
3971 for (size_t i = 0; i < count; ++i) {
3972 ret = queueTriggerLocked(trigger[i]);
3973
3974 if (ret != OK) {
3975 return ret;
3976 }
3977 }
3978
3979 return OK;
3980}
3981
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003982const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3983 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003984 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003985 if (d != nullptr) return d->mId;
3986 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003987}
3988
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003989status_t Camera3Device::RequestThread::queueTriggerLocked(
3990 RequestTrigger trigger) {
3991
3992 uint32_t tag = trigger.metadataTag;
3993 ssize_t index = mTriggerMap.indexOfKey(tag);
3994
3995 switch (trigger.getTagType()) {
3996 case TYPE_BYTE:
3997 // fall-through
3998 case TYPE_INT32:
3999 break;
4000 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004001 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4002 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004003 return INVALID_OPERATION;
4004 }
4005
4006 /**
4007 * Collect only the latest trigger, since we only have 1 field
4008 * in the request settings per trigger tag, and can't send more than 1
4009 * trigger per request.
4010 */
4011 if (index != NAME_NOT_FOUND) {
4012 mTriggerMap.editValueAt(index) = trigger;
4013 } else {
4014 mTriggerMap.add(tag, trigger);
4015 }
4016
4017 return OK;
4018}
4019
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004020status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004021 const RequestList &requests,
4022 /*out*/
4023 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004024 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004025 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004026 if (lastFrameNumber != NULL) {
4027 *lastFrameNumber = mRepeatingLastFrameNumber;
4028 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004029 mRepeatingRequests.clear();
4030 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4031 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004032
4033 unpauseForNewRequests();
4034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004035 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004036 return OK;
4037}
4038
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004039bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004040 if (mRepeatingRequests.empty()) {
4041 return false;
4042 }
4043 int32_t requestId = requestIn->mResultExtras.requestId;
4044 const RequestList &repeatRequests = mRepeatingRequests;
4045 // All repeating requests are guaranteed to have same id so only check first quest
4046 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4047 return (firstRequest->mResultExtras.requestId == requestId);
4048}
4049
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004050status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004051 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004052 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004053 return clearRepeatingRequestsLocked(lastFrameNumber);
4054
4055}
4056
4057status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004058 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004059 if (lastFrameNumber != NULL) {
4060 *lastFrameNumber = mRepeatingLastFrameNumber;
4061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004062 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004063 return OK;
4064}
4065
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004066status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004067 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004068 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004069 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004070 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004071
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004072 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004073
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004074 // Send errors for all requests pending in the request queue, including
4075 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004076 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004077 if (listener != NULL) {
4078 for (RequestList::iterator it = mRequestQueue.begin();
4079 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004080 // Abort the input buffers for reprocess requests.
4081 if ((*it)->mInputStream != NULL) {
4082 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004083 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4084 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004085 if (res != OK) {
4086 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4087 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4088 } else {
4089 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4090 if (res != OK) {
4091 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4092 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4093 }
4094 }
4095 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004096 // Set the frame number this request would have had, if it
4097 // had been submitted; this frame number will not be reused.
4098 // The requestId and burstId fields were set when the request was
4099 // submitted originally (in convertMetadataListToRequestListLocked)
4100 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004101 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004102 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004103 }
4104 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004105 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004106
4107 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004108 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004109 if (lastFrameNumber != NULL) {
4110 *lastFrameNumber = mRepeatingLastFrameNumber;
4111 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004112 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004113 return OK;
4114}
4115
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004116status_t Camera3Device::RequestThread::flush() {
4117 ATRACE_CALL();
4118 Mutex::Autolock l(mFlushLock);
4119
Emilian Peev08dd2452017-04-06 16:55:14 +01004120 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004121}
4122
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004123void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004124 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004125 Mutex::Autolock l(mPauseLock);
4126 mDoPause = paused;
4127 mDoPauseSignal.signal();
4128}
4129
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004130status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4131 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004132 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004133 Mutex::Autolock l(mLatestRequestMutex);
4134 status_t res;
4135 while (mLatestRequestId != requestId) {
4136 nsecs_t startTime = systemTime();
4137
4138 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4139 if (res != OK) return res;
4140
4141 timeout -= (systemTime() - startTime);
4142 }
4143
4144 return OK;
4145}
4146
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004147void Camera3Device::RequestThread::requestExit() {
4148 // Call parent to set up shutdown
4149 Thread::requestExit();
4150 // The exit from any possible waits
4151 mDoPauseSignal.signal();
4152 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004153
4154 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4155 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004156}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004157
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004158void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004159 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004160 bool surfaceAbandoned = false;
4161 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004162 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004163 {
4164 Mutex::Autolock l(mRequestLock);
4165 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4166 // repeating requests.
4167 for (const auto& request : mRepeatingRequests) {
4168 for (const auto& s : request->mOutputStreams) {
4169 if (s->isAbandoned()) {
4170 surfaceAbandoned = true;
4171 clearRepeatingRequestsLocked(&lastFrameNumber);
4172 break;
4173 }
4174 }
4175 if (surfaceAbandoned) {
4176 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004177 }
4178 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004179 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004180 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004181
4182 if (listener != NULL && surfaceAbandoned) {
4183 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004184 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004185}
4186
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004187bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004188 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004189 status_t res;
4190 size_t batchSize = mNextRequests.size();
4191 std::vector<camera3_capture_request_t*> requests(batchSize);
4192 uint32_t numRequestProcessed = 0;
4193 for (size_t i = 0; i < batchSize; i++) {
4194 requests[i] = &mNextRequests.editItemAt(i).halRequest;
4195 }
4196
4197 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
4198 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4199
4200 bool triggerRemoveFailed = false;
4201 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4202 for (size_t i = 0; i < numRequestProcessed; i++) {
4203 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4204 nextRequest.submitted = true;
4205
4206
4207 // Update the latest request sent to HAL
4208 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4209 Mutex::Autolock al(mLatestRequestMutex);
4210
4211 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4212 mLatestRequest.acquire(cloned);
4213
4214 sp<Camera3Device> parent = mParent.promote();
4215 if (parent != NULL) {
4216 parent->monitorMetadata(TagMonitor::REQUEST,
4217 nextRequest.halRequest.frame_number,
4218 0, mLatestRequest);
4219 }
4220 }
4221
4222 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004223 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4224 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004225 }
4226
Emilian Peevaebbe412018-01-15 13:53:24 +00004227 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4228
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004229 if (!triggerRemoveFailed) {
4230 // Remove any previously queued triggers (after unlock)
4231 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4232 if (removeTriggerRes != OK) {
4233 triggerRemoveFailed = true;
4234 triggerFailedRequest = nextRequest;
4235 }
4236 }
4237 }
4238
4239 if (triggerRemoveFailed) {
4240 SET_ERR("RequestThread: Unable to remove triggers "
4241 "(capture request %d, HAL device: %s (%d)",
4242 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4243 cleanUpFailedRequests(/*sendRequestError*/ false);
4244 return false;
4245 }
4246
4247 if (res != OK) {
4248 // Should only get a failure here for malformed requests or device-level
4249 // errors, so consider all errors fatal. Bad metadata failures should
4250 // come through notify.
4251 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4252 mNextRequests[numRequestProcessed].halRequest.frame_number,
4253 strerror(-res), res);
4254 cleanUpFailedRequests(/*sendRequestError*/ false);
4255 return false;
4256 }
4257 return true;
4258}
4259
4260bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4261 status_t res;
4262
4263 for (auto& nextRequest : mNextRequests) {
4264 // Submit request and block until ready for next one
4265 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4266 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4267
4268 if (res != OK) {
4269 // Should only get a failure here for malformed requests or device-level
4270 // errors, so consider all errors fatal. Bad metadata failures should
4271 // come through notify.
4272 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4273 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4274 res);
4275 cleanUpFailedRequests(/*sendRequestError*/ false);
4276 return false;
4277 }
4278
4279 // Mark that the request has be submitted successfully.
4280 nextRequest.submitted = true;
4281
4282 // Update the latest request sent to HAL
4283 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4284 Mutex::Autolock al(mLatestRequestMutex);
4285
4286 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4287 mLatestRequest.acquire(cloned);
4288
4289 sp<Camera3Device> parent = mParent.promote();
4290 if (parent != NULL) {
4291 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4292 0, mLatestRequest);
4293 }
4294 }
4295
4296 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004297 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4298 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004299 }
4300
Emilian Peevaebbe412018-01-15 13:53:24 +00004301 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4302
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004303 // Remove any previously queued triggers (after unlock)
4304 res = removeTriggers(mPrevRequest);
4305 if (res != OK) {
4306 SET_ERR("RequestThread: Unable to remove triggers "
4307 "(capture request %d, HAL device: %s (%d)",
4308 nextRequest.halRequest.frame_number, strerror(-res), res);
4309 cleanUpFailedRequests(/*sendRequestError*/ false);
4310 return false;
4311 }
4312 }
4313 return true;
4314}
4315
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004316nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4317 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4318 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4319 find_camera_metadata_ro_entry(request,
4320 ANDROID_CONTROL_AE_MODE,
4321 &e);
4322 if (e.count == 0) return maxExpectedDuration;
4323
4324 switch (e.data.u8[0]) {
4325 case ANDROID_CONTROL_AE_MODE_OFF:
4326 find_camera_metadata_ro_entry(request,
4327 ANDROID_SENSOR_EXPOSURE_TIME,
4328 &e);
4329 if (e.count > 0) {
4330 maxExpectedDuration = e.data.i64[0];
4331 }
4332 find_camera_metadata_ro_entry(request,
4333 ANDROID_SENSOR_FRAME_DURATION,
4334 &e);
4335 if (e.count > 0) {
4336 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4337 }
4338 break;
4339 default:
4340 find_camera_metadata_ro_entry(request,
4341 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4342 &e);
4343 if (e.count > 1) {
4344 maxExpectedDuration = 1e9 / e.data.u8[0];
4345 }
4346 break;
4347 }
4348
4349 return maxExpectedDuration;
4350}
4351
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004352bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4353 ATRACE_CALL();
4354 bool updatesDetected = false;
4355
4356 for (auto tag : mSessionParamKeys) {
4357 camera_metadata_ro_entry entry = settings.find(tag);
4358 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4359
4360 if (entry.count > 0) {
4361 bool isDifferent = false;
4362 if (lastEntry.count > 0) {
4363 // Have a last value, compare to see if changed
4364 if (lastEntry.type == entry.type &&
4365 lastEntry.count == entry.count) {
4366 // Same type and count, compare values
4367 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4368 size_t entryBytes = bytesPerValue * lastEntry.count;
4369 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4370 if (cmp != 0) {
4371 isDifferent = true;
4372 }
4373 } else {
4374 // Count or type has changed
4375 isDifferent = true;
4376 }
4377 } else {
4378 // No last entry, so always consider to be different
4379 isDifferent = true;
4380 }
4381
4382 if (isDifferent) {
4383 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
4384 mLatestSessionParams.update(entry);
4385 updatesDetected = true;
4386 }
4387 } else if (lastEntry.count > 0) {
4388 // Value has been removed
4389 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4390 mLatestSessionParams.erase(tag);
4391 updatesDetected = true;
4392 }
4393 }
4394
4395 return updatesDetected;
4396}
4397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004398bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004399 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004400 status_t res;
4401
4402 // Handle paused state.
4403 if (waitIfPaused()) {
4404 return true;
4405 }
4406
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004407 // Wait for the next batch of requests.
4408 waitForNextRequestBatch();
4409 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004410 return true;
4411 }
4412
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004413 // Get the latest request ID, if any
4414 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004415 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004416 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004417 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004418 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004419 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004420 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4421 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004422 }
4423
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004424 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4425 // or a single request from streaming or burst. In either case the first element
4426 // should contain the latest camera settings that we need to check for any session
4427 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004428 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004429 res = OK;
4430
4431 //Input stream buffers are already acquired at this point so an input stream
4432 //will not be able to move to idle state unless we force it.
4433 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4434 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4435 if (res != OK) {
4436 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4437 cleanUpFailedRequests(/*sendRequestError*/ false);
4438 return false;
4439 }
4440 }
4441
4442 if (res == OK) {
4443 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4444 if (statusTracker != 0) {
4445 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4446
4447 sp<Camera3Device> parent = mParent.promote();
4448 if (parent != nullptr) {
4449 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4450 }
4451
4452 statusTracker->markComponentActive(mStatusId);
4453 setPaused(false);
4454 }
4455
4456 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4457 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4458 if (res != OK) {
4459 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4460 cleanUpFailedRequests(/*sendRequestError*/ false);
4461 return false;
4462 }
4463 }
4464 }
4465 }
4466
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004467 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004468 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004469 if (res == TIMED_OUT) {
4470 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004471 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004472 // Check if any stream is abandoned.
4473 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004474 return true;
4475 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004476 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004477 return false;
4478 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004479
Zhijun Hecc27e112013-10-03 16:12:43 -07004480 // Inform waitUntilRequestProcessed thread of a new request ID
4481 {
4482 Mutex::Autolock al(mLatestRequestMutex);
4483
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004484 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004485 mLatestRequestSignal.signal();
4486 }
4487
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004488 // Submit a batch of requests to HAL.
4489 // Use flush lock only when submitting multilple requests in a batch.
4490 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4491 // which may take a long time to finish so synchronizing flush() and
4492 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4493 // For now, only synchronize for high speed recording and we should figure something out for
4494 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004495 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004496
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004497 if (useFlushLock) {
4498 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004499 }
4500
Zhijun Hef0645c12016-08-02 00:58:11 -07004501 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004502 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004503
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004504 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004505 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004506 if (mInterface->supportBatchRequest()) {
4507 submitRequestSuccess = sendRequestsBatch();
4508 } else {
4509 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004510 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004511 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4512 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004513
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004514 if (useFlushLock) {
4515 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004516 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004517
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004518 // Unset as current request
4519 {
4520 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004521 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004522 }
4523
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004524 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004525}
4526
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004527status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004528 ATRACE_CALL();
4529
Shuzhen Wang4a472662017-02-26 23:29:04 -08004530 for (size_t i = 0; i < mNextRequests.size(); i++) {
4531 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004532 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4533 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4534 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4535
4536 // Prepare a request to HAL
4537 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4538
4539 // Insert any queued triggers (before metadata is locked)
4540 status_t res = insertTriggers(captureRequest);
4541
4542 if (res < 0) {
4543 SET_ERR("RequestThread: Unable to insert triggers "
4544 "(capture request %d, HAL device: %s (%d)",
4545 halRequest->frame_number, strerror(-res), res);
4546 return INVALID_OPERATION;
4547 }
4548 int triggerCount = res;
4549 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4550 mPrevTriggers = triggerCount;
4551
4552 // If the request is the same as last, or we had triggers last time
4553 if (mPrevRequest != captureRequest || triggersMixedIn) {
4554 /**
4555 * HAL workaround:
4556 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4557 */
4558 res = addDummyTriggerIds(captureRequest);
4559 if (res != OK) {
4560 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4561 "(capture request %d, HAL device: %s (%d)",
4562 halRequest->frame_number, strerror(-res), res);
4563 return INVALID_OPERATION;
4564 }
4565
4566 /**
4567 * The request should be presorted so accesses in HAL
4568 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4569 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004570 captureRequest->mSettingsList.begin()->metadata.sort();
4571 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004572 mPrevRequest = captureRequest;
4573 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4574
4575 IF_ALOGV() {
4576 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4577 find_camera_metadata_ro_entry(
4578 halRequest->settings,
4579 ANDROID_CONTROL_AF_TRIGGER,
4580 &e
4581 );
4582 if (e.count > 0) {
4583 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4584 __FUNCTION__,
4585 halRequest->frame_number,
4586 e.data.u8[0]);
4587 }
4588 }
4589 } else {
4590 // leave request.settings NULL to indicate 'reuse latest given'
4591 ALOGVV("%s: Request settings are REUSED",
4592 __FUNCTION__);
4593 }
4594
Emilian Peevaebbe412018-01-15 13:53:24 +00004595 if (captureRequest->mSettingsList.size() > 1) {
4596 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4597 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
4598 halRequest->physcam_settings =
4599 new const camera_metadata* [halRequest->num_physcam_settings];
4600 auto it = ++captureRequest->mSettingsList.begin();
4601 size_t i = 0;
4602 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4603 halRequest->physcam_id[i] = it->cameraId.c_str();
4604 it->metadata.sort();
4605 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4606 }
4607 }
4608
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004609 uint32_t totalNumBuffers = 0;
4610
4611 // Fill in buffers
4612 if (captureRequest->mInputStream != NULL) {
4613 halRequest->input_buffer = &captureRequest->mInputBuffer;
4614 totalNumBuffers += 1;
4615 } else {
4616 halRequest->input_buffer = NULL;
4617 }
4618
4619 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4620 captureRequest->mOutputStreams.size());
4621 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004622 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4623 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004624
4625 // Prepare video buffers for high speed recording on the first video request.
4626 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4627 // Only try to prepare video stream on the first video request.
4628 mPrepareVideoStream = false;
4629
4630 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4631 while (res == NOT_ENOUGH_DATA) {
4632 res = outputStream->prepareNextBuffer();
4633 }
4634 if (res != OK) {
4635 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4636 __FUNCTION__, strerror(-res), res);
4637 outputStream->cancelPrepare();
4638 }
4639 }
4640
Shuzhen Wang4a472662017-02-26 23:29:04 -08004641 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4642 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004643 if (res != OK) {
4644 // Can't get output buffer from gralloc queue - this could be due to
4645 // abandoned queue or other consumer misbehavior, so not a fatal
4646 // error
4647 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4648 " %s (%d)", strerror(-res), res);
4649
4650 return TIMED_OUT;
4651 }
4652 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004653
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004654 }
4655 totalNumBuffers += halRequest->num_output_buffers;
4656
4657 // Log request in the in-flight queue
4658 sp<Camera3Device> parent = mParent.promote();
4659 if (parent == NULL) {
4660 // Should not happen, and nowhere to send errors to, so just log it
4661 CLOGE("RequestThread: Parent is gone");
4662 return INVALID_OPERATION;
4663 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004664
4665 // If this request list is for constrained high speed recording (not
4666 // preview), and the current request is not the last one in the batch,
4667 // do not send callback to the app.
4668 bool hasCallback = true;
4669 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4670 hasCallback = false;
4671 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004672 res = parent->registerInFlight(halRequest->frame_number,
4673 totalNumBuffers, captureRequest->mResultExtras,
4674 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004675 hasCallback,
4676 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004677 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4678 ", burstId = %" PRId32 ".",
4679 __FUNCTION__,
4680 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4681 captureRequest->mResultExtras.burstId);
4682 if (res != OK) {
4683 SET_ERR("RequestThread: Unable to register new in-flight request:"
4684 " %s (%d)", strerror(-res), res);
4685 return INVALID_OPERATION;
4686 }
4687 }
4688
4689 return OK;
4690}
4691
Igor Murashkin1e479c02013-09-06 16:55:14 -07004692CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004693 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004694 Mutex::Autolock al(mLatestRequestMutex);
4695
4696 ALOGV("RequestThread::%s", __FUNCTION__);
4697
4698 return mLatestRequest;
4699}
4700
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004701bool Camera3Device::RequestThread::isStreamPending(
4702 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004703 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004704 Mutex::Autolock l(mRequestLock);
4705
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004706 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 if (!nextRequest.submitted) {
4708 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4709 if (stream == s) return true;
4710 }
4711 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004712 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004713 }
4714
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004715 for (const auto& request : mRequestQueue) {
4716 for (const auto& s : request->mOutputStreams) {
4717 if (stream == s) return true;
4718 }
4719 if (stream == request->mInputStream) return true;
4720 }
4721
4722 for (const auto& request : mRepeatingRequests) {
4723 for (const auto& s : request->mOutputStreams) {
4724 if (stream == s) return true;
4725 }
4726 if (stream == request->mInputStream) return true;
4727 }
4728
4729 return false;
4730}
Jianing Weicb0652e2014-03-12 18:29:36 -07004731
Emilian Peev40ead602017-09-26 15:46:36 +01004732bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4733 ATRACE_CALL();
4734 Mutex::Autolock l(mRequestLock);
4735
4736 for (const auto& nextRequest : mNextRequests) {
4737 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4738 if (s.first == streamId) {
4739 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4740 if (it != s.second.end()) {
4741 return true;
4742 }
4743 }
4744 }
4745 }
4746
4747 for (const auto& request : mRequestQueue) {
4748 for (const auto& s : request->mOutputSurfaces) {
4749 if (s.first == streamId) {
4750 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4751 if (it != s.second.end()) {
4752 return true;
4753 }
4754 }
4755 }
4756 }
4757
4758 for (const auto& request : mRepeatingRequests) {
4759 for (const auto& s : request->mOutputSurfaces) {
4760 if (s.first == streamId) {
4761 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4762 if (it != s.second.end()) {
4763 return true;
4764 }
4765 }
4766 }
4767 }
4768
4769 return false;
4770}
4771
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004772nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004773 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004774 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004775 return mExpectedInflightDuration > kMinInflightDuration ?
4776 mExpectedInflightDuration : kMinInflightDuration;
4777}
4778
Emilian Peevaebbe412018-01-15 13:53:24 +00004779void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4780 camera3_capture_request_t *halRequest) {
4781 if ((request == nullptr) || (halRequest == nullptr)) {
4782 ALOGE("%s: Invalid request!", __FUNCTION__);
4783 return;
4784 }
4785
4786 if (halRequest->num_physcam_settings > 0) {
4787 if (halRequest->physcam_id != nullptr) {
4788 delete [] halRequest->physcam_id;
4789 halRequest->physcam_id = nullptr;
4790 }
4791 if (halRequest->physcam_settings != nullptr) {
4792 auto it = ++(request->mSettingsList.begin());
4793 size_t i = 0;
4794 for (; it != request->mSettingsList.end(); it++, i++) {
4795 it->metadata.unlock(halRequest->physcam_settings[i]);
4796 }
4797 delete [] halRequest->physcam_settings;
4798 halRequest->physcam_settings = nullptr;
4799 }
4800 }
4801}
4802
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004803void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4804 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004805 return;
4806 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004807
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004808 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004809 // Skip the ones that have been submitted successfully.
4810 if (nextRequest.submitted) {
4811 continue;
4812 }
4813
4814 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4815 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4816 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4817
4818 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004819 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004820 }
4821
Emilian Peevaebbe412018-01-15 13:53:24 +00004822 cleanupPhysicalSettings(captureRequest, halRequest);
4823
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004824 if (captureRequest->mInputStream != NULL) {
4825 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4826 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4827 }
4828
4829 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004830 //Buffers that failed processing could still have
4831 //valid acquire fence.
4832 int acquireFence = (*outputBuffers)[i].acquire_fence;
4833 if (0 <= acquireFence) {
4834 close(acquireFence);
4835 outputBuffers->editItemAt(i).acquire_fence = -1;
4836 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004837 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4838 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4839 }
4840
4841 if (sendRequestError) {
4842 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004843 sp<NotificationListener> listener = mListener.promote();
4844 if (listener != NULL) {
4845 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004846 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004847 captureRequest->mResultExtras);
4848 }
4849 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004850
4851 // Remove yet-to-be submitted inflight request from inflightMap
4852 {
4853 sp<Camera3Device> parent = mParent.promote();
4854 if (parent != NULL) {
4855 Mutex::Autolock l(parent->mInFlightLock);
4856 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4857 if (idx >= 0) {
4858 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4859 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4860 parent->removeInFlightMapEntryLocked(idx);
4861 }
4862 }
4863 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004864 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004865
4866 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004867 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004868}
4869
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004870void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004871 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004872 // Optimized a bit for the simple steady-state case (single repeating
4873 // request), to avoid putting that request in the queue temporarily.
4874 Mutex::Autolock l(mRequestLock);
4875
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004876 assert(mNextRequests.empty());
4877
4878 NextRequest nextRequest;
4879 nextRequest.captureRequest = waitForNextRequestLocked();
4880 if (nextRequest.captureRequest == nullptr) {
4881 return;
4882 }
4883
4884 nextRequest.halRequest = camera3_capture_request_t();
4885 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004886 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004887
4888 // Wait for additional requests
4889 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4890
4891 for (size_t i = 1; i < batchSize; i++) {
4892 NextRequest additionalRequest;
4893 additionalRequest.captureRequest = waitForNextRequestLocked();
4894 if (additionalRequest.captureRequest == nullptr) {
4895 break;
4896 }
4897
4898 additionalRequest.halRequest = camera3_capture_request_t();
4899 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004900 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004901 }
4902
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004903 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004904 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004905 mNextRequests.size(), batchSize);
4906 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 }
4908
4909 return;
4910}
4911
4912sp<Camera3Device::CaptureRequest>
4913 Camera3Device::RequestThread::waitForNextRequestLocked() {
4914 status_t res;
4915 sp<CaptureRequest> nextRequest;
4916
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004917 while (mRequestQueue.empty()) {
4918 if (!mRepeatingRequests.empty()) {
4919 // Always atomically enqueue all requests in a repeating request
4920 // list. Guarantees a complete in-sequence set of captures to
4921 // application.
4922 const RequestList &requests = mRepeatingRequests;
4923 RequestList::const_iterator firstRequest =
4924 requests.begin();
4925 nextRequest = *firstRequest;
4926 mRequestQueue.insert(mRequestQueue.end(),
4927 ++firstRequest,
4928 requests.end());
4929 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004930
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004931 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004932
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004933 break;
4934 }
4935
4936 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4937
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004938 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4939 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004940 Mutex::Autolock pl(mPauseLock);
4941 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004942 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004943 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004944 // Let the tracker know
4945 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4946 if (statusTracker != 0) {
4947 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4948 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004949 }
4950 // Stop waiting for now and let thread management happen
4951 return NULL;
4952 }
4953 }
4954
4955 if (nextRequest == NULL) {
4956 // Don't have a repeating request already in hand, so queue
4957 // must have an entry now.
4958 RequestList::iterator firstRequest =
4959 mRequestQueue.begin();
4960 nextRequest = *firstRequest;
4961 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004962 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4963 sp<NotificationListener> listener = mListener.promote();
4964 if (listener != NULL) {
4965 listener->notifyRequestQueueEmpty();
4966 }
4967 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004968 }
4969
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004970 // In case we've been unpaused by setPaused clearing mDoPause, need to
4971 // update internal pause state (capture/setRepeatingRequest unpause
4972 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004973 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004974 if (mPaused) {
4975 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4976 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4977 if (statusTracker != 0) {
4978 statusTracker->markComponentActive(mStatusId);
4979 }
4980 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004981 mPaused = false;
4982
4983 // Check if we've reconfigured since last time, and reset the preview
4984 // request if so. Can't use 'NULL request == repeat' across configure calls.
4985 if (mReconfigured) {
4986 mPrevRequest.clear();
4987 mReconfigured = false;
4988 }
4989
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004990 if (nextRequest != NULL) {
4991 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004992 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4993 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004994
4995 // Since RequestThread::clear() removes buffers from the input stream,
4996 // get the right buffer here before unlocking mRequestLock
4997 if (nextRequest->mInputStream != NULL) {
4998 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4999 if (res != OK) {
5000 // Can't get input buffer from gralloc queue - this could be due to
5001 // disconnected queue or other producer misbehavior, so not a fatal
5002 // error
5003 ALOGE("%s: Can't get input buffer, skipping request:"
5004 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005005
5006 sp<NotificationListener> listener = mListener.promote();
5007 if (listener != NULL) {
5008 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005009 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005010 nextRequest->mResultExtras);
5011 }
5012 return NULL;
5013 }
5014 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005015 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005016
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005017 return nextRequest;
5018}
5019
5020bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005021 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005022 status_t res;
5023 Mutex::Autolock l(mPauseLock);
5024 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005025 if (mPaused == false) {
5026 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005027 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5028 // Let the tracker know
5029 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5030 if (statusTracker != 0) {
5031 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5032 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005033 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005034
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005035 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005036 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005037 return true;
5038 }
5039 }
5040 // We don't set mPaused to false here, because waitForNextRequest needs
5041 // to further manage the paused state in case of starvation.
5042 return false;
5043}
5044
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005045void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005046 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005047 // With work to do, mark thread as unpaused.
5048 // If paused by request (setPaused), don't resume, to avoid
5049 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005050 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005051 Mutex::Autolock p(mPauseLock);
5052 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005053 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5054 if (mPaused) {
5055 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5056 if (statusTracker != 0) {
5057 statusTracker->markComponentActive(mStatusId);
5058 }
5059 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005060 mPaused = false;
5061 }
5062}
5063
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005064void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5065 sp<Camera3Device> parent = mParent.promote();
5066 if (parent != NULL) {
5067 va_list args;
5068 va_start(args, fmt);
5069
5070 parent->setErrorStateV(fmt, args);
5071
5072 va_end(args);
5073 }
5074}
5075
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005076status_t Camera3Device::RequestThread::insertTriggers(
5077 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005078 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005079 Mutex::Autolock al(mTriggerMutex);
5080
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005081 sp<Camera3Device> parent = mParent.promote();
5082 if (parent == NULL) {
5083 CLOGE("RequestThread: Parent is gone");
5084 return DEAD_OBJECT;
5085 }
5086
Emilian Peevaebbe412018-01-15 13:53:24 +00005087 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005088 size_t count = mTriggerMap.size();
5089
5090 for (size_t i = 0; i < count; ++i) {
5091 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005092 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005093
5094 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5095 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5096 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005097 if (isAeTrigger) {
5098 request->mResultExtras.precaptureTriggerId = triggerId;
5099 mCurrentPreCaptureTriggerId = triggerId;
5100 } else {
5101 request->mResultExtras.afTriggerId = triggerId;
5102 mCurrentAfTriggerId = triggerId;
5103 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005104 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005105 }
5106
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005107 camera_metadata_entry entry = metadata.find(tag);
5108
5109 if (entry.count > 0) {
5110 /**
5111 * Already has an entry for this trigger in the request.
5112 * Rewrite it with our requested trigger value.
5113 */
5114 RequestTrigger oldTrigger = trigger;
5115
5116 oldTrigger.entryValue = entry.data.u8[0];
5117
5118 mTriggerReplacedMap.add(tag, oldTrigger);
5119 } else {
5120 /**
5121 * More typical, no trigger entry, so we just add it
5122 */
5123 mTriggerRemovedMap.add(tag, trigger);
5124 }
5125
5126 status_t res;
5127
5128 switch (trigger.getTagType()) {
5129 case TYPE_BYTE: {
5130 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5131 res = metadata.update(tag,
5132 &entryValue,
5133 /*count*/1);
5134 break;
5135 }
5136 case TYPE_INT32:
5137 res = metadata.update(tag,
5138 &trigger.entryValue,
5139 /*count*/1);
5140 break;
5141 default:
5142 ALOGE("%s: Type not supported: 0x%x",
5143 __FUNCTION__,
5144 trigger.getTagType());
5145 return INVALID_OPERATION;
5146 }
5147
5148 if (res != OK) {
5149 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5150 ", value %d", __FUNCTION__, trigger.getTagName(),
5151 trigger.entryValue);
5152 return res;
5153 }
5154
5155 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5156 trigger.getTagName(),
5157 trigger.entryValue);
5158 }
5159
5160 mTriggerMap.clear();
5161
5162 return count;
5163}
5164
5165status_t Camera3Device::RequestThread::removeTriggers(
5166 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005167 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005168 Mutex::Autolock al(mTriggerMutex);
5169
Emilian Peevaebbe412018-01-15 13:53:24 +00005170 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005171
5172 /**
5173 * Replace all old entries with their old values.
5174 */
5175 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5176 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5177
5178 status_t res;
5179
5180 uint32_t tag = trigger.metadataTag;
5181 switch (trigger.getTagType()) {
5182 case TYPE_BYTE: {
5183 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5184 res = metadata.update(tag,
5185 &entryValue,
5186 /*count*/1);
5187 break;
5188 }
5189 case TYPE_INT32:
5190 res = metadata.update(tag,
5191 &trigger.entryValue,
5192 /*count*/1);
5193 break;
5194 default:
5195 ALOGE("%s: Type not supported: 0x%x",
5196 __FUNCTION__,
5197 trigger.getTagType());
5198 return INVALID_OPERATION;
5199 }
5200
5201 if (res != OK) {
5202 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5203 ", trigger value %d", __FUNCTION__,
5204 trigger.getTagName(), trigger.entryValue);
5205 return res;
5206 }
5207 }
5208 mTriggerReplacedMap.clear();
5209
5210 /**
5211 * Remove all new entries.
5212 */
5213 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5214 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5215 status_t res = metadata.erase(trigger.metadataTag);
5216
5217 if (res != OK) {
5218 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5219 ", trigger value %d", __FUNCTION__,
5220 trigger.getTagName(), trigger.entryValue);
5221 return res;
5222 }
5223 }
5224 mTriggerRemovedMap.clear();
5225
5226 return OK;
5227}
5228
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005229status_t Camera3Device::RequestThread::addDummyTriggerIds(
5230 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005231 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005232 static const int32_t dummyTriggerId = 1;
5233 status_t res;
5234
Emilian Peevaebbe412018-01-15 13:53:24 +00005235 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005236
5237 // If AF trigger is active, insert a dummy AF trigger ID if none already
5238 // exists
5239 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5240 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5241 if (afTrigger.count > 0 &&
5242 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5243 afId.count == 0) {
5244 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5245 if (res != OK) return res;
5246 }
5247
5248 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5249 // if none already exists
5250 camera_metadata_entry pcTrigger =
5251 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5252 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5253 if (pcTrigger.count > 0 &&
5254 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5255 pcId.count == 0) {
5256 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5257 &dummyTriggerId, 1);
5258 if (res != OK) return res;
5259 }
5260
5261 return OK;
5262}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005263
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005264/**
5265 * PreparerThread inner class methods
5266 */
5267
5268Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005269 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005270 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005271}
5272
5273Camera3Device::PreparerThread::~PreparerThread() {
5274 Thread::requestExitAndWait();
5275 if (mCurrentStream != nullptr) {
5276 mCurrentStream->cancelPrepare();
5277 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5278 mCurrentStream.clear();
5279 }
5280 clear();
5281}
5282
Ruben Brunkc78ac262015-08-13 17:58:46 -07005283status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005284 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005285 status_t res;
5286
5287 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005288 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005289
Ruben Brunkc78ac262015-08-13 17:58:46 -07005290 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005291 if (res == OK) {
5292 // No preparation needed, fire listener right off
5293 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005294 if (listener != NULL) {
5295 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005296 }
5297 return OK;
5298 } else if (res != NOT_ENOUGH_DATA) {
5299 return res;
5300 }
5301
5302 // Need to prepare, start up thread if necessary
5303 if (!mActive) {
5304 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5305 // isn't running
5306 Thread::requestExitAndWait();
5307 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5308 if (res != OK) {
5309 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005310 if (listener != NULL) {
5311 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005312 }
5313 return res;
5314 }
5315 mCancelNow = false;
5316 mActive = true;
5317 ALOGV("%s: Preparer stream started", __FUNCTION__);
5318 }
5319
5320 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005321 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005322 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5323
5324 return OK;
5325}
5326
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005327void Camera3Device::PreparerThread::pause() {
5328 ATRACE_CALL();
5329
5330 Mutex::Autolock l(mLock);
5331
5332 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5333 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5334 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5335 int currentMaxCount = mCurrentMaxCount;
5336 mPendingStreams.clear();
5337 mCancelNow = true;
5338 while (mActive) {
5339 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5340 if (res == TIMED_OUT) {
5341 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5342 return;
5343 } else if (res != OK) {
5344 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5345 return;
5346 }
5347 }
5348
5349 //Check whether the prepare thread was able to complete the current
5350 //stream. In case work is still pending emplace it along with the rest
5351 //of the streams in the pending list.
5352 if (currentStream != nullptr) {
5353 if (!mCurrentPrepareComplete) {
5354 pendingStreams.emplace(currentMaxCount, currentStream);
5355 }
5356 }
5357
5358 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5359 for (const auto& it : mPendingStreams) {
5360 it.second->cancelPrepare();
5361 }
5362}
5363
5364status_t Camera3Device::PreparerThread::resume() {
5365 ATRACE_CALL();
5366 status_t res;
5367
5368 Mutex::Autolock l(mLock);
5369 sp<NotificationListener> listener = mListener.promote();
5370
5371 if (mActive) {
5372 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5373 return NO_INIT;
5374 }
5375
5376 auto it = mPendingStreams.begin();
5377 for (; it != mPendingStreams.end();) {
5378 res = it->second->startPrepare(it->first);
5379 if (res == OK) {
5380 if (listener != NULL) {
5381 listener->notifyPrepared(it->second->getId());
5382 }
5383 it = mPendingStreams.erase(it);
5384 } else if (res != NOT_ENOUGH_DATA) {
5385 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5386 res, strerror(-res));
5387 it = mPendingStreams.erase(it);
5388 } else {
5389 it++;
5390 }
5391 }
5392
5393 if (mPendingStreams.empty()) {
5394 return OK;
5395 }
5396
5397 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5398 if (res != OK) {
5399 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5400 __FUNCTION__, res, strerror(-res));
5401 return res;
5402 }
5403 mCancelNow = false;
5404 mActive = true;
5405 ALOGV("%s: Preparer stream started", __FUNCTION__);
5406
5407 return OK;
5408}
5409
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005410status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005411 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005412 Mutex::Autolock l(mLock);
5413
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005414 for (const auto& it : mPendingStreams) {
5415 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005416 }
5417 mPendingStreams.clear();
5418 mCancelNow = true;
5419
5420 return OK;
5421}
5422
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005423void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005424 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005425 Mutex::Autolock l(mLock);
5426 mListener = listener;
5427}
5428
5429bool Camera3Device::PreparerThread::threadLoop() {
5430 status_t res;
5431 {
5432 Mutex::Autolock l(mLock);
5433 if (mCurrentStream == nullptr) {
5434 // End thread if done with work
5435 if (mPendingStreams.empty()) {
5436 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5437 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5438 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5439 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005440 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005441 return false;
5442 }
5443
5444 // Get next stream to prepare
5445 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005446 mCurrentStream = it->second;
5447 mCurrentMaxCount = it->first;
5448 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005449 mPendingStreams.erase(it);
5450 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5451 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5452 } else if (mCancelNow) {
5453 mCurrentStream->cancelPrepare();
5454 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5455 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5456 mCurrentStream.clear();
5457 mCancelNow = false;
5458 return true;
5459 }
5460 }
5461
5462 res = mCurrentStream->prepareNextBuffer();
5463 if (res == NOT_ENOUGH_DATA) return true;
5464 if (res != OK) {
5465 // Something bad happened; try to recover by cancelling prepare and
5466 // signalling listener anyway
5467 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5468 mCurrentStream->getId(), res, strerror(-res));
5469 mCurrentStream->cancelPrepare();
5470 }
5471
5472 // This stream has finished, notify listener
5473 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005474 sp<NotificationListener> listener = mListener.promote();
5475 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005476 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5477 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005478 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005479 }
5480
5481 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5482 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005483 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005484
5485 return true;
5486}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005487
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005488/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005489 * Static callback forwarding methods from HAL to instance
5490 */
5491
5492void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5493 const camera3_capture_result *result) {
5494 Camera3Device *d =
5495 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005496
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005497 d->processCaptureResult(result);
5498}
5499
5500void Camera3Device::sNotify(const camera3_callback_ops *cb,
5501 const camera3_notify_msg *msg) {
5502 Camera3Device *d =
5503 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5504 d->notify(msg);
5505}
5506
5507}; // namespace android