blob: 16d699911f1124714e5355a04e288718dd3daf4a [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
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(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700744 const List<const CameraMetadata> &metadataList,
745 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;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700754 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
755 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++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700768 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
769 if (metadataIt->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 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700773 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700774 } else {
775 CLOGE("RequestID does not exist in metadata");
776 return BAD_VALUE;
777 }
778
Jianing Wei90e59c92014-03-12 18:29:36 -0700779 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700780
781 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700782 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700783 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
784 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
785 return BAD_VALUE;
786 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700787
788 // Setup batch size if this is a high speed video recording request.
789 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
790 auto firstRequest = requestList->begin();
791 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
792 if (outputStream->isVideoStream()) {
793 (*firstRequest)->mBatchSize = requestList->size();
794 break;
795 }
796 }
797 }
798
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 return OK;
800}
801
Jianing Weicb0652e2014-03-12 18:29:36 -0700802status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800803 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800804
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700805 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 std::list<const SurfaceMap> surfaceMaps;
807 convertToRequestList(requests, surfaceMaps, request);
808
809 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
810}
811
812void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
813 std::list<const SurfaceMap>& surfaceMaps,
814 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700815 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816
817 SurfaceMap surfaceMap;
818 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
819 // With no surface list passed in, stream and surface will have 1-to-1
820 // mapping. So the surface index is 0 for each stream in the surfaceMap.
821 for (size_t i = 0; i < streams.count; i++) {
822 surfaceMap[streams.data.i32[i]].push_back(0);
823 }
824 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800825}
826
Jianing Wei90e59c92014-03-12 18:29:36 -0700827status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700828 const List<const CameraMetadata> &requests,
829 const std::list<const SurfaceMap> &surfaceMaps,
830 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700831 /*out*/
832 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700833 ATRACE_CALL();
834 Mutex::Autolock il(mInterfaceLock);
835 Mutex::Autolock l(mLock);
836
837 status_t res = checkStatusOkToCaptureLocked();
838 if (res != OK) {
839 // error logged by previous call
840 return res;
841 }
842
843 RequestList requestList;
844
Shuzhen Wang0129d522016-10-30 22:43:41 -0700845 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
846 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700847 if (res != OK) {
848 // error logged by previous call
849 return res;
850 }
851
852 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700853 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700854 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700855 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700856 }
857
858 if (res == OK) {
859 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
860 if (res != OK) {
861 SET_ERR_L("Can't transition to active in %f seconds!",
862 kActiveTimeout/1e9);
863 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800864 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700865 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700866 } else {
867 CLOGE("Cannot queue request. Impossible.");
868 return BAD_VALUE;
869 }
870
871 return res;
872}
873
Yifan Honga640c5a2017-04-12 16:30:31 -0700874// Only one processCaptureResult should be called at a time, so
875// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800876hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800877 const hardware::hidl_vec<
878 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700879 // Ideally we should grab mLock, but that can lead to deadlock, and
880 // it's not super important to get up to date value of mStatus for this
881 // warning print, hence skipping the lock here
882 if (mStatus == STATUS_ERROR) {
883 // Per API contract, HAL should act as closed after device error
884 // But mStatus can be set to error by framework as well, so just log
885 // a warning here.
886 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700887 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700888
889 if (mProcessCaptureResultLock.tryLock() != OK) {
890 // This should never happen; it indicates a wrong client implementation
891 // that doesn't follow the contract. But, we can be tolerant here.
892 ALOGE("%s: callback overlapped! waiting 1s...",
893 __FUNCTION__);
894 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
895 ALOGE("%s: cannot acquire lock in 1s, dropping results",
896 __FUNCTION__);
897 // really don't know what to do, so bail out.
898 return hardware::Void();
899 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800900 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700901 for (const auto& result : results) {
902 processOneCaptureResultLocked(result);
903 }
904 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800905 return hardware::Void();
906}
907
Yifan Honga640c5a2017-04-12 16:30:31 -0700908void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800909 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800910 camera3_capture_result r;
911 status_t res;
912 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700913
914 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
915 if (result.fmqResultSize > 0) {
916 resultMetadata.resize(result.fmqResultSize);
917 if (mResultMetadataQueue == nullptr) {
918 return; // logged in initialize()
919 }
920 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
921 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
922 __FUNCTION__, result.frameNumber, result.fmqResultSize);
923 return;
924 }
925 } else {
926 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
927 result.result.size());
928 }
929
930 if (resultMetadata.size() != 0) {
931 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
932 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800933 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
934 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
935 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800936 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800937 }
938 } else {
939 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 }
941
942 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
943 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
944 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
945 auto& bDst = outputBuffers[i];
946 const StreamBuffer &bSrc = result.outputBuffers[i];
947
948 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100949 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800950 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
951 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800952 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800953 }
954 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
955
956 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800957 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800958 if (res != OK) {
959 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
960 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800961 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800962 }
963 bDst.buffer = buffer;
964 bDst.status = mapHidlBufferStatus(bSrc.status);
965 bDst.acquire_fence = -1;
966 if (bSrc.releaseFence == nullptr) {
967 bDst.release_fence = -1;
968 } else if (bSrc.releaseFence->numFds == 1) {
969 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
970 } else {
971 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
972 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800973 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800974 }
975 }
976 r.num_output_buffers = outputBuffers.size();
977 r.output_buffers = outputBuffers.data();
978
979 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800980 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 r.input_buffer = nullptr;
982 } else {
983 if (mInputStream->getId() != result.inputBuffer.streamId) {
984 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
985 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800986 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800987 }
988 inputBuffer.stream = mInputStream->asHalStream();
989 buffer_handle_t *buffer;
990 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
991 &buffer);
992 if (res != OK) {
993 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
994 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800995 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800996 }
997 inputBuffer.buffer = buffer;
998 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
999 inputBuffer.acquire_fence = -1;
1000 if (result.inputBuffer.releaseFence == nullptr) {
1001 inputBuffer.release_fence = -1;
1002 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1003 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1004 } else {
1005 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1006 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001007 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001008 }
1009 r.input_buffer = &inputBuffer;
1010 }
1011
1012 r.partial_result = result.partialResult;
1013
1014 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001015}
1016
1017hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001018 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001019 // Ideally we should grab mLock, but that can lead to deadlock, and
1020 // it's not super important to get up to date value of mStatus for this
1021 // warning print, hence skipping the lock here
1022 if (mStatus == STATUS_ERROR) {
1023 // Per API contract, HAL should act as closed after device error
1024 // But mStatus can be set to error by framework as well, so just log
1025 // a warning here.
1026 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001027 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001028
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001029 for (const auto& msg : msgs) {
1030 notify(msg);
1031 }
1032 return hardware::Void();
1033}
1034
1035void Camera3Device::notify(
1036 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1037
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001038 camera3_notify_msg m;
1039 switch (msg.type) {
1040 case MsgType::ERROR:
1041 m.type = CAMERA3_MSG_ERROR;
1042 m.message.error.frame_number = msg.msg.error.frameNumber;
1043 if (msg.msg.error.errorStreamId >= 0) {
1044 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001045 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001046 ALOGE("%s: Frame %d: Invalid error stream id %d",
1047 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001049 }
1050 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1051 } else {
1052 m.message.error.error_stream = nullptr;
1053 }
1054 switch (msg.msg.error.errorCode) {
1055 case ErrorCode::ERROR_DEVICE:
1056 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1057 break;
1058 case ErrorCode::ERROR_REQUEST:
1059 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1060 break;
1061 case ErrorCode::ERROR_RESULT:
1062 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1063 break;
1064 case ErrorCode::ERROR_BUFFER:
1065 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1066 break;
1067 }
1068 break;
1069 case MsgType::SHUTTER:
1070 m.type = CAMERA3_MSG_SHUTTER;
1071 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1072 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1073 break;
1074 }
1075 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001076}
1077
Jianing Weicb0652e2014-03-12 18:29:36 -07001078status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001079 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001080 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001081 ATRACE_CALL();
1082
Shuzhen Wang0129d522016-10-30 22:43:41 -07001083 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001084}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001085
Jianing Weicb0652e2014-03-12 18:29:36 -07001086status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1087 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001088 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001089
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001090 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 std::list<const SurfaceMap> surfaceMaps;
1092 convertToRequestList(requests, surfaceMaps, request);
1093
1094 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1095 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096}
1097
Jianing Weicb0652e2014-03-12 18:29:36 -07001098status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001099 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001100 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001101 ATRACE_CALL();
1102
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001104}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001105
1106sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001107 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001108 status_t res;
1109
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001110 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001111 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1112 // so unilaterally select normal operating mode.
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001113 res = filterParamsAndConfigureLocked(request, CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001114 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001116 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001118 } else if (mStatus == STATUS_UNCONFIGURED) {
1119 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001120 CLOGE("No streams configured");
1121 return NULL;
1122 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001123 }
1124
Shuzhen Wang0129d522016-10-30 22:43:41 -07001125 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001127}
1128
Jianing Weicb0652e2014-03-12 18:29:36 -07001129status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001130 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001131 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001133
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001134 switch (mStatus) {
1135 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001136 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 return INVALID_OPERATION;
1138 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001139 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001140 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001141 case STATUS_UNCONFIGURED:
1142 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 case STATUS_ACTIVE:
1144 // OK
1145 break;
1146 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001147 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148 return INVALID_OPERATION;
1149 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001150 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001151
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001152 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001153}
1154
1155status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1156 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001157 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001158
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001159 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001160}
1161
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162status_t Camera3Device::createInputStream(
1163 uint32_t width, uint32_t height, int format, int *id) {
1164 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001165 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001166 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001167 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001168 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1169 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001170
1171 status_t res;
1172 bool wasActive = false;
1173
1174 switch (mStatus) {
1175 case STATUS_ERROR:
1176 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1177 return INVALID_OPERATION;
1178 case STATUS_UNINITIALIZED:
1179 ALOGE("%s: Device not initialized", __FUNCTION__);
1180 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001181 case STATUS_UNCONFIGURED:
1182 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001183 // OK
1184 break;
1185 case STATUS_ACTIVE:
1186 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001187 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001188 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001190 return res;
1191 }
1192 wasActive = true;
1193 break;
1194 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196 return INVALID_OPERATION;
1197 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001198 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001199
1200 if (mInputStream != 0) {
1201 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1202 return INVALID_OPERATION;
1203 }
1204
1205 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1206 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001207 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001208
1209 mInputStream = newStream;
1210
1211 *id = mNextStreamId++;
1212
1213 // Continue captures if active at start
1214 if (wasActive) {
1215 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001216 // Reuse current operating mode and session parameters for new stream config
1217 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001218 if (res != OK) {
1219 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1220 __FUNCTION__, mNextStreamId, strerror(-res), res);
1221 return res;
1222 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001224 }
1225
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001226 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001227 return OK;
1228}
1229
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001230status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001231 uint32_t width, uint32_t height, int format,
1232 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001233 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001234 ATRACE_CALL();
1235
1236 if (consumer == nullptr) {
1237 ALOGE("%s: consumer must not be null", __FUNCTION__);
1238 return BAD_VALUE;
1239 }
1240
1241 std::vector<sp<Surface>> consumers;
1242 consumers.push_back(consumer);
1243
1244 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Emilian Peev40ead602017-09-26 15:46:36 +01001245 format, dataSpace, rotation, id, surfaceIds, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001246}
1247
1248status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1249 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1250 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001251 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001253
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001255 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001257 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Emilian Peev050f5dc2017-05-18 14:43:56 +01001258 " consumer usage %" PRIu64 ", isShared %d", mId.string(), mNextStreamId, width, height, format,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001259 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001260
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 status_t res;
1262 bool wasActive = false;
1263
1264 switch (mStatus) {
1265 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001266 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 return INVALID_OPERATION;
1268 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 case STATUS_UNCONFIGURED:
1272 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 // OK
1274 break;
1275 case STATUS_ACTIVE:
1276 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001277 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 return res;
1281 }
1282 wasActive = true;
1283 break;
1284 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001285 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 return INVALID_OPERATION;
1287 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001289
1290 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001291
Shuzhen Wang0129d522016-10-30 22:43:41 -07001292 if (consumers.size() == 0 && !hasDeferredConsumer) {
1293 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1294 return BAD_VALUE;
1295 }
Zhijun He5d677d12016-05-29 16:52:39 -07001296
Shuzhen Wang0129d522016-10-30 22:43:41 -07001297 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001298 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1299 return BAD_VALUE;
1300 }
1301
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001303 ssize_t blobBufferSize;
1304 if (dataSpace != HAL_DATASPACE_DEPTH) {
1305 blobBufferSize = getJpegBufferSize(width, height);
1306 if (blobBufferSize <= 0) {
1307 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1308 return BAD_VALUE;
1309 }
1310 } else {
1311 blobBufferSize = getPointCloudBufferSize();
1312 if (blobBufferSize <= 0) {
1313 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1314 return BAD_VALUE;
1315 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001316 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001317 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001318 width, height, blobBufferSize, format, dataSpace, rotation,
1319 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001320 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1321 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1322 if (rawOpaqueBufferSize <= 0) {
1323 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1324 return BAD_VALUE;
1325 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001326 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001327 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1328 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001329 } else if (isShared) {
1330 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1331 width, height, format, consumerUsage, dataSpace, rotation,
1332 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001333 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001334 newStream = new Camera3OutputStream(mNextStreamId,
1335 width, height, format, consumerUsage, dataSpace, rotation,
1336 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001338 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001339 width, height, format, dataSpace, rotation,
1340 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 }
Emilian Peev40ead602017-09-26 15:46:36 +01001342
1343 size_t consumerCount = consumers.size();
1344 for (size_t i = 0; i < consumerCount; i++) {
1345 int id = newStream->getSurfaceId(consumers[i]);
1346 if (id < 0) {
1347 SET_ERR_L("Invalid surface id");
1348 return BAD_VALUE;
1349 }
1350 if (surfaceIds != nullptr) {
1351 surfaceIds->push_back(id);
1352 }
1353 }
1354
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001355 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356
Emilian Peev08dd2452017-04-06 16:55:14 +01001357 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001358
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 res = mOutputStreams.add(mNextStreamId, newStream);
1360 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001361 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 return res;
1363 }
1364
1365 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001366 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367
1368 // Continue captures if active at start
1369 if (wasActive) {
1370 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001371 // Reuse current operating mode and session parameters for new stream config
1372 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001374 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1375 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 return res;
1377 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001380 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001382}
1383
Emilian Peev710c1422017-08-30 11:19:38 +01001384status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001385 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001386 if (nullptr == streamInfo) {
1387 return BAD_VALUE;
1388 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001389 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 switch (mStatus) {
1393 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001394 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 return INVALID_OPERATION;
1396 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001397 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001399 case STATUS_UNCONFIGURED:
1400 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001401 case STATUS_ACTIVE:
1402 // OK
1403 break;
1404 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001405 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return INVALID_OPERATION;
1407 }
1408
1409 ssize_t idx = mOutputStreams.indexOfKey(id);
1410 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001411 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return idx;
1413 }
1414
Emilian Peev710c1422017-08-30 11:19:38 +01001415 streamInfo->width = mOutputStreams[idx]->getWidth();
1416 streamInfo->height = mOutputStreams[idx]->getHeight();
1417 streamInfo->format = mOutputStreams[idx]->getFormat();
1418 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1419 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1420 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001421 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1422 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001424}
1425
1426status_t Camera3Device::setStreamTransform(int id,
1427 int transform) {
1428 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001429 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001431
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 switch (mStatus) {
1433 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001434 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 return INVALID_OPERATION;
1436 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001437 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001439 case STATUS_UNCONFIGURED:
1440 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 case STATUS_ACTIVE:
1442 // OK
1443 break;
1444 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 return INVALID_OPERATION;
1447 }
1448
1449 ssize_t idx = mOutputStreams.indexOfKey(id);
1450 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001451 CLOGE("Stream %d does not exist",
1452 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 return BAD_VALUE;
1454 }
1455
1456 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001457}
1458
1459status_t Camera3Device::deleteStream(int id) {
1460 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 Mutex::Autolock l(mLock);
1463 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001464
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001465 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 // CameraDevice semantics require device to already be idle before
1468 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001470 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001471 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 }
1473
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001474 if (mStatus == STATUS_ERROR) {
1475 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1476 __FUNCTION__, mId.string());
1477 return -EBUSY;
1478 }
1479
Igor Murashkin2fba5842013-04-22 14:03:54 -07001480 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001481 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 if (mInputStream != NULL && id == mInputStream->getId()) {
1483 deletedStream = mInputStream;
1484 mInputStream.clear();
1485 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001486 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return BAD_VALUE;
1489 }
Zhijun He5f446352014-01-22 09:49:33 -08001490 }
1491
1492 // Delete output stream or the output part of a bi-directional stream.
1493 if (outputStreamIdx != NAME_NOT_FOUND) {
1494 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 mOutputStreams.removeItem(id);
1496 }
1497
1498 // Free up the stream endpoint so that it can be used by some other stream
1499 res = deletedStream->disconnect();
1500 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001501 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 // fall through since we want to still list the stream as deleted.
1503 }
1504 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001505 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
1507 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001508}
1509
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001510status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001511 ATRACE_CALL();
1512 ALOGV("%s: E", __FUNCTION__);
1513
1514 Mutex::Autolock il(mInterfaceLock);
1515 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001516
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001517 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1518}
1519
1520status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1521 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001522 //Filter out any incoming session parameters
1523 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001524 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1525 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001526 CameraMetadata filteredParams(availableSessionKeys.count);
1527 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1528 filteredParams.getAndLock());
1529 set_camera_metadata_vendor_id(meta, mVendorTagId);
1530 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001531 if (availableSessionKeys.count > 0) {
1532 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1533 camera_metadata_ro_entry entry = params.find(
1534 availableSessionKeys.data.i32[i]);
1535 if (entry.count > 0) {
1536 filteredParams.update(entry);
1537 }
1538 }
1539 }
1540
1541 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001542}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001543
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001544status_t Camera3Device::getInputBufferProducer(
1545 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001546 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001547 Mutex::Autolock il(mInterfaceLock);
1548 Mutex::Autolock l(mLock);
1549
1550 if (producer == NULL) {
1551 return BAD_VALUE;
1552 } else if (mInputStream == NULL) {
1553 return INVALID_OPERATION;
1554 }
1555
1556 return mInputStream->getInputBufferProducer(producer);
1557}
1558
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001559status_t Camera3Device::createDefaultRequest(int templateId,
1560 CameraMetadata *request) {
1561 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001562 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001563
1564 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1565 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1566 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1567 return BAD_VALUE;
1568 }
1569
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001572 {
1573 Mutex::Autolock l(mLock);
1574 switch (mStatus) {
1575 case STATUS_ERROR:
1576 CLOGE("Device has encountered a serious error");
1577 return INVALID_OPERATION;
1578 case STATUS_UNINITIALIZED:
1579 CLOGE("Device is not initialized!");
1580 return INVALID_OPERATION;
1581 case STATUS_UNCONFIGURED:
1582 case STATUS_CONFIGURED:
1583 case STATUS_ACTIVE:
1584 // OK
1585 break;
1586 default:
1587 SET_ERR_L("Unexpected status: %d", mStatus);
1588 return INVALID_OPERATION;
1589 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001591 if (!mRequestTemplateCache[templateId].isEmpty()) {
1592 *request = mRequestTemplateCache[templateId];
1593 return OK;
1594 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001595 }
1596
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001597 camera_metadata_t *rawRequest;
1598 status_t res = mInterface->constructDefaultRequestSettings(
1599 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001600
1601 {
1602 Mutex::Autolock l(mLock);
1603 if (res == BAD_VALUE) {
1604 ALOGI("%s: template %d is not supported on this camera device",
1605 __FUNCTION__, templateId);
1606 return res;
1607 } else if (res != OK) {
1608 CLOGE("Unable to construct request template %d: %s (%d)",
1609 templateId, strerror(-res), res);
1610 return res;
1611 }
1612
1613 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1614 mRequestTemplateCache[templateId].acquire(rawRequest);
1615
1616 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001617 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618 return OK;
1619}
1620
1621status_t Camera3Device::waitUntilDrained() {
1622 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001623 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001624 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001627 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001628}
1629
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001630status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 switch (mStatus) {
1632 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001634 ALOGV("%s: Already idle", __FUNCTION__);
1635 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001636 case STATUS_CONFIGURED:
1637 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001638 case STATUS_ERROR:
1639 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001640 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 break;
1642 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001643 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001644 return INVALID_OPERATION;
1645 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001646 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1647 maxExpectedDuration);
1648 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001649 if (res != OK) {
1650 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1651 res);
1652 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001653 return res;
1654}
1655
Ruben Brunk183f0562015-08-12 12:55:02 -07001656
1657void Camera3Device::internalUpdateStatusLocked(Status status) {
1658 mStatus = status;
1659 mRecentStatusUpdates.add(mStatus);
1660 mStatusChanged.broadcast();
1661}
1662
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001664status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001665 mRequestThread->setPaused(true);
1666 mPauseStateNotify = true;
1667
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001668 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1669 maxExpectedDuration);
1670 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001671 if (res != OK) {
1672 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001673 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674 }
1675
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001676 return res;
1677}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001678
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679// Resume after internalPauseAndWaitLocked
1680status_t Camera3Device::internalResumeLocked() {
1681 status_t res;
1682
1683 mRequestThread->setPaused(false);
1684
1685 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1686 if (res != OK) {
1687 SET_ERR_L("Can't transition to active in %f seconds!",
1688 kActiveTimeout/1e9);
1689 }
1690 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001691 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692}
1693
Ruben Brunk183f0562015-08-12 12:55:02 -07001694status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001696
1697 size_t startIndex = 0;
1698 if (mStatusWaiters == 0) {
1699 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1700 // this status list
1701 mRecentStatusUpdates.clear();
1702 } else {
1703 // If other threads are waiting on updates to this status list, set the position of the
1704 // first element that this list will check rather than clearing the list.
1705 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 }
1707
Ruben Brunk183f0562015-08-12 12:55:02 -07001708 mStatusWaiters++;
1709
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001710 bool stateSeen = false;
1711 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001712 if (active == (mStatus == STATUS_ACTIVE)) {
1713 // Desired state is current
1714 break;
1715 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001716
1717 res = mStatusChanged.waitRelative(mLock, timeout);
1718 if (res != OK) break;
1719
Ruben Brunk183f0562015-08-12 12:55:02 -07001720 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1721 // transitions.
1722 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1723 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1724 __FUNCTION__);
1725
1726 // Encountered desired state since we began waiting
1727 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001728 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1729 stateSeen = true;
1730 break;
1731 }
1732 }
1733 } while (!stateSeen);
1734
Ruben Brunk183f0562015-08-12 12:55:02 -07001735 mStatusWaiters--;
1736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001737 return res;
1738}
1739
1740
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001741status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001742 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001743 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001745 if (listener != NULL && mListener != NULL) {
1746 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1747 }
1748 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001749 mRequestThread->setNotificationListener(listener);
1750 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001751
1752 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753}
1754
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001755bool Camera3Device::willNotify3A() {
1756 return false;
1757}
1758
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001759status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001760 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001761 status_t res;
1762 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001763
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001764 while (mResultQueue.empty()) {
1765 res = mResultSignal.waitRelative(mOutputLock, timeout);
1766 if (res == TIMED_OUT) {
1767 return res;
1768 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001769 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1770 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001771 return res;
1772 }
1773 }
1774 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001775}
1776
Jianing Weicb0652e2014-03-12 18:29:36 -07001777status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001778 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001779 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001780
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001781 if (mResultQueue.empty()) {
1782 return NOT_ENOUGH_DATA;
1783 }
1784
Jianing Weicb0652e2014-03-12 18:29:36 -07001785 if (frame == NULL) {
1786 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1787 return BAD_VALUE;
1788 }
1789
1790 CaptureResult &result = *(mResultQueue.begin());
1791 frame->mResultExtras = result.mResultExtras;
1792 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001793 mResultQueue.erase(mResultQueue.begin());
1794
1795 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001796}
1797
1798status_t Camera3Device::triggerAutofocus(uint32_t id) {
1799 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001801
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001802 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1803 // Mix-in this trigger into the next request and only the next request.
1804 RequestTrigger trigger[] = {
1805 {
1806 ANDROID_CONTROL_AF_TRIGGER,
1807 ANDROID_CONTROL_AF_TRIGGER_START
1808 },
1809 {
1810 ANDROID_CONTROL_AF_TRIGGER_ID,
1811 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001812 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001813 };
1814
1815 return mRequestThread->queueTrigger(trigger,
1816 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001817}
1818
1819status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1820 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001822
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1824 // Mix-in this trigger into the next request and only the next request.
1825 RequestTrigger trigger[] = {
1826 {
1827 ANDROID_CONTROL_AF_TRIGGER,
1828 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1829 },
1830 {
1831 ANDROID_CONTROL_AF_TRIGGER_ID,
1832 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001833 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001834 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001835
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001836 return mRequestThread->queueTrigger(trigger,
1837 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001838}
1839
1840status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1841 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001843
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001844 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1845 // Mix-in this trigger into the next request and only the next request.
1846 RequestTrigger trigger[] = {
1847 {
1848 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1849 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1850 },
1851 {
1852 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1853 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001854 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001855 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001856
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001857 return mRequestThread->queueTrigger(trigger,
1858 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001859}
1860
Jianing Weicb0652e2014-03-12 18:29:36 -07001861status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001862 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001863 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001865
Zhijun He7ef20392014-04-21 16:04:17 -07001866 {
1867 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001868 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001869 }
1870
Emilian Peev08dd2452017-04-06 16:55:14 +01001871 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001872}
1873
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001874status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001875 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1876}
1877
1878status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001879 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001880 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001881 Mutex::Autolock il(mInterfaceLock);
1882 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001883
1884 sp<Camera3StreamInterface> stream;
1885 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1886 if (outputStreamIdx == NAME_NOT_FOUND) {
1887 CLOGE("Stream %d does not exist", streamId);
1888 return BAD_VALUE;
1889 }
1890
1891 stream = mOutputStreams.editValueAt(outputStreamIdx);
1892
1893 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001894 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001895 return BAD_VALUE;
1896 }
1897
1898 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001899 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001900 return BAD_VALUE;
1901 }
1902
Ruben Brunkc78ac262015-08-13 17:58:46 -07001903 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001904}
1905
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001906status_t Camera3Device::tearDown(int streamId) {
1907 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001908 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001909 Mutex::Autolock il(mInterfaceLock);
1910 Mutex::Autolock l(mLock);
1911
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001912 sp<Camera3StreamInterface> stream;
1913 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1914 if (outputStreamIdx == NAME_NOT_FOUND) {
1915 CLOGE("Stream %d does not exist", streamId);
1916 return BAD_VALUE;
1917 }
1918
1919 stream = mOutputStreams.editValueAt(outputStreamIdx);
1920
1921 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1922 CLOGE("Stream %d is a target of a in-progress request", streamId);
1923 return BAD_VALUE;
1924 }
1925
1926 return stream->tearDown();
1927}
1928
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001929status_t Camera3Device::addBufferListenerForStream(int streamId,
1930 wp<Camera3StreamBufferListener> listener) {
1931 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001932 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001933 Mutex::Autolock il(mInterfaceLock);
1934 Mutex::Autolock l(mLock);
1935
1936 sp<Camera3StreamInterface> stream;
1937 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1938 if (outputStreamIdx == NAME_NOT_FOUND) {
1939 CLOGE("Stream %d does not exist", streamId);
1940 return BAD_VALUE;
1941 }
1942
1943 stream = mOutputStreams.editValueAt(outputStreamIdx);
1944 stream->addBufferListener(listener);
1945
1946 return OK;
1947}
1948
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001949/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001950 * Methods called by subclasses
1951 */
1952
1953void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001954 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001955 {
1956 // Need mLock to safely update state and synchronize to current
1957 // state of methods in flight.
1958 Mutex::Autolock l(mLock);
1959 // We can get various system-idle notices from the status tracker
1960 // while starting up. Only care about them if we've actually sent
1961 // in some requests recently.
1962 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1963 return;
1964 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001965 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001966 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001967 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001968
1969 // Skip notifying listener if we're doing some user-transparent
1970 // state changes
1971 if (mPauseStateNotify) return;
1972 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001973
1974 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001975 {
1976 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001977 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001978 }
1979 if (idle && listener != NULL) {
1980 listener->notifyIdle();
1981 }
1982}
1983
Shuzhen Wang758c2152017-01-10 18:26:18 -08001984status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001985 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001986 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001987 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1988 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001989
1990 if (surfaceIds == nullptr) {
1991 return BAD_VALUE;
1992 }
1993
Zhijun He5d677d12016-05-29 16:52:39 -07001994 Mutex::Autolock il(mInterfaceLock);
1995 Mutex::Autolock l(mLock);
1996
Shuzhen Wang758c2152017-01-10 18:26:18 -08001997 if (consumers.size() == 0) {
1998 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001999 return BAD_VALUE;
2000 }
2001
2002 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2003 if (idx == NAME_NOT_FOUND) {
2004 CLOGE("Stream %d is unknown", streamId);
2005 return idx;
2006 }
2007 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002008 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002009 if (res != OK) {
2010 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2011 return res;
2012 }
2013
Emilian Peev40ead602017-09-26 15:46:36 +01002014 for (auto &consumer : consumers) {
2015 int id = stream->getSurfaceId(consumer);
2016 if (id < 0) {
2017 CLOGE("Invalid surface id!");
2018 return BAD_VALUE;
2019 }
2020 surfaceIds->push_back(id);
2021 }
2022
Shuzhen Wang0129d522016-10-30 22:43:41 -07002023 if (stream->isConsumerConfigurationDeferred()) {
2024 if (!stream->isConfiguring()) {
2025 CLOGE("Stream %d was already fully configured.", streamId);
2026 return INVALID_OPERATION;
2027 }
Zhijun He5d677d12016-05-29 16:52:39 -07002028
Shuzhen Wang0129d522016-10-30 22:43:41 -07002029 res = stream->finishConfiguration();
2030 if (res != OK) {
2031 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2032 stream->getId(), strerror(-res), res);
2033 return res;
2034 }
Zhijun He5d677d12016-05-29 16:52:39 -07002035 }
2036
2037 return OK;
2038}
2039
Emilian Peev40ead602017-09-26 15:46:36 +01002040status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2041 const std::vector<OutputStreamInfo> &outputInfo,
2042 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2043 Mutex::Autolock il(mInterfaceLock);
2044 Mutex::Autolock l(mLock);
2045
2046 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2047 if (idx == NAME_NOT_FOUND) {
2048 CLOGE("Stream %d is unknown", streamId);
2049 return idx;
2050 }
2051
2052 for (const auto &it : removedSurfaceIds) {
2053 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2054 CLOGE("Shared surface still part of a pending request!");
2055 return -EBUSY;
2056 }
2057 }
2058
2059 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2060 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2061 if (res != OK) {
2062 CLOGE("Stream %d failed to update stream (error %d %s) ",
2063 streamId, res, strerror(-res));
2064 if (res == UNKNOWN_ERROR) {
2065 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2066 __FUNCTION__);
2067 }
2068 return res;
2069 }
2070
2071 return res;
2072}
2073
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002074status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2075 Mutex::Autolock il(mInterfaceLock);
2076 Mutex::Autolock l(mLock);
2077
2078 int idx = mOutputStreams.indexOfKey(streamId);
2079 if (idx == NAME_NOT_FOUND) {
2080 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2081 return BAD_VALUE;
2082 }
2083
2084 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2085 return stream->dropBuffers(dropping);
2086}
2087
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002088/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002089 * Camera3Device private methods
2090 */
2091
2092sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002093 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094 ATRACE_CALL();
2095 status_t res;
2096
2097 sp<CaptureRequest> newRequest = new CaptureRequest;
2098 newRequest->mSettings = request;
2099
2100 camera_metadata_entry_t inputStreams =
2101 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2102 if (inputStreams.count > 0) {
2103 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002104 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002105 CLOGE("Request references unknown input stream %d",
2106 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 return NULL;
2108 }
2109 // Lazy completion of stream configuration (allocation/registration)
2110 // on first use
2111 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002112 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002114 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002116 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 return NULL;
2118 }
2119 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002120 // Check if stream is being prepared
2121 if (mInputStream->isPreparing()) {
2122 CLOGE("Request references an input stream that's being prepared!");
2123 return NULL;
2124 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125
2126 newRequest->mInputStream = mInputStream;
2127 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2128 }
2129
2130 camera_metadata_entry_t streams =
2131 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2132 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002133 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002134 return NULL;
2135 }
2136
2137 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002138 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002140 CLOGE("Request references unknown stream %d",
2141 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 return NULL;
2143 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002144 sp<Camera3OutputStreamInterface> stream =
2145 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146
Zhijun He5d677d12016-05-29 16:52:39 -07002147 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002148 auto iter = surfaceMap.find(streams.data.i32[i]);
2149 if (iter != surfaceMap.end()) {
2150 const std::vector<size_t>& surfaces = iter->second;
2151 for (const auto& surface : surfaces) {
2152 if (stream->isConsumerConfigurationDeferred(surface)) {
2153 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2154 "due to deferred consumer", stream->getId(), surface);
2155 return NULL;
2156 }
2157 }
2158 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002159 }
2160
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002161 // Lazy completion of stream configuration (allocation/registration)
2162 // on first use
2163 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002164 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002166 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2167 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002168 return NULL;
2169 }
2170 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002171 // Check if stream is being prepared
2172 if (stream->isPreparing()) {
2173 CLOGE("Request references an output stream that's being prepared!");
2174 return NULL;
2175 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002176
2177 newRequest->mOutputStreams.push(stream);
2178 }
2179 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002180 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181
2182 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002183}
2184
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002185bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2186 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2187 Size size = mSupportedOpaqueInputSizes[i];
2188 if (size.width == width && size.height == height) {
2189 return true;
2190 }
2191 }
2192
2193 return false;
2194}
2195
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002196void Camera3Device::cancelStreamsConfigurationLocked() {
2197 int res = OK;
2198 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2199 res = mInputStream->cancelConfiguration();
2200 if (res != OK) {
2201 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2202 mInputStream->getId(), strerror(-res), res);
2203 }
2204 }
2205
2206 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2207 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2208 if (outputStream->isConfiguring()) {
2209 res = outputStream->cancelConfiguration();
2210 if (res != OK) {
2211 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2212 outputStream->getId(), strerror(-res), res);
2213 }
2214 }
2215 }
2216
2217 // Return state to that at start of call, so that future configures
2218 // properly clean things up
2219 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2220 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002221
2222 res = mPreparerThread->resume();
2223 if (res != OK) {
2224 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2225 }
2226}
2227
2228bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2229 ATRACE_CALL();
2230 bool ret = false;
2231
2232 Mutex::Autolock il(mInterfaceLock);
2233 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2234
2235 Mutex::Autolock l(mLock);
2236 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2237 if (rc == NO_ERROR) {
2238 mNeedConfig = true;
2239 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2240 if (rc == NO_ERROR) {
2241 ret = true;
2242 mPauseStateNotify = false;
2243 //Moving to active state while holding 'mLock' is important.
2244 //There could be pending calls to 'create-/deleteStream' which
2245 //will trigger another stream configuration while the already
2246 //present streams end up with outstanding buffers that will
2247 //not get drained.
2248 internalUpdateStatusLocked(STATUS_ACTIVE);
2249 } else {
2250 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2251 __FUNCTION__, rc);
2252 }
2253 } else {
2254 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2255 }
2256
2257 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002258}
2259
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002260status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002261 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 ATRACE_CALL();
2263 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002264
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002265 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002266 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002267 return INVALID_OPERATION;
2268 }
2269
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002270 if (operatingMode < 0) {
2271 CLOGE("Invalid operating mode: %d", operatingMode);
2272 return BAD_VALUE;
2273 }
2274
2275 bool isConstrainedHighSpeed =
2276 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2277 operatingMode;
2278
2279 if (mOperatingMode != operatingMode) {
2280 mNeedConfig = true;
2281 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2282 mOperatingMode = operatingMode;
2283 }
2284
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002285 if (!mNeedConfig) {
2286 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2287 return OK;
2288 }
2289
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002290 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2291 // adding a dummy stream instead.
2292 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2293 if (mOutputStreams.size() == 0) {
2294 addDummyStreamLocked();
2295 } else {
2296 tryRemoveDummyStreamLocked();
2297 }
2298
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002300 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002302 mPreparerThread->pause();
2303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002305 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2307
2308 Vector<camera3_stream_t*> streams;
2309 streams.setCapacity(config.num_streams);
2310
2311 if (mInputStream != NULL) {
2312 camera3_stream_t *inputStream;
2313 inputStream = mInputStream->startConfiguration();
2314 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002315 CLOGE("Can't start input stream configuration");
2316 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317 return INVALID_OPERATION;
2318 }
2319 streams.add(inputStream);
2320 }
2321
2322 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002323
2324 // Don't configure bidi streams twice, nor add them twice to the list
2325 if (mOutputStreams[i].get() ==
2326 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2327
2328 config.num_streams--;
2329 continue;
2330 }
2331
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002332 camera3_stream_t *outputStream;
2333 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2334 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002335 CLOGE("Can't start output stream configuration");
2336 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002337 return INVALID_OPERATION;
2338 }
2339 streams.add(outputStream);
2340 }
2341
2342 config.streams = streams.editArray();
2343
2344 // Do the HAL configuration; will potentially touch stream
2345 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002346
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002347 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
2348 res = mInterface->configureStreams(sessionBuffer, &config);
2349 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002351 if (res == BAD_VALUE) {
2352 // HAL rejected this set of streams as unsupported, clean up config
2353 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002354 CLOGE("Set of requested inputs/outputs not supported by HAL");
2355 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002356 return BAD_VALUE;
2357 } else if (res != OK) {
2358 // Some other kind of error from configure_streams - this is not
2359 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002360 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2361 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002362 return res;
2363 }
2364
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002365 // Finish all stream configuration immediately.
2366 // TODO: Try to relax this later back to lazy completion, which should be
2367 // faster
2368
Igor Murashkin073f8572013-05-02 14:59:28 -07002369 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002370 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002371 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002372 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002373 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002374 cancelStreamsConfigurationLocked();
2375 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002376 }
2377 }
2378
2379 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002380 sp<Camera3OutputStreamInterface> outputStream =
2381 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002382 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002383 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002384 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002385 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002386 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002387 cancelStreamsConfigurationLocked();
2388 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002389 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002390 }
2391 }
2392
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 // Request thread needs to know to avoid using repeat-last-settings protocol
2394 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002395 if (notifyRequestThread) {
2396 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2397 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398
Zhijun He90f7c372016-08-16 16:19:43 -07002399 char value[PROPERTY_VALUE_MAX];
2400 property_get("camera.fifo.disable", value, "0");
2401 int32_t disableFifo = atoi(value);
2402 if (disableFifo != 1) {
2403 // Boost priority of request thread to SCHED_FIFO.
2404 pid_t requestThreadTid = mRequestThread->getTid();
2405 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002406 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002407 if (res != OK) {
2408 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2409 strerror(-res), res);
2410 } else {
2411 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2412 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002413 }
2414
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002415 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002416 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2417 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2418 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2419 sessionParams.unlock(newSessionParams);
2420 mSessionParams.unlock(currentSessionParams);
2421 if (updateSessionParams) {
2422 mSessionParams = sessionParams;
2423 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002425 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426
Ruben Brunk183f0562015-08-12 12:55:02 -07002427 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2428 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002429
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002430 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002431
Zhijun He0a210512014-07-24 13:45:15 -07002432 // tear down the deleted streams after configure streams.
2433 mDeletedStreams.clear();
2434
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002435 auto rc = mPreparerThread->resume();
2436 if (rc != OK) {
2437 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2438 return rc;
2439 }
2440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002442}
2443
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002444status_t Camera3Device::addDummyStreamLocked() {
2445 ATRACE_CALL();
2446 status_t res;
2447
2448 if (mDummyStreamId != NO_STREAM) {
2449 // Should never be adding a second dummy stream when one is already
2450 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002451 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2452 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002453 return INVALID_OPERATION;
2454 }
2455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002456 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002457
2458 sp<Camera3OutputStreamInterface> dummyStream =
2459 new Camera3DummyStream(mNextStreamId);
2460
2461 res = mOutputStreams.add(mNextStreamId, dummyStream);
2462 if (res < 0) {
2463 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2464 return res;
2465 }
2466
2467 mDummyStreamId = mNextStreamId;
2468 mNextStreamId++;
2469
2470 return OK;
2471}
2472
2473status_t Camera3Device::tryRemoveDummyStreamLocked() {
2474 ATRACE_CALL();
2475 status_t res;
2476
2477 if (mDummyStreamId == NO_STREAM) return OK;
2478 if (mOutputStreams.size() == 1) return OK;
2479
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002480 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002481
2482 // Ok, have a dummy stream and there's at least one other output stream,
2483 // so remove the dummy
2484
2485 sp<Camera3StreamInterface> deletedStream;
2486 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2487 if (outputStreamIdx == NAME_NOT_FOUND) {
2488 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2489 return INVALID_OPERATION;
2490 }
2491
2492 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2493 mOutputStreams.removeItemsAt(outputStreamIdx);
2494
2495 // Free up the stream endpoint so that it can be used by some other stream
2496 res = deletedStream->disconnect();
2497 if (res != OK) {
2498 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2499 // fall through since we want to still list the stream as deleted.
2500 }
2501 mDeletedStreams.add(deletedStream);
2502 mDummyStreamId = NO_STREAM;
2503
2504 return res;
2505}
2506
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002507void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002508 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002509 Mutex::Autolock l(mLock);
2510 va_list args;
2511 va_start(args, fmt);
2512
2513 setErrorStateLockedV(fmt, args);
2514
2515 va_end(args);
2516}
2517
2518void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002519 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002520 Mutex::Autolock l(mLock);
2521 setErrorStateLockedV(fmt, args);
2522}
2523
2524void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2525 va_list args;
2526 va_start(args, fmt);
2527
2528 setErrorStateLockedV(fmt, args);
2529
2530 va_end(args);
2531}
2532
2533void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002534 // Print out all error messages to log
2535 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002536 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002537
2538 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002539 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002540
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002541 mErrorCause = errorCause;
2542
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002543 if (mRequestThread != nullptr) {
2544 mRequestThread->setPaused(true);
2545 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002546 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002547
2548 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002549 sp<NotificationListener> listener = mListener.promote();
2550 if (listener != NULL) {
2551 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002552 CaptureResultExtras());
2553 }
2554
2555 // Save stack trace. View by dumping it later.
2556 CameraTraces::saveTrace();
2557 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002558}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002559
2560/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002561 * In-flight request management
2562 */
2563
Jianing Weicb0652e2014-03-12 18:29:36 -07002564status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002565 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002566 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002567 ATRACE_CALL();
2568 Mutex::Autolock l(mInFlightLock);
2569
2570 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002571 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002572 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002573 if (res < 0) return res;
2574
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002575 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002576 // hold mLock to prevent race with disconnect
2577 Mutex::Autolock l(mLock);
2578 if (mStatusTracker != nullptr) {
2579 mStatusTracker->markComponentActive(mInFlightStatusId);
2580 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002581 }
2582
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002583 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002584 return OK;
2585}
2586
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002587void Camera3Device::returnOutputBuffers(
2588 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2589 nsecs_t timestamp) {
2590 for (size_t i = 0; i < numBuffers; i++)
2591 {
2592 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2593 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2594 // Note: stream may be deallocated at this point, if this buffer was
2595 // the last reference to it.
2596 if (res != OK) {
2597 ALOGE("Can't return buffer to its stream: %s (%d)",
2598 strerror(-res), res);
2599 }
2600 }
2601}
2602
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002603void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002604 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002605 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002606 mInFlightMap.removeItemsAt(idx, 1);
2607
2608 // Indicate idle inFlightMap to the status tracker
2609 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002610 // hold mLock to prevent race with disconnect
2611 Mutex::Autolock l(mLock);
2612 if (mStatusTracker != nullptr) {
2613 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2614 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002615 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002616 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002617}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002618
2619void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2620
2621 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2622 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2623
2624 nsecs_t sensorTimestamp = request.sensorTimestamp;
2625 nsecs_t shutterTimestamp = request.shutterTimestamp;
2626
2627 // Check if it's okay to remove the request from InFlightMap:
2628 // In the case of a successful request:
2629 // all input and output buffers, all result metadata, shutter callback
2630 // arrived.
2631 // In the case of a unsuccessful request:
2632 // all input and output buffers arrived.
2633 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002634 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002635 (request.haveResultMetadata && shutterTimestamp != 0))) {
2636 ATRACE_ASYNC_END("frame capture", frameNumber);
2637
Shuzhen Wang403044a2017-02-26 23:29:04 -08002638 // Sanity check - if sensor timestamp matches shutter timestamp in the
2639 // case of request having callback.
2640 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002641 sensorTimestamp != shutterTimestamp) {
2642 SET_ERR("sensor timestamp (%" PRId64
2643 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2644 sensorTimestamp, frameNumber, shutterTimestamp);
2645 }
2646
2647 // for an unsuccessful request, it may have pending output buffers to
2648 // return.
2649 assert(request.requestStatus != OK ||
2650 request.pendingOutputBuffers.size() == 0);
2651 returnOutputBuffers(request.pendingOutputBuffers.array(),
2652 request.pendingOutputBuffers.size(), 0);
2653
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002654 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002655 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2656 }
2657
2658 // Sanity check - if we have too many in-flight frames, something has
2659 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002660 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002661 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002662 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2663 kInFlightWarnLimitHighSpeed) {
2664 CLOGE("In-flight list too large for high speed configuration: %zu",
2665 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002666 }
2667}
2668
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002669void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002670 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002671 { // First return buffers cached in mInFlightMap
2672 Mutex::Autolock l(mInFlightLock);
2673 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2674 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2675 returnOutputBuffers(request.pendingOutputBuffers.array(),
2676 request.pendingOutputBuffers.size(), 0);
2677 }
2678 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002679 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002680 }
2681
2682 // Then return all inflight buffers not returned by HAL
2683 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2684 mInterface->getInflightBufferKeys(&inflightKeys);
2685
2686 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2687 for (auto& pair : inflightKeys) {
2688 int32_t frameNumber = pair.first;
2689 int32_t streamId = pair.second;
2690 buffer_handle_t* buffer;
2691 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2692 if (res != OK) {
2693 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2694 __FUNCTION__, frameNumber, streamId);
2695 continue;
2696 }
2697
2698 camera3_stream_buffer_t streamBuffer;
2699 streamBuffer.buffer = buffer;
2700 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2701 streamBuffer.acquire_fence = -1;
2702 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002703
2704 // First check if the buffer belongs to deleted stream
2705 bool streamDeleted = false;
2706 for (auto& stream : mDeletedStreams) {
2707 if (streamId == stream->getId()) {
2708 streamDeleted = true;
2709 // Return buffer to deleted stream
2710 camera3_stream* halStream = stream->asHalStream();
2711 streamBuffer.stream = halStream;
2712 switch (halStream->stream_type) {
2713 case CAMERA3_STREAM_OUTPUT:
2714 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2715 if (res != OK) {
2716 ALOGE("%s: Can't return output buffer for frame %d to"
2717 " stream %d: %s (%d)", __FUNCTION__,
2718 frameNumber, streamId, strerror(-res), res);
2719 }
2720 break;
2721 case CAMERA3_STREAM_INPUT:
2722 res = stream->returnInputBuffer(streamBuffer);
2723 if (res != OK) {
2724 ALOGE("%s: Can't return input buffer for frame %d to"
2725 " stream %d: %s (%d)", __FUNCTION__,
2726 frameNumber, streamId, strerror(-res), res);
2727 }
2728 break;
2729 default: // Bi-direcitonal stream is deprecated
2730 ALOGE("%s: stream %d has unknown stream type %d",
2731 __FUNCTION__, streamId, halStream->stream_type);
2732 break;
2733 }
2734 break;
2735 }
2736 }
2737 if (streamDeleted) {
2738 continue;
2739 }
2740
2741 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002742 if (streamId == inputStreamId) {
2743 streamBuffer.stream = mInputStream->asHalStream();
2744 res = mInputStream->returnInputBuffer(streamBuffer);
2745 if (res != OK) {
2746 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002747 " stream %d: %s (%d)", __FUNCTION__,
2748 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002749 }
2750 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002751 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2752 if (idx == NAME_NOT_FOUND) {
2753 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2754 continue;
2755 }
2756 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002757 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2758 }
2759 }
2760}
2761
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002762void Camera3Device::insertResultLocked(CaptureResult *result,
2763 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002764 if (result == nullptr) return;
2765
Emilian Peev71c73a22017-03-21 16:35:51 +00002766 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2767 result->mMetadata.getAndLock());
2768 set_camera_metadata_vendor_id(meta, mVendorTagId);
2769 result->mMetadata.unlock(meta);
2770
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002771 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2772 (int32_t*)&frameNumber, 1) != OK) {
2773 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2774 return;
2775 }
2776
2777 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2778 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2779 return;
2780 }
2781
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002782 // Valid result, insert into queue
2783 List<CaptureResult>::iterator queuedResult =
2784 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2785 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2786 ", burstId = %" PRId32, __FUNCTION__,
2787 queuedResult->mResultExtras.requestId,
2788 queuedResult->mResultExtras.frameNumber,
2789 queuedResult->mResultExtras.burstId);
2790
2791 mResultSignal.signal();
2792}
2793
2794
2795void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002796 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002797 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002798 Mutex::Autolock l(mOutputLock);
2799
2800 CaptureResult captureResult;
2801 captureResult.mResultExtras = resultExtras;
2802 captureResult.mMetadata = partialResult;
2803
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002804 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002805}
2806
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002807
2808void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2809 CaptureResultExtras &resultExtras,
2810 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002811 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002812 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002813 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002814 if (pendingMetadata.isEmpty())
2815 return;
2816
2817 Mutex::Autolock l(mOutputLock);
2818
2819 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002820 if (reprocess) {
2821 if (frameNumber < mNextReprocessResultFrameNumber) {
2822 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002823 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002824 frameNumber, mNextReprocessResultFrameNumber);
2825 return;
2826 }
2827 mNextReprocessResultFrameNumber = frameNumber + 1;
2828 } else {
2829 if (frameNumber < mNextResultFrameNumber) {
2830 SET_ERR("Out-of-order capture result metadata submitted! "
2831 "(got frame number %d, expecting %d)",
2832 frameNumber, mNextResultFrameNumber);
2833 return;
2834 }
2835 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002836 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002837
2838 CaptureResult captureResult;
2839 captureResult.mResultExtras = resultExtras;
2840 captureResult.mMetadata = pendingMetadata;
2841
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002842 // Append any previous partials to form a complete result
2843 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2844 captureResult.mMetadata.append(collectedPartialResult);
2845 }
2846
2847 captureResult.mMetadata.sort();
2848
2849 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002850 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2851 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002852 SET_ERR("No timestamp provided by HAL for frame %d!",
2853 frameNumber);
2854 return;
2855 }
2856
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002857 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2858 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2859
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002860 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002861}
2862
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002863/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002864 * Camera HAL device callback methods
2865 */
2866
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002867void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002868 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002869
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002870 status_t res;
2871
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002872 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002873 if (result->result == NULL && result->num_output_buffers == 0 &&
2874 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002875 SET_ERR("No result data provided by HAL for frame %d",
2876 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002877 return;
2878 }
Zhijun He204e3292014-07-14 17:09:23 -07002879
Zhijun He204e3292014-07-14 17:09:23 -07002880 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002881 result->result != NULL &&
2882 result->partial_result != 1) {
2883 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2884 " if partial result is not supported",
2885 frameNumber, result->partial_result);
2886 return;
2887 }
2888
2889 bool isPartialResult = false;
2890 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002891 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002892 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002893
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002894 // Get shutter timestamp and resultExtras from list of in-flight requests,
2895 // where it was added by the shutter notification for this frame. If the
2896 // shutter timestamp isn't received yet, append the output buffers to the
2897 // in-flight request and they will be returned when the shutter timestamp
2898 // arrives. Update the in-flight status and remove the in-flight entry if
2899 // all result data and shutter timestamp have been received.
2900 nsecs_t shutterTimestamp = 0;
2901
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002902 {
2903 Mutex::Autolock l(mInFlightLock);
2904 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2905 if (idx == NAME_NOT_FOUND) {
2906 SET_ERR("Unknown frame number for capture result: %d",
2907 frameNumber);
2908 return;
2909 }
2910 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002911 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2912 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002913 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002914 __FUNCTION__, request.resultExtras.requestId,
2915 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002916 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002917 // Always update the partial count to the latest one if it's not 0
2918 // (buffers only). When framework aggregates adjacent partial results
2919 // into one, the latest partial count will be used.
2920 if (result->partial_result != 0)
2921 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002922
2923 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002924 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002925 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2926 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2927 " the range of [1, %d] when metadata is included in the result",
2928 frameNumber, result->partial_result, mNumPartialResults);
2929 return;
2930 }
2931 isPartialResult = (result->partial_result < mNumPartialResults);
2932 if (isPartialResult) {
2933 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002934 }
2935
Shuzhen Wang4a472662017-02-26 23:29:04 -08002936 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002937 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002938 sendPartialCaptureResult(result->result, request.resultExtras,
2939 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002940 }
2941 }
2942
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002943 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002944 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002945
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002946 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002947 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002948 if (request.haveResultMetadata) {
2949 SET_ERR("Called multiple times with metadata for frame %d",
2950 frameNumber);
2951 return;
2952 }
Zhijun He204e3292014-07-14 17:09:23 -07002953 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002954 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002955 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002956 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002957 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002958 request.haveResultMetadata = true;
2959 }
2960
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002961 uint32_t numBuffersReturned = result->num_output_buffers;
2962 if (result->input_buffer != NULL) {
2963 if (hasInputBufferInRequest) {
2964 numBuffersReturned += 1;
2965 } else {
2966 ALOGW("%s: Input buffer should be NULL if there is no input"
2967 " buffer sent in the request",
2968 __FUNCTION__);
2969 }
2970 }
2971 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002972 if (request.numBuffersLeft < 0) {
2973 SET_ERR("Too many buffers returned for frame %d",
2974 frameNumber);
2975 return;
2976 }
2977
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002978 camera_metadata_ro_entry_t entry;
2979 res = find_camera_metadata_ro_entry(result->result,
2980 ANDROID_SENSOR_TIMESTAMP, &entry);
2981 if (res == OK && entry.count == 1) {
2982 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002983 }
2984
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002985 // If shutter event isn't received yet, append the output buffers to
2986 // the in-flight request. Otherwise, return the output buffers to
2987 // streams.
2988 if (shutterTimestamp == 0) {
2989 request.pendingOutputBuffers.appendArray(result->output_buffers,
2990 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002991 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002992 returnOutputBuffers(result->output_buffers,
2993 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002994 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002995
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002996 if (result->result != NULL && !isPartialResult) {
2997 if (shutterTimestamp == 0) {
2998 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002999 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003000 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003001 CameraMetadata metadata;
3002 metadata = result->result;
3003 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003004 collectedPartialResult, frameNumber,
3005 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003006 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003007 }
3008
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003009 removeInFlightRequestIfReadyLocked(idx);
3010 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003011
Zhijun Hef0d962a2014-06-30 10:24:11 -07003012 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003013 if (hasInputBufferInRequest) {
3014 Camera3Stream *stream =
3015 Camera3Stream::cast(result->input_buffer->stream);
3016 res = stream->returnInputBuffer(*(result->input_buffer));
3017 // Note: stream may be deallocated at this point, if this buffer was the
3018 // last reference to it.
3019 if (res != OK) {
3020 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3021 " its stream:%s (%d)", __FUNCTION__,
3022 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003023 }
3024 } else {
3025 ALOGW("%s: Input buffer should be NULL if there is no input"
3026 " buffer sent in the request, skipping input buffer return.",
3027 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003028 }
3029 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003030}
3031
3032void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003033 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003034 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003035 {
3036 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003037 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003038 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003039
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003040 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003041 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003042 return;
3043 }
3044
3045 switch (msg->type) {
3046 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003047 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003048 break;
3049 }
3050 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003051 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003052 break;
3053 }
3054 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003055 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003056 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003057 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003058}
3059
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003060void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003061 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003062 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003063 // Map camera HAL error codes to ICameraDeviceCallback error codes
3064 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003066 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003067 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003068 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003069 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003070 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003072 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003073 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003074 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003075 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003076 };
3077
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003078 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003079 ((msg.error_code >= 0) &&
3080 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3081 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003083
3084 int streamId = 0;
3085 if (msg.error_stream != NULL) {
3086 Camera3Stream *stream =
3087 Camera3Stream::cast(msg.error_stream);
3088 streamId = stream->getId();
3089 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003090 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3091 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003092 streamId, msg.error_code);
3093
3094 CaptureResultExtras resultExtras;
3095 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003096 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003097 // SET_ERR calls notifyError
3098 SET_ERR("Camera HAL reported serious device error");
3099 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003100 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3101 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3102 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003103 {
3104 Mutex::Autolock l(mInFlightLock);
3105 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3106 if (idx >= 0) {
3107 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3108 r.requestStatus = msg.error_code;
3109 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003110 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3111 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3112 errorCode) {
3113 r.skipResultMetadata = true;
3114 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003115 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3116 errorCode) {
3117 // In case of missing result check whether the buffers
3118 // returned. If they returned, then remove inflight
3119 // request.
3120 removeInFlightRequestIfReadyLocked(idx);
3121 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003122 } else {
3123 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003124 ALOGE("Camera %s: %s: cannot find in-flight request on "
3125 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003126 resultExtras.frameNumber);
3127 }
3128 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003129 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003130 if (listener != NULL) {
3131 listener->notifyError(errorCode, resultExtras);
3132 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003134 }
3135 break;
3136 default:
3137 // SET_ERR calls notifyError
3138 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3139 break;
3140 }
3141}
3142
3143void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003144 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003145 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003146 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003147
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003148 // Set timestamp for the request in the in-flight tracking
3149 // and get the request ID to send upstream
3150 {
3151 Mutex::Autolock l(mInFlightLock);
3152 idx = mInFlightMap.indexOfKey(msg.frame_number);
3153 if (idx >= 0) {
3154 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003155
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003156 // Verify ordering of shutter notifications
3157 {
3158 Mutex::Autolock l(mOutputLock);
3159 // TODO: need to track errors for tighter bounds on expected frame number.
3160 if (r.hasInputBuffer) {
3161 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3162 SET_ERR("Shutter notification out-of-order. Expected "
3163 "notification for frame %d, got frame %d",
3164 mNextReprocessShutterFrameNumber, msg.frame_number);
3165 return;
3166 }
3167 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3168 } else {
3169 if (msg.frame_number < mNextShutterFrameNumber) {
3170 SET_ERR("Shutter notification out-of-order. Expected "
3171 "notification for frame %d, got frame %d",
3172 mNextShutterFrameNumber, msg.frame_number);
3173 return;
3174 }
3175 mNextShutterFrameNumber = msg.frame_number + 1;
3176 }
3177 }
3178
Shuzhen Wang4a472662017-02-26 23:29:04 -08003179 r.shutterTimestamp = msg.timestamp;
3180 if (r.hasCallback) {
3181 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003182 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003183 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003184 // Call listener, if any
3185 if (listener != NULL) {
3186 listener->notifyShutter(r.resultExtras, msg.timestamp);
3187 }
3188 // send pending result and buffers
3189 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3190 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003191 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003192 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003193 returnOutputBuffers(r.pendingOutputBuffers.array(),
3194 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3195 r.pendingOutputBuffers.clear();
3196
3197 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003198 }
3199 }
3200 if (idx < 0) {
3201 SET_ERR("Shutter notification for non-existent frame number %d",
3202 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003203 }
3204}
3205
3206
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003207CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003208 ALOGV("%s", __FUNCTION__);
3209
Igor Murashkin1e479c02013-09-06 16:55:14 -07003210 CameraMetadata retVal;
3211
3212 if (mRequestThread != NULL) {
3213 retVal = mRequestThread->getLatestRequest();
3214 }
3215
Igor Murashkin1e479c02013-09-06 16:55:14 -07003216 return retVal;
3217}
3218
Jianing Weicb0652e2014-03-12 18:29:36 -07003219
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003220void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3221 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3222 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3223}
3224
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003225/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003226 * HalInterface inner class methods
3227 */
3228
Yifan Hongf79b5542017-04-11 14:44:25 -07003229Camera3Device::HalInterface::HalInterface(
3230 sp<ICameraDeviceSession> &session,
3231 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003232 mHidlSession(session),
3233 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003234
Emilian Peev31abd0a2017-05-11 18:37:46 +01003235Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003236
3237Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003238 mHidlSession(other.mHidlSession),
3239 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003240
3241bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003242 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003243}
3244
3245void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003246 mHidlSession.clear();
3247}
3248
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003249bool Camera3Device::HalInterface::supportBatchRequest() {
3250 return mHidlSession != nullptr;
3251}
3252
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003253status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3254 camera3_request_template_t templateId,
3255 /*out*/ camera_metadata_t **requestTemplate) {
3256 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3257 if (!valid()) return INVALID_OPERATION;
3258 status_t res = OK;
3259
Emilian Peev31abd0a2017-05-11 18:37:46 +01003260 common::V1_0::Status status;
3261 RequestTemplate id;
3262 switch (templateId) {
3263 case CAMERA3_TEMPLATE_PREVIEW:
3264 id = RequestTemplate::PREVIEW;
3265 break;
3266 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3267 id = RequestTemplate::STILL_CAPTURE;
3268 break;
3269 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3270 id = RequestTemplate::VIDEO_RECORD;
3271 break;
3272 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3273 id = RequestTemplate::VIDEO_SNAPSHOT;
3274 break;
3275 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3276 id = RequestTemplate::ZERO_SHUTTER_LAG;
3277 break;
3278 case CAMERA3_TEMPLATE_MANUAL:
3279 id = RequestTemplate::MANUAL;
3280 break;
3281 default:
3282 // Unknown template ID
3283 return BAD_VALUE;
3284 }
3285 auto err = mHidlSession->constructDefaultRequestSettings(id,
3286 [&status, &requestTemplate]
3287 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3288 status = s;
3289 if (status == common::V1_0::Status::OK) {
3290 const camera_metadata *r =
3291 reinterpret_cast<const camera_metadata_t*>(request.data());
3292 size_t expectedSize = request.size();
3293 int ret = validate_camera_metadata_structure(r, &expectedSize);
3294 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3295 *requestTemplate = clone_camera_metadata(r);
3296 if (*requestTemplate == nullptr) {
3297 ALOGE("%s: Unable to clone camera metadata received from HAL",
3298 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003299 status = common::V1_0::Status::INTERNAL_ERROR;
3300 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003301 } else {
3302 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3303 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003304 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003305 }
3306 });
3307 if (!err.isOk()) {
3308 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3309 res = DEAD_OBJECT;
3310 } else {
3311 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003312 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003314 return res;
3315}
3316
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003317status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
3318 camera3_stream_configuration *config) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003319 ATRACE_NAME("CameraHal::configureStreams");
3320 if (!valid()) return INVALID_OPERATION;
3321 status_t res = OK;
3322
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 // Convert stream config to HIDL
3324 std::set<int> activeStreams;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003325 device::V3_4::StreamConfiguration requestedConfiguration;
3326 requestedConfiguration.v3_2.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003327 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003328 Stream &dst = requestedConfiguration.v3_2.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003329 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003330
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3332 cam3stream->setBufferFreedListener(this);
3333 int streamId = cam3stream->getId();
3334 StreamType streamType;
3335 switch (src->stream_type) {
3336 case CAMERA3_STREAM_OUTPUT:
3337 streamType = StreamType::OUTPUT;
3338 break;
3339 case CAMERA3_STREAM_INPUT:
3340 streamType = StreamType::INPUT;
3341 break;
3342 default:
3343 ALOGE("%s: Stream %d: Unsupported stream type %d",
3344 __FUNCTION__, streamId, config->streams[i]->stream_type);
3345 return BAD_VALUE;
3346 }
3347 dst.id = streamId;
3348 dst.streamType = streamType;
3349 dst.width = src->width;
3350 dst.height = src->height;
3351 dst.format = mapToPixelFormat(src->format);
Emilian Peev050f5dc2017-05-18 14:43:56 +01003352 dst.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peev31abd0a2017-05-11 18:37:46 +01003353 dst.dataSpace = mapToHidlDataspace(src->data_space);
3354 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3355
3356 activeStreams.insert(streamId);
3357 // Create Buffer ID map if necessary
3358 if (mBufferIdMaps.count(streamId) == 0) {
3359 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3360 }
3361 }
3362 // remove BufferIdMap for deleted streams
3363 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3364 int streamId = it->first;
3365 bool active = activeStreams.count(streamId) > 0;
3366 if (!active) {
3367 it = mBufferIdMaps.erase(it);
3368 } else {
3369 ++it;
3370 }
3371 }
3372
3373 res = mapToStreamConfigurationMode(
3374 (camera3_stream_configuration_mode_t) config->operation_mode,
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003375 /*out*/ &requestedConfiguration.v3_2.operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003376 if (res != OK) {
3377 return res;
3378 }
3379
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003380 requestedConfiguration.sessionParams.setToExternal(
3381 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3382 get_camera_metadata_size(sessionParams));
3383
Emilian Peev31abd0a2017-05-11 18:37:46 +01003384 // Invoke configureStreams
3385
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003386 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003387 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003388
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003389 // See if we have v3.4 or v3.3 HAL
3390 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003391 sp<device::V3_3::ICameraDeviceSession> hidlSession_3_3;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003392 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3393 if (castResult_3_4.isOk()) {
3394 hidlSession_3_4 = castResult_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003395 } else {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003396 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3397 if (castResult_3_3.isOk()) {
3398 hidlSession_3_3 = castResult_3_3;
3399 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003400 }
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003401
3402 if (hidlSession_3_4 != nullptr) {
3403 // We do; use v3.4 for the call
3404 ALOGV("%s: v3.4 device found", __FUNCTION__);
3405 auto err = hidlSession_3_4->configureStreams_3_4(requestedConfiguration,
3406 [&status, &finalConfiguration]
3407 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
3408 finalConfiguration = halConfiguration;
3409 status = s;
3410 });
3411 if (!err.isOk()) {
3412 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3413 return DEAD_OBJECT;
3414 }
3415 } else if (hidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003416 // We do; use v3.3 for the call
3417 ALOGV("%s: v3.3 device found", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003418 auto err = hidlSession_3_3->configureStreams_3_3(requestedConfiguration.v3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003419 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003420 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003421 finalConfiguration = halConfiguration;
3422 status = s;
3423 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003424 if (!err.isOk()) {
3425 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3426 return DEAD_OBJECT;
3427 }
3428 } else {
3429 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3430 ALOGV("%s: v3.2 device found", __FUNCTION__);
3431 HalStreamConfiguration finalConfiguration_3_2;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003432 auto err = mHidlSession->configureStreams(requestedConfiguration.v3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003433 [&status, &finalConfiguration_3_2]
3434 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3435 finalConfiguration_3_2 = halConfiguration;
3436 status = s;
3437 });
3438 if (!err.isOk()) {
3439 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3440 return DEAD_OBJECT;
3441 }
3442 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3443 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3444 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3445 finalConfiguration.streams[i].overrideDataSpace =
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003446 requestedConfiguration.v3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003447 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003448 }
3449
3450 if (status != common::V1_0::Status::OK ) {
3451 return CameraProviderManager::mapToStatusT(status);
3452 }
3453
3454 // And convert output stream configuration from HIDL
3455
3456 for (size_t i = 0; i < config->num_streams; i++) {
3457 camera3_stream_t *dst = config->streams[i];
3458 int streamId = Camera3Stream::cast(dst)->getId();
3459
3460 // Start scan at i, with the assumption that the stream order matches
3461 size_t realIdx = i;
3462 bool found = false;
3463 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003464 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003465 found = true;
3466 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003467 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003468 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3469 }
3470 if (!found) {
3471 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3472 __FUNCTION__, streamId);
3473 return INVALID_OPERATION;
3474 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003475 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003476
Emilian Peev710c1422017-08-30 11:19:38 +01003477 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3478 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003479 dstStream->setDataSpaceOverride(false);
3480 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3481 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3482
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3484 if (dst->format != overrideFormat) {
3485 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3486 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003487 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003488 if (dst->data_space != overrideDataSpace) {
3489 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3490 streamId, dst->format);
3491 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003492 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003493 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003494 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3495
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 // Override allowed with IMPLEMENTATION_DEFINED
3497 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003498 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003499 }
3500
Emilian Peev31abd0a2017-05-11 18:37:46 +01003501 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003502 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003503 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003504 __FUNCTION__, streamId);
3505 return INVALID_OPERATION;
3506 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003507 dstStream->setUsage(
3508 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003509 } else {
3510 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003511 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003512 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3513 __FUNCTION__, streamId);
3514 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003515 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003516 dstStream->setUsage(
3517 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003518 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003519 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003520 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003521
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003522 return res;
3523}
3524
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003525void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3526 /*out*/device::V3_2::CaptureRequest* captureRequest,
3527 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003528 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003529 if (captureRequest == nullptr || handlesCreated == nullptr) {
3530 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3531 __FUNCTION__, captureRequest, handlesCreated);
3532 return;
3533 }
3534
3535 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003536
3537 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003538
3539 {
3540 std::lock_guard<std::mutex> lock(mInflightLock);
3541 if (request->input_buffer != nullptr) {
3542 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3543 buffer_handle_t buf = *(request->input_buffer->buffer);
3544 auto pair = getBufferId(buf, streamId);
3545 bool isNewBuffer = pair.first;
3546 uint64_t bufferId = pair.second;
3547 captureRequest->inputBuffer.streamId = streamId;
3548 captureRequest->inputBuffer.bufferId = bufferId;
3549 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3550 captureRequest->inputBuffer.status = BufferStatus::OK;
3551 native_handle_t *acquireFence = nullptr;
3552 if (request->input_buffer->acquire_fence != -1) {
3553 acquireFence = native_handle_create(1,0);
3554 acquireFence->data[0] = request->input_buffer->acquire_fence;
3555 handlesCreated->push_back(acquireFence);
3556 }
3557 captureRequest->inputBuffer.acquireFence = acquireFence;
3558 captureRequest->inputBuffer.releaseFence = nullptr;
3559
3560 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3561 request->input_buffer->buffer,
3562 request->input_buffer->acquire_fence);
3563 } else {
3564 captureRequest->inputBuffer.streamId = -1;
3565 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3566 }
3567
3568 captureRequest->outputBuffers.resize(request->num_output_buffers);
3569 for (size_t i = 0; i < request->num_output_buffers; i++) {
3570 const camera3_stream_buffer_t *src = request->output_buffers + i;
3571 StreamBuffer &dst = captureRequest->outputBuffers[i];
3572 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3573 buffer_handle_t buf = *(src->buffer);
3574 auto pair = getBufferId(buf, streamId);
3575 bool isNewBuffer = pair.first;
3576 dst.streamId = streamId;
3577 dst.bufferId = pair.second;
3578 dst.buffer = isNewBuffer ? buf : nullptr;
3579 dst.status = BufferStatus::OK;
3580 native_handle_t *acquireFence = nullptr;
3581 if (src->acquire_fence != -1) {
3582 acquireFence = native_handle_create(1,0);
3583 acquireFence->data[0] = src->acquire_fence;
3584 handlesCreated->push_back(acquireFence);
3585 }
3586 dst.acquireFence = acquireFence;
3587 dst.releaseFence = nullptr;
3588
3589 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3590 src->buffer, src->acquire_fence);
3591 }
3592 }
3593}
3594
3595status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3596 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3597 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3598 if (!valid()) return INVALID_OPERATION;
3599
3600 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3601 size_t batchSize = requests.size();
3602 captureRequests.resize(batchSize);
3603 std::vector<native_handle_t*> handlesCreated;
3604
3605 for (size_t i = 0; i < batchSize; i++) {
3606 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3607 }
3608
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003609 std::vector<device::V3_2::BufferCache> cachesToRemove;
3610 {
3611 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3612 for (auto& pair : mFreedBuffers) {
3613 // The stream might have been removed since onBufferFreed
3614 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3615 cachesToRemove.push_back({pair.first, pair.second});
3616 }
3617 }
3618 mFreedBuffers.clear();
3619 }
3620
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003621 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3622 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003623
3624 // Write metadata to FMQ.
3625 for (size_t i = 0; i < batchSize; i++) {
3626 camera3_capture_request_t* request = requests[i];
3627 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3628
3629 if (request->settings != nullptr) {
3630 size_t settingsSize = get_camera_metadata_size(request->settings);
3631 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3632 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3633 captureRequest->settings.resize(0);
3634 captureRequest->fmqSettingsSize = settingsSize;
3635 } else {
3636 if (mRequestMetadataQueue != nullptr) {
3637 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3638 }
3639 captureRequest->settings.setToExternal(
3640 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3641 get_camera_metadata_size(request->settings));
3642 captureRequest->fmqSettingsSize = 0u;
3643 }
3644 } else {
3645 // A null request settings maps to a size-0 CameraMetadata
3646 captureRequest->settings.resize(0);
3647 captureRequest->fmqSettingsSize = 0u;
3648 }
3649 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003650 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003651 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3652 status = s;
3653 *numRequestProcessed = n;
3654 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003655 if (!err.isOk()) {
3656 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3657 return DEAD_OBJECT;
3658 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003659 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3660 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3661 __FUNCTION__, *numRequestProcessed, batchSize);
3662 status = common::V1_0::Status::INTERNAL_ERROR;
3663 }
3664
3665 for (auto& handle : handlesCreated) {
3666 native_handle_delete(handle);
3667 }
3668 return CameraProviderManager::mapToStatusT(status);
3669}
3670
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003671status_t Camera3Device::HalInterface::processCaptureRequest(
3672 camera3_capture_request_t *request) {
3673 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003674 if (!valid()) return INVALID_OPERATION;
3675 status_t res = OK;
3676
Emilian Peev31abd0a2017-05-11 18:37:46 +01003677 uint32_t numRequestProcessed = 0;
3678 std::vector<camera3_capture_request_t*> requests(1);
3679 requests[0] = request;
3680 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3681
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003682 return res;
3683}
3684
3685status_t Camera3Device::HalInterface::flush() {
3686 ATRACE_NAME("CameraHal::flush");
3687 if (!valid()) return INVALID_OPERATION;
3688 status_t res = OK;
3689
Emilian Peev31abd0a2017-05-11 18:37:46 +01003690 auto err = mHidlSession->flush();
3691 if (!err.isOk()) {
3692 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3693 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003694 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003695 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003696 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003697
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003698 return res;
3699}
3700
Emilian Peev31abd0a2017-05-11 18:37:46 +01003701status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003702 ATRACE_NAME("CameraHal::dump");
3703 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003704
Emilian Peev31abd0a2017-05-11 18:37:46 +01003705 // Handled by CameraProviderManager::dump
3706
3707 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003708}
3709
3710status_t Camera3Device::HalInterface::close() {
3711 ATRACE_NAME("CameraHal::close()");
3712 if (!valid()) return INVALID_OPERATION;
3713 status_t res = OK;
3714
Emilian Peev31abd0a2017-05-11 18:37:46 +01003715 auto err = mHidlSession->close();
3716 // Interface will be dead shortly anyway, so don't log errors
3717 if (!err.isOk()) {
3718 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003719 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003720
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003721 return res;
3722}
3723
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003724void Camera3Device::HalInterface::getInflightBufferKeys(
3725 std::vector<std::pair<int32_t, int32_t>>* out) {
3726 std::lock_guard<std::mutex> lock(mInflightLock);
3727 out->clear();
3728 out->reserve(mInflightBufferMap.size());
3729 for (auto& pair : mInflightBufferMap) {
3730 uint64_t key = pair.first;
3731 int32_t streamId = key & 0xFFFFFFFF;
3732 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3733 out->push_back(std::make_pair(frameNumber, streamId));
3734 }
3735 return;
3736}
3737
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003738status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003739 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003740 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003741 auto pair = std::make_pair(buffer, acquireFence);
3742 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003743 return OK;
3744}
3745
3746status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003747 int32_t frameNumber, int32_t streamId,
3748 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003749 std::lock_guard<std::mutex> lock(mInflightLock);
3750
3751 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3752 auto it = mInflightBufferMap.find(key);
3753 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003754 auto pair = it->second;
3755 *buffer = pair.first;
3756 int acquireFence = pair.second;
3757 if (acquireFence > 0) {
3758 ::close(acquireFence);
3759 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003760 mInflightBufferMap.erase(it);
3761 return OK;
3762}
3763
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003764std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3765 const buffer_handle_t& buf, int streamId) {
3766 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3767
3768 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3769 auto it = bIdMap.find(buf);
3770 if (it == bIdMap.end()) {
3771 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003772 ALOGV("stream %d now have %zu buffer caches, buf %p",
3773 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003774 return std::make_pair(true, mNextBufferId - 1);
3775 } else {
3776 return std::make_pair(false, it->second);
3777 }
3778}
3779
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003780void Camera3Device::HalInterface::onBufferFreed(
3781 int streamId, const native_handle_t* handle) {
3782 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3783 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3784 auto mapIt = mBufferIdMaps.find(streamId);
3785 if (mapIt == mBufferIdMaps.end()) {
3786 // streamId might be from a deleted stream here
3787 ALOGI("%s: stream %d has been removed",
3788 __FUNCTION__, streamId);
3789 return;
3790 }
3791 BufferIdMap& bIdMap = mapIt->second;
3792 auto it = bIdMap.find(handle);
3793 if (it == bIdMap.end()) {
3794 ALOGW("%s: cannot find buffer %p in stream %d",
3795 __FUNCTION__, handle, streamId);
3796 return;
3797 } else {
3798 bufferId = it->second;
3799 bIdMap.erase(it);
3800 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3801 __FUNCTION__, streamId, bIdMap.size(), handle);
3802 }
3803 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3804}
3805
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003806/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003807 * RequestThread inner class methods
3808 */
3809
3810Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003811 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003812 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003813 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003814 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003815 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003816 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003817 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003818 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003819 mReconfigured(false),
3820 mDoPause(false),
3821 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003822 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003823 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003824 mCurrentAfTriggerId(0),
3825 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003826 mRepeatingLastFrameNumber(
3827 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003828 mPrepareVideoStream(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003829 mRequestLatency(kRequestLatencyBinSize),
3830 mSessionParamKeys(sessionParamKeys),
3831 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003832 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003833}
3834
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003835Camera3Device::RequestThread::~RequestThread() {}
3836
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003837void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003838 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003839 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003840 Mutex::Autolock l(mRequestLock);
3841 mListener = listener;
3842}
3843
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003844void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3845 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003846 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003847 Mutex::Autolock l(mRequestLock);
3848 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003849 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003850 // Prepare video stream for high speed recording.
3851 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003852}
3853
Jianing Wei90e59c92014-03-12 18:29:36 -07003854status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003855 List<sp<CaptureRequest> > &requests,
3856 /*out*/
3857 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003858 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003859 Mutex::Autolock l(mRequestLock);
3860 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3861 ++it) {
3862 mRequestQueue.push_back(*it);
3863 }
3864
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003865 if (lastFrameNumber != NULL) {
3866 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3867 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3868 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3869 *lastFrameNumber);
3870 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003871
Jianing Wei90e59c92014-03-12 18:29:36 -07003872 unpauseForNewRequests();
3873
3874 return OK;
3875}
3876
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003877
3878status_t Camera3Device::RequestThread::queueTrigger(
3879 RequestTrigger trigger[],
3880 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003881 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003882 Mutex::Autolock l(mTriggerMutex);
3883 status_t ret;
3884
3885 for (size_t i = 0; i < count; ++i) {
3886 ret = queueTriggerLocked(trigger[i]);
3887
3888 if (ret != OK) {
3889 return ret;
3890 }
3891 }
3892
3893 return OK;
3894}
3895
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003896const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3897 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003898 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003899 if (d != nullptr) return d->mId;
3900 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003901}
3902
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003903status_t Camera3Device::RequestThread::queueTriggerLocked(
3904 RequestTrigger trigger) {
3905
3906 uint32_t tag = trigger.metadataTag;
3907 ssize_t index = mTriggerMap.indexOfKey(tag);
3908
3909 switch (trigger.getTagType()) {
3910 case TYPE_BYTE:
3911 // fall-through
3912 case TYPE_INT32:
3913 break;
3914 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003915 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3916 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003917 return INVALID_OPERATION;
3918 }
3919
3920 /**
3921 * Collect only the latest trigger, since we only have 1 field
3922 * in the request settings per trigger tag, and can't send more than 1
3923 * trigger per request.
3924 */
3925 if (index != NAME_NOT_FOUND) {
3926 mTriggerMap.editValueAt(index) = trigger;
3927 } else {
3928 mTriggerMap.add(tag, trigger);
3929 }
3930
3931 return OK;
3932}
3933
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003934status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003935 const RequestList &requests,
3936 /*out*/
3937 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003938 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003939 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003940 if (lastFrameNumber != NULL) {
3941 *lastFrameNumber = mRepeatingLastFrameNumber;
3942 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003943 mRepeatingRequests.clear();
3944 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3945 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003946
3947 unpauseForNewRequests();
3948
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003949 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003950 return OK;
3951}
3952
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003953bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003954 if (mRepeatingRequests.empty()) {
3955 return false;
3956 }
3957 int32_t requestId = requestIn->mResultExtras.requestId;
3958 const RequestList &repeatRequests = mRepeatingRequests;
3959 // All repeating requests are guaranteed to have same id so only check first quest
3960 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3961 return (firstRequest->mResultExtras.requestId == requestId);
3962}
3963
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003964status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003965 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003966 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003967 return clearRepeatingRequestsLocked(lastFrameNumber);
3968
3969}
3970
3971status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003972 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003973 if (lastFrameNumber != NULL) {
3974 *lastFrameNumber = mRepeatingLastFrameNumber;
3975 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003976 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003977 return OK;
3978}
3979
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003980status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003981 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003982 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003983 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003984 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003985
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003986 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003987
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003988 // Send errors for all requests pending in the request queue, including
3989 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003990 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003991 if (listener != NULL) {
3992 for (RequestList::iterator it = mRequestQueue.begin();
3993 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003994 // Abort the input buffers for reprocess requests.
3995 if ((*it)->mInputStream != NULL) {
3996 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003997 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3998 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003999 if (res != OK) {
4000 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4001 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4002 } else {
4003 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4004 if (res != OK) {
4005 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4006 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4007 }
4008 }
4009 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004010 // Set the frame number this request would have had, if it
4011 // had been submitted; this frame number will not be reused.
4012 // The requestId and burstId fields were set when the request was
4013 // submitted originally (in convertMetadataListToRequestListLocked)
4014 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004015 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004016 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004017 }
4018 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004019 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004020
4021 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004022 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004023 if (lastFrameNumber != NULL) {
4024 *lastFrameNumber = mRepeatingLastFrameNumber;
4025 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004026 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004027 return OK;
4028}
4029
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004030status_t Camera3Device::RequestThread::flush() {
4031 ATRACE_CALL();
4032 Mutex::Autolock l(mFlushLock);
4033
Emilian Peev08dd2452017-04-06 16:55:14 +01004034 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004035}
4036
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004037void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004038 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004039 Mutex::Autolock l(mPauseLock);
4040 mDoPause = paused;
4041 mDoPauseSignal.signal();
4042}
4043
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004044status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4045 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004046 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004047 Mutex::Autolock l(mLatestRequestMutex);
4048 status_t res;
4049 while (mLatestRequestId != requestId) {
4050 nsecs_t startTime = systemTime();
4051
4052 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4053 if (res != OK) return res;
4054
4055 timeout -= (systemTime() - startTime);
4056 }
4057
4058 return OK;
4059}
4060
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004061void Camera3Device::RequestThread::requestExit() {
4062 // Call parent to set up shutdown
4063 Thread::requestExit();
4064 // The exit from any possible waits
4065 mDoPauseSignal.signal();
4066 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004067
4068 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4069 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004070}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004071
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004072void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004073 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004074 bool surfaceAbandoned = false;
4075 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004076 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004077 {
4078 Mutex::Autolock l(mRequestLock);
4079 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4080 // repeating requests.
4081 for (const auto& request : mRepeatingRequests) {
4082 for (const auto& s : request->mOutputStreams) {
4083 if (s->isAbandoned()) {
4084 surfaceAbandoned = true;
4085 clearRepeatingRequestsLocked(&lastFrameNumber);
4086 break;
4087 }
4088 }
4089 if (surfaceAbandoned) {
4090 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004091 }
4092 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004093 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004094 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004095
4096 if (listener != NULL && surfaceAbandoned) {
4097 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004098 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004099}
4100
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004101bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004102 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004103 status_t res;
4104 size_t batchSize = mNextRequests.size();
4105 std::vector<camera3_capture_request_t*> requests(batchSize);
4106 uint32_t numRequestProcessed = 0;
4107 for (size_t i = 0; i < batchSize; i++) {
4108 requests[i] = &mNextRequests.editItemAt(i).halRequest;
4109 }
4110
4111 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
4112 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4113
4114 bool triggerRemoveFailed = false;
4115 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4116 for (size_t i = 0; i < numRequestProcessed; i++) {
4117 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4118 nextRequest.submitted = true;
4119
4120
4121 // Update the latest request sent to HAL
4122 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4123 Mutex::Autolock al(mLatestRequestMutex);
4124
4125 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4126 mLatestRequest.acquire(cloned);
4127
4128 sp<Camera3Device> parent = mParent.promote();
4129 if (parent != NULL) {
4130 parent->monitorMetadata(TagMonitor::REQUEST,
4131 nextRequest.halRequest.frame_number,
4132 0, mLatestRequest);
4133 }
4134 }
4135
4136 if (nextRequest.halRequest.settings != NULL) {
4137 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4138 }
4139
4140 if (!triggerRemoveFailed) {
4141 // Remove any previously queued triggers (after unlock)
4142 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4143 if (removeTriggerRes != OK) {
4144 triggerRemoveFailed = true;
4145 triggerFailedRequest = nextRequest;
4146 }
4147 }
4148 }
4149
4150 if (triggerRemoveFailed) {
4151 SET_ERR("RequestThread: Unable to remove triggers "
4152 "(capture request %d, HAL device: %s (%d)",
4153 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4154 cleanUpFailedRequests(/*sendRequestError*/ false);
4155 return false;
4156 }
4157
4158 if (res != OK) {
4159 // Should only get a failure here for malformed requests or device-level
4160 // errors, so consider all errors fatal. Bad metadata failures should
4161 // come through notify.
4162 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4163 mNextRequests[numRequestProcessed].halRequest.frame_number,
4164 strerror(-res), res);
4165 cleanUpFailedRequests(/*sendRequestError*/ false);
4166 return false;
4167 }
4168 return true;
4169}
4170
4171bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4172 status_t res;
4173
4174 for (auto& nextRequest : mNextRequests) {
4175 // Submit request and block until ready for next one
4176 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4177 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4178
4179 if (res != OK) {
4180 // Should only get a failure here for malformed requests or device-level
4181 // errors, so consider all errors fatal. Bad metadata failures should
4182 // come through notify.
4183 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4184 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4185 res);
4186 cleanUpFailedRequests(/*sendRequestError*/ false);
4187 return false;
4188 }
4189
4190 // Mark that the request has be submitted successfully.
4191 nextRequest.submitted = true;
4192
4193 // Update the latest request sent to HAL
4194 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4195 Mutex::Autolock al(mLatestRequestMutex);
4196
4197 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4198 mLatestRequest.acquire(cloned);
4199
4200 sp<Camera3Device> parent = mParent.promote();
4201 if (parent != NULL) {
4202 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4203 0, mLatestRequest);
4204 }
4205 }
4206
4207 if (nextRequest.halRequest.settings != NULL) {
4208 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4209 }
4210
4211 // Remove any previously queued triggers (after unlock)
4212 res = removeTriggers(mPrevRequest);
4213 if (res != OK) {
4214 SET_ERR("RequestThread: Unable to remove triggers "
4215 "(capture request %d, HAL device: %s (%d)",
4216 nextRequest.halRequest.frame_number, strerror(-res), res);
4217 cleanUpFailedRequests(/*sendRequestError*/ false);
4218 return false;
4219 }
4220 }
4221 return true;
4222}
4223
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004224nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4225 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4226 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4227 find_camera_metadata_ro_entry(request,
4228 ANDROID_CONTROL_AE_MODE,
4229 &e);
4230 if (e.count == 0) return maxExpectedDuration;
4231
4232 switch (e.data.u8[0]) {
4233 case ANDROID_CONTROL_AE_MODE_OFF:
4234 find_camera_metadata_ro_entry(request,
4235 ANDROID_SENSOR_EXPOSURE_TIME,
4236 &e);
4237 if (e.count > 0) {
4238 maxExpectedDuration = e.data.i64[0];
4239 }
4240 find_camera_metadata_ro_entry(request,
4241 ANDROID_SENSOR_FRAME_DURATION,
4242 &e);
4243 if (e.count > 0) {
4244 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4245 }
4246 break;
4247 default:
4248 find_camera_metadata_ro_entry(request,
4249 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4250 &e);
4251 if (e.count > 1) {
4252 maxExpectedDuration = 1e9 / e.data.u8[0];
4253 }
4254 break;
4255 }
4256
4257 return maxExpectedDuration;
4258}
4259
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004260bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4261 ATRACE_CALL();
4262 bool updatesDetected = false;
4263
4264 for (auto tag : mSessionParamKeys) {
4265 camera_metadata_ro_entry entry = settings.find(tag);
4266 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4267
4268 if (entry.count > 0) {
4269 bool isDifferent = false;
4270 if (lastEntry.count > 0) {
4271 // Have a last value, compare to see if changed
4272 if (lastEntry.type == entry.type &&
4273 lastEntry.count == entry.count) {
4274 // Same type and count, compare values
4275 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4276 size_t entryBytes = bytesPerValue * lastEntry.count;
4277 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4278 if (cmp != 0) {
4279 isDifferent = true;
4280 }
4281 } else {
4282 // Count or type has changed
4283 isDifferent = true;
4284 }
4285 } else {
4286 // No last entry, so always consider to be different
4287 isDifferent = true;
4288 }
4289
4290 if (isDifferent) {
4291 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
4292 mLatestSessionParams.update(entry);
4293 updatesDetected = true;
4294 }
4295 } else if (lastEntry.count > 0) {
4296 // Value has been removed
4297 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4298 mLatestSessionParams.erase(tag);
4299 updatesDetected = true;
4300 }
4301 }
4302
4303 return updatesDetected;
4304}
4305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004307 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004308 status_t res;
4309
4310 // Handle paused state.
4311 if (waitIfPaused()) {
4312 return true;
4313 }
4314
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004315 // Wait for the next batch of requests.
4316 waitForNextRequestBatch();
4317 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 return true;
4319 }
4320
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004321 // Get the latest request ID, if any
4322 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004323 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004324 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004325 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004326 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004327 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004328 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4329 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004330 }
4331
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004332 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4333 // or a single request from streaming or burst. In either case the first element
4334 // should contain the latest camera settings that we need to check for any session
4335 // parameter updates.
4336 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettings)) {
4337 res = OK;
4338
4339 //Input stream buffers are already acquired at this point so an input stream
4340 //will not be able to move to idle state unless we force it.
4341 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4342 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4343 if (res != OK) {
4344 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4345 cleanUpFailedRequests(/*sendRequestError*/ false);
4346 return false;
4347 }
4348 }
4349
4350 if (res == OK) {
4351 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4352 if (statusTracker != 0) {
4353 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4354
4355 sp<Camera3Device> parent = mParent.promote();
4356 if (parent != nullptr) {
4357 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4358 }
4359
4360 statusTracker->markComponentActive(mStatusId);
4361 setPaused(false);
4362 }
4363
4364 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4365 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4366 if (res != OK) {
4367 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4368 cleanUpFailedRequests(/*sendRequestError*/ false);
4369 return false;
4370 }
4371 }
4372 }
4373 }
4374
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004375 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004376 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004377 if (res == TIMED_OUT) {
4378 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004379 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004380 // Check if any stream is abandoned.
4381 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004382 return true;
4383 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004384 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004385 return false;
4386 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004387
Zhijun Hecc27e112013-10-03 16:12:43 -07004388 // Inform waitUntilRequestProcessed thread of a new request ID
4389 {
4390 Mutex::Autolock al(mLatestRequestMutex);
4391
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004392 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004393 mLatestRequestSignal.signal();
4394 }
4395
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004396 // Submit a batch of requests to HAL.
4397 // Use flush lock only when submitting multilple requests in a batch.
4398 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4399 // which may take a long time to finish so synchronizing flush() and
4400 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4401 // For now, only synchronize for high speed recording and we should figure something out for
4402 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004403 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004404
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004405 if (useFlushLock) {
4406 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004407 }
4408
Zhijun Hef0645c12016-08-02 00:58:11 -07004409 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004410 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004411
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004412 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004413 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004414 if (mInterface->supportBatchRequest()) {
4415 submitRequestSuccess = sendRequestsBatch();
4416 } else {
4417 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004418 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004419 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4420 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004421
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004422 if (useFlushLock) {
4423 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004424 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004425
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004426 // Unset as current request
4427 {
4428 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004429 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004430 }
4431
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004432 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004433}
4434
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004435status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004436 ATRACE_CALL();
4437
Shuzhen Wang4a472662017-02-26 23:29:04 -08004438 for (size_t i = 0; i < mNextRequests.size(); i++) {
4439 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004440 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4441 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4442 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4443
4444 // Prepare a request to HAL
4445 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4446
4447 // Insert any queued triggers (before metadata is locked)
4448 status_t res = insertTriggers(captureRequest);
4449
4450 if (res < 0) {
4451 SET_ERR("RequestThread: Unable to insert triggers "
4452 "(capture request %d, HAL device: %s (%d)",
4453 halRequest->frame_number, strerror(-res), res);
4454 return INVALID_OPERATION;
4455 }
4456 int triggerCount = res;
4457 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4458 mPrevTriggers = triggerCount;
4459
4460 // If the request is the same as last, or we had triggers last time
4461 if (mPrevRequest != captureRequest || triggersMixedIn) {
4462 /**
4463 * HAL workaround:
4464 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4465 */
4466 res = addDummyTriggerIds(captureRequest);
4467 if (res != OK) {
4468 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4469 "(capture request %d, HAL device: %s (%d)",
4470 halRequest->frame_number, strerror(-res), res);
4471 return INVALID_OPERATION;
4472 }
4473
4474 /**
4475 * The request should be presorted so accesses in HAL
4476 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4477 */
4478 captureRequest->mSettings.sort();
4479 halRequest->settings = captureRequest->mSettings.getAndLock();
4480 mPrevRequest = captureRequest;
4481 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4482
4483 IF_ALOGV() {
4484 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4485 find_camera_metadata_ro_entry(
4486 halRequest->settings,
4487 ANDROID_CONTROL_AF_TRIGGER,
4488 &e
4489 );
4490 if (e.count > 0) {
4491 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4492 __FUNCTION__,
4493 halRequest->frame_number,
4494 e.data.u8[0]);
4495 }
4496 }
4497 } else {
4498 // leave request.settings NULL to indicate 'reuse latest given'
4499 ALOGVV("%s: Request settings are REUSED",
4500 __FUNCTION__);
4501 }
4502
4503 uint32_t totalNumBuffers = 0;
4504
4505 // Fill in buffers
4506 if (captureRequest->mInputStream != NULL) {
4507 halRequest->input_buffer = &captureRequest->mInputBuffer;
4508 totalNumBuffers += 1;
4509 } else {
4510 halRequest->input_buffer = NULL;
4511 }
4512
4513 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4514 captureRequest->mOutputStreams.size());
4515 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004516 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4517 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004518
4519 // Prepare video buffers for high speed recording on the first video request.
4520 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4521 // Only try to prepare video stream on the first video request.
4522 mPrepareVideoStream = false;
4523
4524 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4525 while (res == NOT_ENOUGH_DATA) {
4526 res = outputStream->prepareNextBuffer();
4527 }
4528 if (res != OK) {
4529 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4530 __FUNCTION__, strerror(-res), res);
4531 outputStream->cancelPrepare();
4532 }
4533 }
4534
Shuzhen Wang4a472662017-02-26 23:29:04 -08004535 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4536 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004537 if (res != OK) {
4538 // Can't get output buffer from gralloc queue - this could be due to
4539 // abandoned queue or other consumer misbehavior, so not a fatal
4540 // error
4541 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4542 " %s (%d)", strerror(-res), res);
4543
4544 return TIMED_OUT;
4545 }
4546 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004547
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004548 }
4549 totalNumBuffers += halRequest->num_output_buffers;
4550
4551 // Log request in the in-flight queue
4552 sp<Camera3Device> parent = mParent.promote();
4553 if (parent == NULL) {
4554 // Should not happen, and nowhere to send errors to, so just log it
4555 CLOGE("RequestThread: Parent is gone");
4556 return INVALID_OPERATION;
4557 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004558
4559 // If this request list is for constrained high speed recording (not
4560 // preview), and the current request is not the last one in the batch,
4561 // do not send callback to the app.
4562 bool hasCallback = true;
4563 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4564 hasCallback = false;
4565 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004566 res = parent->registerInFlight(halRequest->frame_number,
4567 totalNumBuffers, captureRequest->mResultExtras,
4568 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004569 hasCallback,
4570 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004571 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4572 ", burstId = %" PRId32 ".",
4573 __FUNCTION__,
4574 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4575 captureRequest->mResultExtras.burstId);
4576 if (res != OK) {
4577 SET_ERR("RequestThread: Unable to register new in-flight request:"
4578 " %s (%d)", strerror(-res), res);
4579 return INVALID_OPERATION;
4580 }
4581 }
4582
4583 return OK;
4584}
4585
Igor Murashkin1e479c02013-09-06 16:55:14 -07004586CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004587 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004588 Mutex::Autolock al(mLatestRequestMutex);
4589
4590 ALOGV("RequestThread::%s", __FUNCTION__);
4591
4592 return mLatestRequest;
4593}
4594
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004595bool Camera3Device::RequestThread::isStreamPending(
4596 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004597 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004598 Mutex::Autolock l(mRequestLock);
4599
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004600 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004601 if (!nextRequest.submitted) {
4602 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4603 if (stream == s) return true;
4604 }
4605 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004606 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004607 }
4608
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004609 for (const auto& request : mRequestQueue) {
4610 for (const auto& s : request->mOutputStreams) {
4611 if (stream == s) return true;
4612 }
4613 if (stream == request->mInputStream) return true;
4614 }
4615
4616 for (const auto& request : mRepeatingRequests) {
4617 for (const auto& s : request->mOutputStreams) {
4618 if (stream == s) return true;
4619 }
4620 if (stream == request->mInputStream) return true;
4621 }
4622
4623 return false;
4624}
Jianing Weicb0652e2014-03-12 18:29:36 -07004625
Emilian Peev40ead602017-09-26 15:46:36 +01004626bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4627 ATRACE_CALL();
4628 Mutex::Autolock l(mRequestLock);
4629
4630 for (const auto& nextRequest : mNextRequests) {
4631 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4632 if (s.first == streamId) {
4633 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4634 if (it != s.second.end()) {
4635 return true;
4636 }
4637 }
4638 }
4639 }
4640
4641 for (const auto& request : mRequestQueue) {
4642 for (const auto& s : request->mOutputSurfaces) {
4643 if (s.first == streamId) {
4644 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4645 if (it != s.second.end()) {
4646 return true;
4647 }
4648 }
4649 }
4650 }
4651
4652 for (const auto& request : mRepeatingRequests) {
4653 for (const auto& s : request->mOutputSurfaces) {
4654 if (s.first == streamId) {
4655 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4656 if (it != s.second.end()) {
4657 return true;
4658 }
4659 }
4660 }
4661 }
4662
4663 return false;
4664}
4665
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004666nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004667 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004668 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004669 return mExpectedInflightDuration > kMinInflightDuration ?
4670 mExpectedInflightDuration : kMinInflightDuration;
4671}
4672
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004673void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4674 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004675 return;
4676 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004677
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004678 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004679 // Skip the ones that have been submitted successfully.
4680 if (nextRequest.submitted) {
4681 continue;
4682 }
4683
4684 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4685 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4686 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4687
4688 if (halRequest->settings != NULL) {
4689 captureRequest->mSettings.unlock(halRequest->settings);
4690 }
4691
4692 if (captureRequest->mInputStream != NULL) {
4693 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4694 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4695 }
4696
4697 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004698 //Buffers that failed processing could still have
4699 //valid acquire fence.
4700 int acquireFence = (*outputBuffers)[i].acquire_fence;
4701 if (0 <= acquireFence) {
4702 close(acquireFence);
4703 outputBuffers->editItemAt(i).acquire_fence = -1;
4704 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004705 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4706 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4707 }
4708
4709 if (sendRequestError) {
4710 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004711 sp<NotificationListener> listener = mListener.promote();
4712 if (listener != NULL) {
4713 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004714 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004715 captureRequest->mResultExtras);
4716 }
4717 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004718
4719 // Remove yet-to-be submitted inflight request from inflightMap
4720 {
4721 sp<Camera3Device> parent = mParent.promote();
4722 if (parent != NULL) {
4723 Mutex::Autolock l(parent->mInFlightLock);
4724 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4725 if (idx >= 0) {
4726 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4727 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4728 parent->removeInFlightMapEntryLocked(idx);
4729 }
4730 }
4731 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004732 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004733
4734 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004735 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004736}
4737
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004739 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004740 // Optimized a bit for the simple steady-state case (single repeating
4741 // request), to avoid putting that request in the queue temporarily.
4742 Mutex::Autolock l(mRequestLock);
4743
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 assert(mNextRequests.empty());
4745
4746 NextRequest nextRequest;
4747 nextRequest.captureRequest = waitForNextRequestLocked();
4748 if (nextRequest.captureRequest == nullptr) {
4749 return;
4750 }
4751
4752 nextRequest.halRequest = camera3_capture_request_t();
4753 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004754 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004755
4756 // Wait for additional requests
4757 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4758
4759 for (size_t i = 1; i < batchSize; i++) {
4760 NextRequest additionalRequest;
4761 additionalRequest.captureRequest = waitForNextRequestLocked();
4762 if (additionalRequest.captureRequest == nullptr) {
4763 break;
4764 }
4765
4766 additionalRequest.halRequest = camera3_capture_request_t();
4767 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004768 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004769 }
4770
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004771 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004772 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004773 mNextRequests.size(), batchSize);
4774 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775 }
4776
4777 return;
4778}
4779
4780sp<Camera3Device::CaptureRequest>
4781 Camera3Device::RequestThread::waitForNextRequestLocked() {
4782 status_t res;
4783 sp<CaptureRequest> nextRequest;
4784
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004785 while (mRequestQueue.empty()) {
4786 if (!mRepeatingRequests.empty()) {
4787 // Always atomically enqueue all requests in a repeating request
4788 // list. Guarantees a complete in-sequence set of captures to
4789 // application.
4790 const RequestList &requests = mRepeatingRequests;
4791 RequestList::const_iterator firstRequest =
4792 requests.begin();
4793 nextRequest = *firstRequest;
4794 mRequestQueue.insert(mRequestQueue.end(),
4795 ++firstRequest,
4796 requests.end());
4797 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004798
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004799 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004800
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004801 break;
4802 }
4803
4804 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004806 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4807 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004808 Mutex::Autolock pl(mPauseLock);
4809 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004810 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004811 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004812 // Let the tracker know
4813 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4814 if (statusTracker != 0) {
4815 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4816 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004817 }
4818 // Stop waiting for now and let thread management happen
4819 return NULL;
4820 }
4821 }
4822
4823 if (nextRequest == NULL) {
4824 // Don't have a repeating request already in hand, so queue
4825 // must have an entry now.
4826 RequestList::iterator firstRequest =
4827 mRequestQueue.begin();
4828 nextRequest = *firstRequest;
4829 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004830 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4831 sp<NotificationListener> listener = mListener.promote();
4832 if (listener != NULL) {
4833 listener->notifyRequestQueueEmpty();
4834 }
4835 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004836 }
4837
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004838 // In case we've been unpaused by setPaused clearing mDoPause, need to
4839 // update internal pause state (capture/setRepeatingRequest unpause
4840 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004841 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004842 if (mPaused) {
4843 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4844 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4845 if (statusTracker != 0) {
4846 statusTracker->markComponentActive(mStatusId);
4847 }
4848 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004849 mPaused = false;
4850
4851 // Check if we've reconfigured since last time, and reset the preview
4852 // request if so. Can't use 'NULL request == repeat' across configure calls.
4853 if (mReconfigured) {
4854 mPrevRequest.clear();
4855 mReconfigured = false;
4856 }
4857
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004858 if (nextRequest != NULL) {
4859 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004860 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4861 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004862
4863 // Since RequestThread::clear() removes buffers from the input stream,
4864 // get the right buffer here before unlocking mRequestLock
4865 if (nextRequest->mInputStream != NULL) {
4866 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4867 if (res != OK) {
4868 // Can't get input buffer from gralloc queue - this could be due to
4869 // disconnected queue or other producer misbehavior, so not a fatal
4870 // error
4871 ALOGE("%s: Can't get input buffer, skipping request:"
4872 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004873
4874 sp<NotificationListener> listener = mListener.promote();
4875 if (listener != NULL) {
4876 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004877 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004878 nextRequest->mResultExtras);
4879 }
4880 return NULL;
4881 }
4882 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004883 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004884
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004885 return nextRequest;
4886}
4887
4888bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004889 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004890 status_t res;
4891 Mutex::Autolock l(mPauseLock);
4892 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004893 if (mPaused == false) {
4894 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004895 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4896 // Let the tracker know
4897 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4898 if (statusTracker != 0) {
4899 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4900 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004901 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004902
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004903 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004904 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004905 return true;
4906 }
4907 }
4908 // We don't set mPaused to false here, because waitForNextRequest needs
4909 // to further manage the paused state in case of starvation.
4910 return false;
4911}
4912
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004913void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004914 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004915 // With work to do, mark thread as unpaused.
4916 // If paused by request (setPaused), don't resume, to avoid
4917 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004918 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004919 Mutex::Autolock p(mPauseLock);
4920 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004921 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4922 if (mPaused) {
4923 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4924 if (statusTracker != 0) {
4925 statusTracker->markComponentActive(mStatusId);
4926 }
4927 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004928 mPaused = false;
4929 }
4930}
4931
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004932void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4933 sp<Camera3Device> parent = mParent.promote();
4934 if (parent != NULL) {
4935 va_list args;
4936 va_start(args, fmt);
4937
4938 parent->setErrorStateV(fmt, args);
4939
4940 va_end(args);
4941 }
4942}
4943
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004944status_t Camera3Device::RequestThread::insertTriggers(
4945 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004946 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004947 Mutex::Autolock al(mTriggerMutex);
4948
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004949 sp<Camera3Device> parent = mParent.promote();
4950 if (parent == NULL) {
4951 CLOGE("RequestThread: Parent is gone");
4952 return DEAD_OBJECT;
4953 }
4954
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004955 CameraMetadata &metadata = request->mSettings;
4956 size_t count = mTriggerMap.size();
4957
4958 for (size_t i = 0; i < count; ++i) {
4959 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004960 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004961
4962 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4963 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4964 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004965 if (isAeTrigger) {
4966 request->mResultExtras.precaptureTriggerId = triggerId;
4967 mCurrentPreCaptureTriggerId = triggerId;
4968 } else {
4969 request->mResultExtras.afTriggerId = triggerId;
4970 mCurrentAfTriggerId = triggerId;
4971 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004972 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004973 }
4974
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004975 camera_metadata_entry entry = metadata.find(tag);
4976
4977 if (entry.count > 0) {
4978 /**
4979 * Already has an entry for this trigger in the request.
4980 * Rewrite it with our requested trigger value.
4981 */
4982 RequestTrigger oldTrigger = trigger;
4983
4984 oldTrigger.entryValue = entry.data.u8[0];
4985
4986 mTriggerReplacedMap.add(tag, oldTrigger);
4987 } else {
4988 /**
4989 * More typical, no trigger entry, so we just add it
4990 */
4991 mTriggerRemovedMap.add(tag, trigger);
4992 }
4993
4994 status_t res;
4995
4996 switch (trigger.getTagType()) {
4997 case TYPE_BYTE: {
4998 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4999 res = metadata.update(tag,
5000 &entryValue,
5001 /*count*/1);
5002 break;
5003 }
5004 case TYPE_INT32:
5005 res = metadata.update(tag,
5006 &trigger.entryValue,
5007 /*count*/1);
5008 break;
5009 default:
5010 ALOGE("%s: Type not supported: 0x%x",
5011 __FUNCTION__,
5012 trigger.getTagType());
5013 return INVALID_OPERATION;
5014 }
5015
5016 if (res != OK) {
5017 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5018 ", value %d", __FUNCTION__, trigger.getTagName(),
5019 trigger.entryValue);
5020 return res;
5021 }
5022
5023 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5024 trigger.getTagName(),
5025 trigger.entryValue);
5026 }
5027
5028 mTriggerMap.clear();
5029
5030 return count;
5031}
5032
5033status_t Camera3Device::RequestThread::removeTriggers(
5034 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005035 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005036 Mutex::Autolock al(mTriggerMutex);
5037
5038 CameraMetadata &metadata = request->mSettings;
5039
5040 /**
5041 * Replace all old entries with their old values.
5042 */
5043 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5044 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5045
5046 status_t res;
5047
5048 uint32_t tag = trigger.metadataTag;
5049 switch (trigger.getTagType()) {
5050 case TYPE_BYTE: {
5051 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5052 res = metadata.update(tag,
5053 &entryValue,
5054 /*count*/1);
5055 break;
5056 }
5057 case TYPE_INT32:
5058 res = metadata.update(tag,
5059 &trigger.entryValue,
5060 /*count*/1);
5061 break;
5062 default:
5063 ALOGE("%s: Type not supported: 0x%x",
5064 __FUNCTION__,
5065 trigger.getTagType());
5066 return INVALID_OPERATION;
5067 }
5068
5069 if (res != OK) {
5070 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5071 ", trigger value %d", __FUNCTION__,
5072 trigger.getTagName(), trigger.entryValue);
5073 return res;
5074 }
5075 }
5076 mTriggerReplacedMap.clear();
5077
5078 /**
5079 * Remove all new entries.
5080 */
5081 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5082 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5083 status_t res = metadata.erase(trigger.metadataTag);
5084
5085 if (res != OK) {
5086 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5087 ", trigger value %d", __FUNCTION__,
5088 trigger.getTagName(), trigger.entryValue);
5089 return res;
5090 }
5091 }
5092 mTriggerRemovedMap.clear();
5093
5094 return OK;
5095}
5096
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005097status_t Camera3Device::RequestThread::addDummyTriggerIds(
5098 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005099 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005100 static const int32_t dummyTriggerId = 1;
5101 status_t res;
5102
5103 CameraMetadata &metadata = request->mSettings;
5104
5105 // If AF trigger is active, insert a dummy AF trigger ID if none already
5106 // exists
5107 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5108 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5109 if (afTrigger.count > 0 &&
5110 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5111 afId.count == 0) {
5112 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5113 if (res != OK) return res;
5114 }
5115
5116 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5117 // if none already exists
5118 camera_metadata_entry pcTrigger =
5119 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5120 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5121 if (pcTrigger.count > 0 &&
5122 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5123 pcId.count == 0) {
5124 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5125 &dummyTriggerId, 1);
5126 if (res != OK) return res;
5127 }
5128
5129 return OK;
5130}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005131
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005132/**
5133 * PreparerThread inner class methods
5134 */
5135
5136Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005137 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005138 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005139}
5140
5141Camera3Device::PreparerThread::~PreparerThread() {
5142 Thread::requestExitAndWait();
5143 if (mCurrentStream != nullptr) {
5144 mCurrentStream->cancelPrepare();
5145 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5146 mCurrentStream.clear();
5147 }
5148 clear();
5149}
5150
Ruben Brunkc78ac262015-08-13 17:58:46 -07005151status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005152 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005153 status_t res;
5154
5155 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005156 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005157
Ruben Brunkc78ac262015-08-13 17:58:46 -07005158 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005159 if (res == OK) {
5160 // No preparation needed, fire listener right off
5161 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005162 if (listener != NULL) {
5163 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005164 }
5165 return OK;
5166 } else if (res != NOT_ENOUGH_DATA) {
5167 return res;
5168 }
5169
5170 // Need to prepare, start up thread if necessary
5171 if (!mActive) {
5172 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5173 // isn't running
5174 Thread::requestExitAndWait();
5175 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5176 if (res != OK) {
5177 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005178 if (listener != NULL) {
5179 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005180 }
5181 return res;
5182 }
5183 mCancelNow = false;
5184 mActive = true;
5185 ALOGV("%s: Preparer stream started", __FUNCTION__);
5186 }
5187
5188 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005189 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005190 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5191
5192 return OK;
5193}
5194
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005195void Camera3Device::PreparerThread::pause() {
5196 ATRACE_CALL();
5197
5198 Mutex::Autolock l(mLock);
5199
5200 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5201 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5202 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5203 int currentMaxCount = mCurrentMaxCount;
5204 mPendingStreams.clear();
5205 mCancelNow = true;
5206 while (mActive) {
5207 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5208 if (res == TIMED_OUT) {
5209 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5210 return;
5211 } else if (res != OK) {
5212 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5213 return;
5214 }
5215 }
5216
5217 //Check whether the prepare thread was able to complete the current
5218 //stream. In case work is still pending emplace it along with the rest
5219 //of the streams in the pending list.
5220 if (currentStream != nullptr) {
5221 if (!mCurrentPrepareComplete) {
5222 pendingStreams.emplace(currentMaxCount, currentStream);
5223 }
5224 }
5225
5226 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5227 for (const auto& it : mPendingStreams) {
5228 it.second->cancelPrepare();
5229 }
5230}
5231
5232status_t Camera3Device::PreparerThread::resume() {
5233 ATRACE_CALL();
5234 status_t res;
5235
5236 Mutex::Autolock l(mLock);
5237 sp<NotificationListener> listener = mListener.promote();
5238
5239 if (mActive) {
5240 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5241 return NO_INIT;
5242 }
5243
5244 auto it = mPendingStreams.begin();
5245 for (; it != mPendingStreams.end();) {
5246 res = it->second->startPrepare(it->first);
5247 if (res == OK) {
5248 if (listener != NULL) {
5249 listener->notifyPrepared(it->second->getId());
5250 }
5251 it = mPendingStreams.erase(it);
5252 } else if (res != NOT_ENOUGH_DATA) {
5253 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5254 res, strerror(-res));
5255 it = mPendingStreams.erase(it);
5256 } else {
5257 it++;
5258 }
5259 }
5260
5261 if (mPendingStreams.empty()) {
5262 return OK;
5263 }
5264
5265 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5266 if (res != OK) {
5267 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5268 __FUNCTION__, res, strerror(-res));
5269 return res;
5270 }
5271 mCancelNow = false;
5272 mActive = true;
5273 ALOGV("%s: Preparer stream started", __FUNCTION__);
5274
5275 return OK;
5276}
5277
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005278status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005279 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005280 Mutex::Autolock l(mLock);
5281
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005282 for (const auto& it : mPendingStreams) {
5283 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005284 }
5285 mPendingStreams.clear();
5286 mCancelNow = true;
5287
5288 return OK;
5289}
5290
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005291void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005292 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005293 Mutex::Autolock l(mLock);
5294 mListener = listener;
5295}
5296
5297bool Camera3Device::PreparerThread::threadLoop() {
5298 status_t res;
5299 {
5300 Mutex::Autolock l(mLock);
5301 if (mCurrentStream == nullptr) {
5302 // End thread if done with work
5303 if (mPendingStreams.empty()) {
5304 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5305 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5306 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5307 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005308 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005309 return false;
5310 }
5311
5312 // Get next stream to prepare
5313 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005314 mCurrentStream = it->second;
5315 mCurrentMaxCount = it->first;
5316 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005317 mPendingStreams.erase(it);
5318 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5319 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5320 } else if (mCancelNow) {
5321 mCurrentStream->cancelPrepare();
5322 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5323 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5324 mCurrentStream.clear();
5325 mCancelNow = false;
5326 return true;
5327 }
5328 }
5329
5330 res = mCurrentStream->prepareNextBuffer();
5331 if (res == NOT_ENOUGH_DATA) return true;
5332 if (res != OK) {
5333 // Something bad happened; try to recover by cancelling prepare and
5334 // signalling listener anyway
5335 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5336 mCurrentStream->getId(), res, strerror(-res));
5337 mCurrentStream->cancelPrepare();
5338 }
5339
5340 // This stream has finished, notify listener
5341 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005342 sp<NotificationListener> listener = mListener.promote();
5343 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005344 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5345 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005346 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005347 }
5348
5349 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5350 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005351 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005352
5353 return true;
5354}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005355
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005356/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005357 * Static callback forwarding methods from HAL to instance
5358 */
5359
5360void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5361 const camera3_capture_result *result) {
5362 Camera3Device *d =
5363 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005364
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005365 d->processCaptureResult(result);
5366}
5367
5368void Camera3Device::sNotify(const camera3_callback_ops *cb,
5369 const camera3_notify_msg *msg) {
5370 Camera3Device *d =
5371 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5372 d->notify(msg);
5373}
5374
5375}; // namespace android