blob: 7dba20dc1e2f4679d19975831aeb4880e8c28148 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
80 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080081{
82 ATRACE_CALL();
83 camera3_callback_ops::notify = &sNotify;
84 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092 disconnect();
93}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
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) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800672 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 "TEMPLATE_PREVIEW",
674 "TEMPLATE_STILL_CAPTURE",
675 "TEMPLATE_VIDEO_RECORD",
676 "TEMPLATE_VIDEO_SNAPSHOT",
677 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800678 "TEMPLATE_MANUAL",
679 "TEMPLATE_MOTION_TRACKING_PREVIEW",
680 "TEMPALTE_MOTION_TRACKING_BEST"
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800681 };
682
683 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800684 camera_metadata_t *templateRequest = nullptr;
685 mInterface->constructDefaultRequestSettings(
686 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800687 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800688 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800689 lines.append(" Not supported\n");
690 write(fd, lines.string(), lines.size());
691 } else {
692 write(fd, lines.string(), lines.size());
693 dump_indented_camera_metadata(templateRequest,
694 fd, /*verbosity*/2, /*indentation*/8);
695 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800697 }
698 }
699
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700700 mTagMonitor.dumpMonitoredMetadata(fd);
701
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800702 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800703 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800704 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800705 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800706 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800707
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700708 if (gotLock) mLock.unlock();
709 if (gotInterfaceLock) mInterfaceLock.unlock();
710
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800711 return OK;
712}
713
714const CameraMetadata& Camera3Device::info() const {
715 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
717 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700718 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800719 mStatus == STATUS_ERROR ?
720 "when in error state" : "before init");
721 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800722 return mDeviceInfo;
723}
724
Jianing Wei90e59c92014-03-12 18:29:36 -0700725status_t Camera3Device::checkStatusOkToCaptureLocked() {
726 switch (mStatus) {
727 case STATUS_ERROR:
728 CLOGE("Device has encountered a serious error");
729 return INVALID_OPERATION;
730 case STATUS_UNINITIALIZED:
731 CLOGE("Device not initialized");
732 return INVALID_OPERATION;
733 case STATUS_UNCONFIGURED:
734 case STATUS_CONFIGURED:
735 case STATUS_ACTIVE:
736 // OK
737 break;
738 default:
739 SET_ERR_L("Unexpected status: %d", mStatus);
740 return INVALID_OPERATION;
741 }
742 return OK;
743}
744
745status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000746 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700747 const std::list<const SurfaceMap> &surfaceMaps,
748 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700749 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700750 if (requestList == NULL) {
751 CLOGE("requestList cannot be NULL.");
752 return BAD_VALUE;
753 }
754
Jianing Weicb0652e2014-03-12 18:29:36 -0700755 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000756 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700757 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
758 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
759 ++metadataIt, ++surfaceMapIt) {
760 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700761 if (newRequest == 0) {
762 CLOGE("Can't create capture request");
763 return BAD_VALUE;
764 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700765
Shuzhen Wang9d066012016-09-30 11:30:20 -0700766 newRequest->mRepeating = repeating;
767
Jianing Weicb0652e2014-03-12 18:29:36 -0700768 // Setup burst Id and request Id
769 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000770 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
771 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700772 CLOGE("RequestID entry exists; but must not be empty in metadata");
773 return BAD_VALUE;
774 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000775 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
776 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700777 } else {
778 CLOGE("RequestID does not exist in metadata");
779 return BAD_VALUE;
780 }
781
Jianing Wei90e59c92014-03-12 18:29:36 -0700782 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700783
784 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700785 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700786 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
787 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
788 return BAD_VALUE;
789 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700790
791 // Setup batch size if this is a high speed video recording request.
792 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
793 auto firstRequest = requestList->begin();
794 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
795 if (outputStream->isVideoStream()) {
796 (*firstRequest)->mBatchSize = requestList->size();
797 break;
798 }
799 }
800 }
801
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 return OK;
803}
804
Jianing Weicb0652e2014-03-12 18:29:36 -0700805status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800807
Emilian Peevaebbe412018-01-15 13:53:24 +0000808 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700809 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000810 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811
Emilian Peevaebbe412018-01-15 13:53:24 +0000812 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700813}
814
Emilian Peevaebbe412018-01-15 13:53:24 +0000815void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816 std::list<const SurfaceMap>& surfaceMaps,
817 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000818 PhysicalCameraSettingsList requestList;
819 requestList.push_back({std::string(getId().string()), request});
820 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700821
822 SurfaceMap surfaceMap;
823 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
824 // With no surface list passed in, stream and surface will have 1-to-1
825 // mapping. So the surface index is 0 for each stream in the surfaceMap.
826 for (size_t i = 0; i < streams.count; i++) {
827 surfaceMap[streams.data.i32[i]].push_back(0);
828 }
829 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800830}
831
Jianing Wei90e59c92014-03-12 18:29:36 -0700832status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 const std::list<const SurfaceMap> &surfaceMaps,
835 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700836 /*out*/
837 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700838 ATRACE_CALL();
839 Mutex::Autolock il(mInterfaceLock);
840 Mutex::Autolock l(mLock);
841
842 status_t res = checkStatusOkToCaptureLocked();
843 if (res != OK) {
844 // error logged by previous call
845 return res;
846 }
847
848 RequestList requestList;
849
Shuzhen Wang0129d522016-10-30 22:43:41 -0700850 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
851 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700852 if (res != OK) {
853 // error logged by previous call
854 return res;
855 }
856
857 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700858 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700860 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700861 }
862
863 if (res == OK) {
864 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
865 if (res != OK) {
866 SET_ERR_L("Can't transition to active in %f seconds!",
867 kActiveTimeout/1e9);
868 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800869 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700870 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700871 } else {
872 CLOGE("Cannot queue request. Impossible.");
873 return BAD_VALUE;
874 }
875
876 return res;
877}
878
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800879hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800880 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800881 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700882 // Ideally we should grab mLock, but that can lead to deadlock, and
883 // it's not super important to get up to date value of mStatus for this
884 // warning print, hence skipping the lock here
885 if (mStatus == STATUS_ERROR) {
886 // Per API contract, HAL should act as closed after device error
887 // But mStatus can be set to error by framework as well, so just log
888 // a warning here.
889 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700890 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700891
892 if (mProcessCaptureResultLock.tryLock() != OK) {
893 // This should never happen; it indicates a wrong client implementation
894 // that doesn't follow the contract. But, we can be tolerant here.
895 ALOGE("%s: callback overlapped! waiting 1s...",
896 __FUNCTION__);
897 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
898 ALOGE("%s: cannot acquire lock in 1s, dropping results",
899 __FUNCTION__);
900 // really don't know what to do, so bail out.
901 return hardware::Void();
902 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800903 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700904 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800905 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700906 }
907 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800908 return hardware::Void();
909}
910
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800911// Only one processCaptureResult should be called at a time, so
912// the locks won't block. The locks are present here simply to enforce this.
913hardware::Return<void> Camera3Device::processCaptureResult(
914 const hardware::hidl_vec<
915 hardware::camera::device::V3_2::CaptureResult>& results) {
916 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
917
918 // Ideally we should grab mLock, but that can lead to deadlock, and
919 // it's not super important to get up to date value of mStatus for this
920 // warning print, hence skipping the lock here
921 if (mStatus == STATUS_ERROR) {
922 // Per API contract, HAL should act as closed after device error
923 // But mStatus can be set to error by framework as well, so just log
924 // a warning here.
925 ALOGW("%s: received capture result in error state.", __FUNCTION__);
926 }
927
928 if (mProcessCaptureResultLock.tryLock() != OK) {
929 // This should never happen; it indicates a wrong client implementation
930 // that doesn't follow the contract. But, we can be tolerant here.
931 ALOGE("%s: callback overlapped! waiting 1s...",
932 __FUNCTION__);
933 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
934 ALOGE("%s: cannot acquire lock in 1s, dropping results",
935 __FUNCTION__);
936 // really don't know what to do, so bail out.
937 return hardware::Void();
938 }
939 }
940 for (const auto& result : results) {
941 processOneCaptureResultLocked(result, noPhysMetadata);
942 }
943 mProcessCaptureResultLock.unlock();
944 return hardware::Void();
945}
946
947status_t Camera3Device::readOneCameraMetadataLocked(
948 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
949 const hardware::camera::device::V3_2::CameraMetadata& result) {
950 if (fmqResultSize > 0) {
951 resultMetadata.resize(fmqResultSize);
952 if (mResultMetadataQueue == nullptr) {
953 return NO_MEMORY; // logged in initialize()
954 }
955 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
956 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
957 __FUNCTION__, fmqResultSize);
958 return INVALID_OPERATION;
959 }
960 } else {
961 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
962 result.size());
963 }
964
965 if (resultMetadata.size() != 0) {
966 status_t res;
967 const camera_metadata_t* metadata =
968 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
969 size_t expected_metadata_size = resultMetadata.size();
970 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
971 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
972 __FUNCTION__, strerror(-res), res);
973 return INVALID_OPERATION;
974 }
975 }
976
977 return OK;
978}
979
Yifan Honga640c5a2017-04-12 16:30:31 -0700980void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800981 const hardware::camera::device::V3_2::CaptureResult& result,
982 const hardware::hidl_vec<
983 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800984 camera3_capture_result r;
985 status_t res;
986 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700987
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800988 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -0700989 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800990 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
991 if (res != OK) {
992 ALOGE("%s: Frame %d: Failed to read capture result metadata",
993 __FUNCTION__, result.frameNumber);
994 return;
Yifan Honga640c5a2017-04-12 16:30:31 -0700995 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800996 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -0700997
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800998 // Read and validate physical camera metadata
999 size_t physResultCount = physicalCameraMetadatas.size();
1000 std::vector<const char*> physCamIds(physResultCount);
1001 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1002 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1003 physResultMetadata.resize(physResultCount);
1004 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1005 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1006 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1007 if (res != OK) {
1008 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1009 __FUNCTION__, result.frameNumber,
1010 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001011 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001012 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001013 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1014 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1015 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001017 r.num_physcam_metadata = physResultCount;
1018 r.physcam_ids = physCamIds.data();
1019 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001020
1021 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1022 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1023 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1024 auto& bDst = outputBuffers[i];
1025 const StreamBuffer &bSrc = result.outputBuffers[i];
1026
1027 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001028 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001029 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1030 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001031 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001032 }
1033 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1034
1035 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001036 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001037 if (res != OK) {
1038 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1039 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001040 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001041 }
1042 bDst.buffer = buffer;
1043 bDst.status = mapHidlBufferStatus(bSrc.status);
1044 bDst.acquire_fence = -1;
1045 if (bSrc.releaseFence == nullptr) {
1046 bDst.release_fence = -1;
1047 } else if (bSrc.releaseFence->numFds == 1) {
1048 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1049 } else {
1050 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1051 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001052 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001053 }
1054 }
1055 r.num_output_buffers = outputBuffers.size();
1056 r.output_buffers = outputBuffers.data();
1057
1058 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001059 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001060 r.input_buffer = nullptr;
1061 } else {
1062 if (mInputStream->getId() != result.inputBuffer.streamId) {
1063 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1064 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001065 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001066 }
1067 inputBuffer.stream = mInputStream->asHalStream();
1068 buffer_handle_t *buffer;
1069 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1070 &buffer);
1071 if (res != OK) {
1072 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1073 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001074 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001075 }
1076 inputBuffer.buffer = buffer;
1077 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1078 inputBuffer.acquire_fence = -1;
1079 if (result.inputBuffer.releaseFence == nullptr) {
1080 inputBuffer.release_fence = -1;
1081 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1082 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1083 } else {
1084 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1085 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001086 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001087 }
1088 r.input_buffer = &inputBuffer;
1089 }
1090
1091 r.partial_result = result.partialResult;
1092
1093 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001094}
1095
1096hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001097 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001098 // Ideally we should grab mLock, but that can lead to deadlock, and
1099 // it's not super important to get up to date value of mStatus for this
1100 // warning print, hence skipping the lock here
1101 if (mStatus == STATUS_ERROR) {
1102 // Per API contract, HAL should act as closed after device error
1103 // But mStatus can be set to error by framework as well, so just log
1104 // a warning here.
1105 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001106 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001107
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001108 for (const auto& msg : msgs) {
1109 notify(msg);
1110 }
1111 return hardware::Void();
1112}
1113
1114void Camera3Device::notify(
1115 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001117 camera3_notify_msg m;
1118 switch (msg.type) {
1119 case MsgType::ERROR:
1120 m.type = CAMERA3_MSG_ERROR;
1121 m.message.error.frame_number = msg.msg.error.frameNumber;
1122 if (msg.msg.error.errorStreamId >= 0) {
1123 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001124 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125 ALOGE("%s: Frame %d: Invalid error stream id %d",
1126 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001127 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001128 }
1129 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1130 } else {
1131 m.message.error.error_stream = nullptr;
1132 }
1133 switch (msg.msg.error.errorCode) {
1134 case ErrorCode::ERROR_DEVICE:
1135 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1136 break;
1137 case ErrorCode::ERROR_REQUEST:
1138 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1139 break;
1140 case ErrorCode::ERROR_RESULT:
1141 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1142 break;
1143 case ErrorCode::ERROR_BUFFER:
1144 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1145 break;
1146 }
1147 break;
1148 case MsgType::SHUTTER:
1149 m.type = CAMERA3_MSG_SHUTTER;
1150 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1151 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1152 break;
1153 }
1154 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001155}
1156
Emilian Peevaebbe412018-01-15 13:53:24 +00001157status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001158 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001159 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001160 ATRACE_CALL();
1161
Emilian Peevaebbe412018-01-15 13:53:24 +00001162 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001163}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001164
Jianing Weicb0652e2014-03-12 18:29:36 -07001165status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1166 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001167 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001168
Emilian Peevaebbe412018-01-15 13:53:24 +00001169 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001170 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001171 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172
Emilian Peevaebbe412018-01-15 13:53:24 +00001173 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001174 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175}
1176
Emilian Peevaebbe412018-01-15 13:53:24 +00001177status_t Camera3Device::setStreamingRequestList(
1178 const List<const PhysicalCameraSettingsList> &requestsList,
1179 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001180 ATRACE_CALL();
1181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001183}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001184
1185sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001186 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 status_t res;
1188
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001190 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1191 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001192 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1193 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001194 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001196 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001198 } else if (mStatus == STATUS_UNCONFIGURED) {
1199 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 CLOGE("No streams configured");
1201 return NULL;
1202 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 }
1204
Shuzhen Wang0129d522016-10-30 22:43:41 -07001205 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207}
1208
Jianing Weicb0652e2014-03-12 18:29:36 -07001209status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 switch (mStatus) {
1215 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001219 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 case STATUS_UNCONFIGURED:
1222 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 case STATUS_ACTIVE:
1224 // OK
1225 break;
1226 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001227 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 return INVALID_OPERATION;
1229 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001230 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001231
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001232 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233}
1234
1235status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001239 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240}
1241
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001242status_t Camera3Device::createInputStream(
1243 uint32_t width, uint32_t height, int format, int *id) {
1244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001246 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001247 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001248 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1249 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001250
1251 status_t res;
1252 bool wasActive = false;
1253
1254 switch (mStatus) {
1255 case STATUS_ERROR:
1256 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1257 return INVALID_OPERATION;
1258 case STATUS_UNINITIALIZED:
1259 ALOGE("%s: Device not initialized", __FUNCTION__);
1260 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 case STATUS_UNCONFIGURED:
1262 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001263 // OK
1264 break;
1265 case STATUS_ACTIVE:
1266 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001267 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001268 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001269 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001270 return res;
1271 }
1272 wasActive = true;
1273 break;
1274 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 return INVALID_OPERATION;
1277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001279
1280 if (mInputStream != 0) {
1281 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1282 return INVALID_OPERATION;
1283 }
1284
1285 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1286 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288
1289 mInputStream = newStream;
1290
1291 *id = mNextStreamId++;
1292
1293 // Continue captures if active at start
1294 if (wasActive) {
1295 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001296 // Reuse current operating mode and session parameters for new stream config
1297 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001298 if (res != OK) {
1299 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1300 __FUNCTION__, mNextStreamId, strerror(-res), res);
1301 return res;
1302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304 }
1305
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001306 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001307 return OK;
1308}
1309
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001310status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001311 uint32_t width, uint32_t height, int format,
1312 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001313 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001314 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001315 ATRACE_CALL();
1316
1317 if (consumer == nullptr) {
1318 ALOGE("%s: consumer must not be null", __FUNCTION__);
1319 return BAD_VALUE;
1320 }
1321
1322 std::vector<sp<Surface>> consumers;
1323 consumers.push_back(consumer);
1324
1325 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001326 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1327 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001328}
1329
1330status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1331 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1332 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001333 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001334 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001335 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001336
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001337 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001338 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001339 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001340 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001341 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1342 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1343 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 status_t res;
1346 bool wasActive = false;
1347
1348 switch (mStatus) {
1349 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001350 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 return INVALID_OPERATION;
1352 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001353 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001355 case STATUS_UNCONFIGURED:
1356 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 // OK
1358 break;
1359 case STATUS_ACTIVE:
1360 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001361 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001363 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return res;
1365 }
1366 wasActive = true;
1367 break;
1368 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001369 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return INVALID_OPERATION;
1371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001372 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373
1374 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001375
Shuzhen Wang0129d522016-10-30 22:43:41 -07001376 if (consumers.size() == 0 && !hasDeferredConsumer) {
1377 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1378 return BAD_VALUE;
1379 }
Zhijun He5d677d12016-05-29 16:52:39 -07001380
Shuzhen Wang0129d522016-10-30 22:43:41 -07001381 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001382 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1383 return BAD_VALUE;
1384 }
1385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001387 ssize_t blobBufferSize;
1388 if (dataSpace != HAL_DATASPACE_DEPTH) {
1389 blobBufferSize = getJpegBufferSize(width, height);
1390 if (blobBufferSize <= 0) {
1391 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1392 return BAD_VALUE;
1393 }
1394 } else {
1395 blobBufferSize = getPointCloudBufferSize();
1396 if (blobBufferSize <= 0) {
1397 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1398 return BAD_VALUE;
1399 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001400 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001401 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001402 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001403 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001404 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1405 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1406 if (rawOpaqueBufferSize <= 0) {
1407 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1408 return BAD_VALUE;
1409 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001410 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001411 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001412 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001413 } else if (isShared) {
1414 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1415 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001416 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001417 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001418 newStream = new Camera3OutputStream(mNextStreamId,
1419 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001420 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001422 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001423 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001424 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 }
Emilian Peev40ead602017-09-26 15:46:36 +01001426
1427 size_t consumerCount = consumers.size();
1428 for (size_t i = 0; i < consumerCount; i++) {
1429 int id = newStream->getSurfaceId(consumers[i]);
1430 if (id < 0) {
1431 SET_ERR_L("Invalid surface id");
1432 return BAD_VALUE;
1433 }
1434 if (surfaceIds != nullptr) {
1435 surfaceIds->push_back(id);
1436 }
1437 }
1438
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001439 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440
Emilian Peev08dd2452017-04-06 16:55:14 +01001441 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001442
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 res = mOutputStreams.add(mNextStreamId, newStream);
1444 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 return res;
1447 }
1448
1449 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001450 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451
1452 // Continue captures if active at start
1453 if (wasActive) {
1454 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001455 // Reuse current operating mode and session parameters for new stream config
1456 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001458 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1459 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 return res;
1461 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001462 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001464 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001466}
1467
Emilian Peev710c1422017-08-30 11:19:38 +01001468status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001469 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001470 if (nullptr == streamInfo) {
1471 return BAD_VALUE;
1472 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001473 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 switch (mStatus) {
1477 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001478 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 return INVALID_OPERATION;
1480 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001481 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001483 case STATUS_UNCONFIGURED:
1484 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 case STATUS_ACTIVE:
1486 // OK
1487 break;
1488 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001489 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 return INVALID_OPERATION;
1491 }
1492
1493 ssize_t idx = mOutputStreams.indexOfKey(id);
1494 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 return idx;
1497 }
1498
Emilian Peev710c1422017-08-30 11:19:38 +01001499 streamInfo->width = mOutputStreams[idx]->getWidth();
1500 streamInfo->height = mOutputStreams[idx]->getHeight();
1501 streamInfo->format = mOutputStreams[idx]->getFormat();
1502 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1503 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1504 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001505 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1506 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001508}
1509
1510status_t Camera3Device::setStreamTransform(int id,
1511 int transform) {
1512 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001515
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 switch (mStatus) {
1517 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001518 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return INVALID_OPERATION;
1520 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001521 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523 case STATUS_UNCONFIGURED:
1524 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 case STATUS_ACTIVE:
1526 // OK
1527 break;
1528 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 return INVALID_OPERATION;
1531 }
1532
1533 ssize_t idx = mOutputStreams.indexOfKey(id);
1534 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001535 CLOGE("Stream %d does not exist",
1536 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return BAD_VALUE;
1538 }
1539
1540 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001541}
1542
1543status_t Camera3Device::deleteStream(int id) {
1544 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 Mutex::Autolock l(mLock);
1547 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001549 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001550
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 // CameraDevice semantics require device to already be idle before
1552 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001554 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001555 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 }
1557
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001558 if (mStatus == STATUS_ERROR) {
1559 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1560 __FUNCTION__, mId.string());
1561 return -EBUSY;
1562 }
1563
Igor Murashkin2fba5842013-04-22 14:03:54 -07001564 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001565 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 if (mInputStream != NULL && id == mInputStream->getId()) {
1567 deletedStream = mInputStream;
1568 mInputStream.clear();
1569 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001570 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return BAD_VALUE;
1573 }
Zhijun He5f446352014-01-22 09:49:33 -08001574 }
1575
1576 // Delete output stream or the output part of a bi-directional stream.
1577 if (outputStreamIdx != NAME_NOT_FOUND) {
1578 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 mOutputStreams.removeItem(id);
1580 }
1581
1582 // Free up the stream endpoint so that it can be used by some other stream
1583 res = deletedStream->disconnect();
1584 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001585 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 // fall through since we want to still list the stream as deleted.
1587 }
1588 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001589 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590
1591 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001592}
1593
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001594status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001595 ATRACE_CALL();
1596 ALOGV("%s: E", __FUNCTION__);
1597
1598 Mutex::Autolock il(mInterfaceLock);
1599 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001600
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001601 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1602}
1603
1604status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1605 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001606 //Filter out any incoming session parameters
1607 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001608 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1609 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001610 CameraMetadata filteredParams(availableSessionKeys.count);
1611 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1612 filteredParams.getAndLock());
1613 set_camera_metadata_vendor_id(meta, mVendorTagId);
1614 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001615 if (availableSessionKeys.count > 0) {
1616 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1617 camera_metadata_ro_entry entry = params.find(
1618 availableSessionKeys.data.i32[i]);
1619 if (entry.count > 0) {
1620 filteredParams.update(entry);
1621 }
1622 }
1623 }
1624
1625 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001626}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001627
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001628status_t Camera3Device::getInputBufferProducer(
1629 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001630 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001631 Mutex::Autolock il(mInterfaceLock);
1632 Mutex::Autolock l(mLock);
1633
1634 if (producer == NULL) {
1635 return BAD_VALUE;
1636 } else if (mInputStream == NULL) {
1637 return INVALID_OPERATION;
1638 }
1639
1640 return mInputStream->getInputBufferProducer(producer);
1641}
1642
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643status_t Camera3Device::createDefaultRequest(int templateId,
1644 CameraMetadata *request) {
1645 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001646 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001647
1648 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1649 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1650 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1651 return BAD_VALUE;
1652 }
1653
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001654 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001655
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001656 {
1657 Mutex::Autolock l(mLock);
1658 switch (mStatus) {
1659 case STATUS_ERROR:
1660 CLOGE("Device has encountered a serious error");
1661 return INVALID_OPERATION;
1662 case STATUS_UNINITIALIZED:
1663 CLOGE("Device is not initialized!");
1664 return INVALID_OPERATION;
1665 case STATUS_UNCONFIGURED:
1666 case STATUS_CONFIGURED:
1667 case STATUS_ACTIVE:
1668 // OK
1669 break;
1670 default:
1671 SET_ERR_L("Unexpected status: %d", mStatus);
1672 return INVALID_OPERATION;
1673 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001675 if (!mRequestTemplateCache[templateId].isEmpty()) {
1676 *request = mRequestTemplateCache[templateId];
1677 return OK;
1678 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001679 }
1680
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001681 camera_metadata_t *rawRequest;
1682 status_t res = mInterface->constructDefaultRequestSettings(
1683 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001684
1685 {
1686 Mutex::Autolock l(mLock);
1687 if (res == BAD_VALUE) {
1688 ALOGI("%s: template %d is not supported on this camera device",
1689 __FUNCTION__, templateId);
1690 return res;
1691 } else if (res != OK) {
1692 CLOGE("Unable to construct request template %d: %s (%d)",
1693 templateId, strerror(-res), res);
1694 return res;
1695 }
1696
1697 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1698 mRequestTemplateCache[templateId].acquire(rawRequest);
1699
1700 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001701 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001702 return OK;
1703}
1704
1705status_t Camera3Device::waitUntilDrained() {
1706 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001707 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001708 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001709 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001711 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001712}
1713
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001714status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001715 switch (mStatus) {
1716 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001717 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001718 ALOGV("%s: Already idle", __FUNCTION__);
1719 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001720 case STATUS_CONFIGURED:
1721 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001722 case STATUS_ERROR:
1723 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001724 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001725 break;
1726 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001727 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001728 return INVALID_OPERATION;
1729 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001730 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1731 maxExpectedDuration);
1732 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001733 if (res != OK) {
1734 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1735 res);
1736 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001737 return res;
1738}
1739
Ruben Brunk183f0562015-08-12 12:55:02 -07001740
1741void Camera3Device::internalUpdateStatusLocked(Status status) {
1742 mStatus = status;
1743 mRecentStatusUpdates.add(mStatus);
1744 mStatusChanged.broadcast();
1745}
1746
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001747void Camera3Device::pauseStateNotify(bool enable) {
1748 Mutex::Autolock il(mInterfaceLock);
1749 Mutex::Autolock l(mLock);
1750
1751 mPauseStateNotify = enable;
1752}
1753
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001755status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001758 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1759 maxExpectedDuration);
1760 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001761 if (res != OK) {
1762 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001763 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 }
1765
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001766 return res;
1767}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001768
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001769// Resume after internalPauseAndWaitLocked
1770status_t Camera3Device::internalResumeLocked() {
1771 status_t res;
1772
1773 mRequestThread->setPaused(false);
1774
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001775 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1776 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001777 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1778 if (res != OK) {
1779 SET_ERR_L("Can't transition to active in %f seconds!",
1780 kActiveTimeout/1e9);
1781 }
1782 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001783 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001784}
1785
Ruben Brunk183f0562015-08-12 12:55:02 -07001786status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001788
1789 size_t startIndex = 0;
1790 if (mStatusWaiters == 0) {
1791 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1792 // this status list
1793 mRecentStatusUpdates.clear();
1794 } else {
1795 // If other threads are waiting on updates to this status list, set the position of the
1796 // first element that this list will check rather than clearing the list.
1797 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 }
1799
Ruben Brunk183f0562015-08-12 12:55:02 -07001800 mStatusWaiters++;
1801
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802 bool stateSeen = false;
1803 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001804 if (active == (mStatus == STATUS_ACTIVE)) {
1805 // Desired state is current
1806 break;
1807 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808
1809 res = mStatusChanged.waitRelative(mLock, timeout);
1810 if (res != OK) break;
1811
Ruben Brunk183f0562015-08-12 12:55:02 -07001812 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1813 // transitions.
1814 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1815 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1816 __FUNCTION__);
1817
1818 // Encountered desired state since we began waiting
1819 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1821 stateSeen = true;
1822 break;
1823 }
1824 }
1825 } while (!stateSeen);
1826
Ruben Brunk183f0562015-08-12 12:55:02 -07001827 mStatusWaiters--;
1828
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 return res;
1830}
1831
1832
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001833status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001834 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001835 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001837 if (listener != NULL && mListener != NULL) {
1838 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1839 }
1840 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001841 mRequestThread->setNotificationListener(listener);
1842 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001843
1844 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001845}
1846
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001847bool Camera3Device::willNotify3A() {
1848 return false;
1849}
1850
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001851status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001852 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001853 status_t res;
1854 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001855
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001856 while (mResultQueue.empty()) {
1857 res = mResultSignal.waitRelative(mOutputLock, timeout);
1858 if (res == TIMED_OUT) {
1859 return res;
1860 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001861 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1862 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001863 return res;
1864 }
1865 }
1866 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867}
1868
Jianing Weicb0652e2014-03-12 18:29:36 -07001869status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001870 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001871 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001872
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001873 if (mResultQueue.empty()) {
1874 return NOT_ENOUGH_DATA;
1875 }
1876
Jianing Weicb0652e2014-03-12 18:29:36 -07001877 if (frame == NULL) {
1878 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1879 return BAD_VALUE;
1880 }
1881
1882 CaptureResult &result = *(mResultQueue.begin());
1883 frame->mResultExtras = result.mResultExtras;
1884 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001885 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001886 mResultQueue.erase(mResultQueue.begin());
1887
1888 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889}
1890
1891status_t Camera3Device::triggerAutofocus(uint32_t id) {
1892 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001893 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001895 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1896 // Mix-in this trigger into the next request and only the next request.
1897 RequestTrigger trigger[] = {
1898 {
1899 ANDROID_CONTROL_AF_TRIGGER,
1900 ANDROID_CONTROL_AF_TRIGGER_START
1901 },
1902 {
1903 ANDROID_CONTROL_AF_TRIGGER_ID,
1904 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001905 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001906 };
1907
1908 return mRequestThread->queueTrigger(trigger,
1909 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001910}
1911
1912status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1913 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001914 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001915
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001916 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1917 // Mix-in this trigger into the next request and only the next request.
1918 RequestTrigger trigger[] = {
1919 {
1920 ANDROID_CONTROL_AF_TRIGGER,
1921 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1922 },
1923 {
1924 ANDROID_CONTROL_AF_TRIGGER_ID,
1925 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001926 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001927 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001928
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001929 return mRequestThread->queueTrigger(trigger,
1930 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001931}
1932
1933status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1934 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001936
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001937 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1938 // Mix-in this trigger into the next request and only the next request.
1939 RequestTrigger trigger[] = {
1940 {
1941 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1942 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1943 },
1944 {
1945 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1946 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001947 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001948 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001949
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001950 return mRequestThread->queueTrigger(trigger,
1951 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001952}
1953
Jianing Weicb0652e2014-03-12 18:29:36 -07001954status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001955 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001956 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001957 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001958
Zhijun He7ef20392014-04-21 16:04:17 -07001959 {
1960 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001961 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001962 }
1963
Emilian Peev08dd2452017-04-06 16:55:14 +01001964 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001965}
1966
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001967status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001968 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1969}
1970
1971status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001972 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001973 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001974 Mutex::Autolock il(mInterfaceLock);
1975 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001976
1977 sp<Camera3StreamInterface> stream;
1978 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1979 if (outputStreamIdx == NAME_NOT_FOUND) {
1980 CLOGE("Stream %d does not exist", streamId);
1981 return BAD_VALUE;
1982 }
1983
1984 stream = mOutputStreams.editValueAt(outputStreamIdx);
1985
1986 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001987 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001988 return BAD_VALUE;
1989 }
1990
1991 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001992 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001993 return BAD_VALUE;
1994 }
1995
Ruben Brunkc78ac262015-08-13 17:58:46 -07001996 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001997}
1998
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001999status_t Camera3Device::tearDown(int streamId) {
2000 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002001 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002002 Mutex::Autolock il(mInterfaceLock);
2003 Mutex::Autolock l(mLock);
2004
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002005 sp<Camera3StreamInterface> stream;
2006 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2007 if (outputStreamIdx == NAME_NOT_FOUND) {
2008 CLOGE("Stream %d does not exist", streamId);
2009 return BAD_VALUE;
2010 }
2011
2012 stream = mOutputStreams.editValueAt(outputStreamIdx);
2013
2014 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2015 CLOGE("Stream %d is a target of a in-progress request", streamId);
2016 return BAD_VALUE;
2017 }
2018
2019 return stream->tearDown();
2020}
2021
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002022status_t Camera3Device::addBufferListenerForStream(int streamId,
2023 wp<Camera3StreamBufferListener> listener) {
2024 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002025 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002026 Mutex::Autolock il(mInterfaceLock);
2027 Mutex::Autolock l(mLock);
2028
2029 sp<Camera3StreamInterface> stream;
2030 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2031 if (outputStreamIdx == NAME_NOT_FOUND) {
2032 CLOGE("Stream %d does not exist", streamId);
2033 return BAD_VALUE;
2034 }
2035
2036 stream = mOutputStreams.editValueAt(outputStreamIdx);
2037 stream->addBufferListener(listener);
2038
2039 return OK;
2040}
2041
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002042/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002043 * Methods called by subclasses
2044 */
2045
2046void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002047 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002048 {
2049 // Need mLock to safely update state and synchronize to current
2050 // state of methods in flight.
2051 Mutex::Autolock l(mLock);
2052 // We can get various system-idle notices from the status tracker
2053 // while starting up. Only care about them if we've actually sent
2054 // in some requests recently.
2055 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2056 return;
2057 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002058 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2059 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002060 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002061
2062 // Skip notifying listener if we're doing some user-transparent
2063 // state changes
2064 if (mPauseStateNotify) return;
2065 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002066
2067 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002068 {
2069 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002070 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002071 }
2072 if (idle && listener != NULL) {
2073 listener->notifyIdle();
2074 }
2075}
2076
Shuzhen Wang758c2152017-01-10 18:26:18 -08002077status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002078 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002079 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002080 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2081 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002082
2083 if (surfaceIds == nullptr) {
2084 return BAD_VALUE;
2085 }
2086
Zhijun He5d677d12016-05-29 16:52:39 -07002087 Mutex::Autolock il(mInterfaceLock);
2088 Mutex::Autolock l(mLock);
2089
Shuzhen Wang758c2152017-01-10 18:26:18 -08002090 if (consumers.size() == 0) {
2091 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002092 return BAD_VALUE;
2093 }
2094
2095 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2096 if (idx == NAME_NOT_FOUND) {
2097 CLOGE("Stream %d is unknown", streamId);
2098 return idx;
2099 }
2100 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002101 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002102 if (res != OK) {
2103 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2104 return res;
2105 }
2106
Emilian Peev40ead602017-09-26 15:46:36 +01002107 for (auto &consumer : consumers) {
2108 int id = stream->getSurfaceId(consumer);
2109 if (id < 0) {
2110 CLOGE("Invalid surface id!");
2111 return BAD_VALUE;
2112 }
2113 surfaceIds->push_back(id);
2114 }
2115
Shuzhen Wang0129d522016-10-30 22:43:41 -07002116 if (stream->isConsumerConfigurationDeferred()) {
2117 if (!stream->isConfiguring()) {
2118 CLOGE("Stream %d was already fully configured.", streamId);
2119 return INVALID_OPERATION;
2120 }
Zhijun He5d677d12016-05-29 16:52:39 -07002121
Shuzhen Wang0129d522016-10-30 22:43:41 -07002122 res = stream->finishConfiguration();
2123 if (res != OK) {
2124 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2125 stream->getId(), strerror(-res), res);
2126 return res;
2127 }
Zhijun He5d677d12016-05-29 16:52:39 -07002128 }
2129
2130 return OK;
2131}
2132
Emilian Peev40ead602017-09-26 15:46:36 +01002133status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2134 const std::vector<OutputStreamInfo> &outputInfo,
2135 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2136 Mutex::Autolock il(mInterfaceLock);
2137 Mutex::Autolock l(mLock);
2138
2139 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2140 if (idx == NAME_NOT_FOUND) {
2141 CLOGE("Stream %d is unknown", streamId);
2142 return idx;
2143 }
2144
2145 for (const auto &it : removedSurfaceIds) {
2146 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2147 CLOGE("Shared surface still part of a pending request!");
2148 return -EBUSY;
2149 }
2150 }
2151
2152 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2153 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2154 if (res != OK) {
2155 CLOGE("Stream %d failed to update stream (error %d %s) ",
2156 streamId, res, strerror(-res));
2157 if (res == UNKNOWN_ERROR) {
2158 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2159 __FUNCTION__);
2160 }
2161 return res;
2162 }
2163
2164 return res;
2165}
2166
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002167status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2168 Mutex::Autolock il(mInterfaceLock);
2169 Mutex::Autolock l(mLock);
2170
2171 int idx = mOutputStreams.indexOfKey(streamId);
2172 if (idx == NAME_NOT_FOUND) {
2173 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2174 return BAD_VALUE;
2175 }
2176
2177 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2178 return stream->dropBuffers(dropping);
2179}
2180
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002182 * Camera3Device private methods
2183 */
2184
2185sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002186 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002187 ATRACE_CALL();
2188 status_t res;
2189
2190 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002191 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002192
2193 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002194 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195 if (inputStreams.count > 0) {
2196 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002197 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002198 CLOGE("Request references unknown input stream %d",
2199 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200 return NULL;
2201 }
2202 // Lazy completion of stream configuration (allocation/registration)
2203 // on first use
2204 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002205 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002206 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002207 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002208 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002209 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 return NULL;
2211 }
2212 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002213 // Check if stream is being prepared
2214 if (mInputStream->isPreparing()) {
2215 CLOGE("Request references an input stream that's being prepared!");
2216 return NULL;
2217 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002218
2219 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002220 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002221 }
2222
2223 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002224 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002226 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002227 return NULL;
2228 }
2229
2230 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002231 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002232 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002233 CLOGE("Request references unknown stream %d",
2234 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235 return NULL;
2236 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002237 sp<Camera3OutputStreamInterface> stream =
2238 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239
Zhijun He5d677d12016-05-29 16:52:39 -07002240 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002241 auto iter = surfaceMap.find(streams.data.i32[i]);
2242 if (iter != surfaceMap.end()) {
2243 const std::vector<size_t>& surfaces = iter->second;
2244 for (const auto& surface : surfaces) {
2245 if (stream->isConsumerConfigurationDeferred(surface)) {
2246 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2247 "due to deferred consumer", stream->getId(), surface);
2248 return NULL;
2249 }
2250 }
2251 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002252 }
2253
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 // Lazy completion of stream configuration (allocation/registration)
2255 // on first use
2256 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002257 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002259 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2260 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002261 return NULL;
2262 }
2263 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002264 // Check if stream is being prepared
2265 if (stream->isPreparing()) {
2266 CLOGE("Request references an output stream that's being prepared!");
2267 return NULL;
2268 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002269
2270 newRequest->mOutputStreams.push(stream);
2271 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002272 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002273 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002274
2275 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002276}
2277
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002278bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2279 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2280 Size size = mSupportedOpaqueInputSizes[i];
2281 if (size.width == width && size.height == height) {
2282 return true;
2283 }
2284 }
2285
2286 return false;
2287}
2288
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002289void Camera3Device::cancelStreamsConfigurationLocked() {
2290 int res = OK;
2291 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2292 res = mInputStream->cancelConfiguration();
2293 if (res != OK) {
2294 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2295 mInputStream->getId(), strerror(-res), res);
2296 }
2297 }
2298
2299 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2300 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2301 if (outputStream->isConfiguring()) {
2302 res = outputStream->cancelConfiguration();
2303 if (res != OK) {
2304 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2305 outputStream->getId(), strerror(-res), res);
2306 }
2307 }
2308 }
2309
2310 // Return state to that at start of call, so that future configures
2311 // properly clean things up
2312 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2313 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002314
2315 res = mPreparerThread->resume();
2316 if (res != OK) {
2317 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2318 }
2319}
2320
2321bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2322 ATRACE_CALL();
2323 bool ret = false;
2324
2325 Mutex::Autolock il(mInterfaceLock);
2326 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2327
2328 Mutex::Autolock l(mLock);
2329 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2330 if (rc == NO_ERROR) {
2331 mNeedConfig = true;
2332 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2333 if (rc == NO_ERROR) {
2334 ret = true;
2335 mPauseStateNotify = false;
2336 //Moving to active state while holding 'mLock' is important.
2337 //There could be pending calls to 'create-/deleteStream' which
2338 //will trigger another stream configuration while the already
2339 //present streams end up with outstanding buffers that will
2340 //not get drained.
2341 internalUpdateStatusLocked(STATUS_ACTIVE);
2342 } else {
2343 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2344 __FUNCTION__, rc);
2345 }
2346 } else {
2347 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2348 }
2349
2350 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002351}
2352
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002353status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002354 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002355 ATRACE_CALL();
2356 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002357
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002358 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002359 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 return INVALID_OPERATION;
2361 }
2362
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002363 if (operatingMode < 0) {
2364 CLOGE("Invalid operating mode: %d", operatingMode);
2365 return BAD_VALUE;
2366 }
2367
2368 bool isConstrainedHighSpeed =
2369 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2370 operatingMode;
2371
2372 if (mOperatingMode != operatingMode) {
2373 mNeedConfig = true;
2374 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2375 mOperatingMode = operatingMode;
2376 }
2377
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002378 if (!mNeedConfig) {
2379 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2380 return OK;
2381 }
2382
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002383 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2384 // adding a dummy stream instead.
2385 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2386 if (mOutputStreams.size() == 0) {
2387 addDummyStreamLocked();
2388 } else {
2389 tryRemoveDummyStreamLocked();
2390 }
2391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002393 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002395 mPreparerThread->pause();
2396
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002398 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2400
2401 Vector<camera3_stream_t*> streams;
2402 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002403 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002404
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002405
2406 if (mInputStream != NULL) {
2407 camera3_stream_t *inputStream;
2408 inputStream = mInputStream->startConfiguration();
2409 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002410 CLOGE("Can't start input stream configuration");
2411 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002412 return INVALID_OPERATION;
2413 }
2414 streams.add(inputStream);
2415 }
2416
2417 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002418
2419 // Don't configure bidi streams twice, nor add them twice to the list
2420 if (mOutputStreams[i].get() ==
2421 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2422
2423 config.num_streams--;
2424 continue;
2425 }
2426
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427 camera3_stream_t *outputStream;
2428 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2429 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002430 CLOGE("Can't start output stream configuration");
2431 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002432 return INVALID_OPERATION;
2433 }
2434 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002435
2436 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2437 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002438 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2439 // always occupy the initial entry.
2440 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002441 getJpegBufferSize(outputStream->width, outputStream->height));
2442 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002443 }
2444
2445 config.streams = streams.editArray();
2446
2447 // Do the HAL configuration; will potentially touch stream
2448 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002449
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002450 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002451 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002452 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002453
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002454 if (res == BAD_VALUE) {
2455 // HAL rejected this set of streams as unsupported, clean up config
2456 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 CLOGE("Set of requested inputs/outputs not supported by HAL");
2458 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002459 return BAD_VALUE;
2460 } else if (res != OK) {
2461 // Some other kind of error from configure_streams - this is not
2462 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002463 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2464 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002465 return res;
2466 }
2467
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002468 // Finish all stream configuration immediately.
2469 // TODO: Try to relax this later back to lazy completion, which should be
2470 // faster
2471
Igor Murashkin073f8572013-05-02 14:59:28 -07002472 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002473 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002474 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002475 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002476 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002477 cancelStreamsConfigurationLocked();
2478 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002479 }
2480 }
2481
2482 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002483 sp<Camera3OutputStreamInterface> outputStream =
2484 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002485 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002486 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002487 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002488 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002489 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002490 cancelStreamsConfigurationLocked();
2491 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002492 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002493 }
2494 }
2495
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002496 // Request thread needs to know to avoid using repeat-last-settings protocol
2497 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002498 if (notifyRequestThread) {
2499 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2500 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002501
Zhijun He90f7c372016-08-16 16:19:43 -07002502 char value[PROPERTY_VALUE_MAX];
2503 property_get("camera.fifo.disable", value, "0");
2504 int32_t disableFifo = atoi(value);
2505 if (disableFifo != 1) {
2506 // Boost priority of request thread to SCHED_FIFO.
2507 pid_t requestThreadTid = mRequestThread->getTid();
2508 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002509 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002510 if (res != OK) {
2511 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2512 strerror(-res), res);
2513 } else {
2514 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2515 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002516 }
2517
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002518 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002519 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2520 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2521 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2522 sessionParams.unlock(newSessionParams);
2523 mSessionParams.unlock(currentSessionParams);
2524 if (updateSessionParams) {
2525 mSessionParams = sessionParams;
2526 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002527
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002528 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529
Ruben Brunk183f0562015-08-12 12:55:02 -07002530 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2531 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002533 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002534
Zhijun He0a210512014-07-24 13:45:15 -07002535 // tear down the deleted streams after configure streams.
2536 mDeletedStreams.clear();
2537
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002538 auto rc = mPreparerThread->resume();
2539 if (rc != OK) {
2540 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2541 return rc;
2542 }
2543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002545}
2546
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002547status_t Camera3Device::addDummyStreamLocked() {
2548 ATRACE_CALL();
2549 status_t res;
2550
2551 if (mDummyStreamId != NO_STREAM) {
2552 // Should never be adding a second dummy stream when one is already
2553 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002554 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2555 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 return INVALID_OPERATION;
2557 }
2558
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002559 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002560
2561 sp<Camera3OutputStreamInterface> dummyStream =
2562 new Camera3DummyStream(mNextStreamId);
2563
2564 res = mOutputStreams.add(mNextStreamId, dummyStream);
2565 if (res < 0) {
2566 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2567 return res;
2568 }
2569
2570 mDummyStreamId = mNextStreamId;
2571 mNextStreamId++;
2572
2573 return OK;
2574}
2575
2576status_t Camera3Device::tryRemoveDummyStreamLocked() {
2577 ATRACE_CALL();
2578 status_t res;
2579
2580 if (mDummyStreamId == NO_STREAM) return OK;
2581 if (mOutputStreams.size() == 1) return OK;
2582
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002583 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584
2585 // Ok, have a dummy stream and there's at least one other output stream,
2586 // so remove the dummy
2587
2588 sp<Camera3StreamInterface> deletedStream;
2589 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2590 if (outputStreamIdx == NAME_NOT_FOUND) {
2591 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2592 return INVALID_OPERATION;
2593 }
2594
2595 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2596 mOutputStreams.removeItemsAt(outputStreamIdx);
2597
2598 // Free up the stream endpoint so that it can be used by some other stream
2599 res = deletedStream->disconnect();
2600 if (res != OK) {
2601 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2602 // fall through since we want to still list the stream as deleted.
2603 }
2604 mDeletedStreams.add(deletedStream);
2605 mDummyStreamId = NO_STREAM;
2606
2607 return res;
2608}
2609
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002610void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002611 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002612 Mutex::Autolock l(mLock);
2613 va_list args;
2614 va_start(args, fmt);
2615
2616 setErrorStateLockedV(fmt, args);
2617
2618 va_end(args);
2619}
2620
2621void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002622 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002623 Mutex::Autolock l(mLock);
2624 setErrorStateLockedV(fmt, args);
2625}
2626
2627void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2628 va_list args;
2629 va_start(args, fmt);
2630
2631 setErrorStateLockedV(fmt, args);
2632
2633 va_end(args);
2634}
2635
2636void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002637 // Print out all error messages to log
2638 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002639 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002640
2641 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002642 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002643
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002644 mErrorCause = errorCause;
2645
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002646 if (mRequestThread != nullptr) {
2647 mRequestThread->setPaused(true);
2648 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002649 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002650
2651 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002652 sp<NotificationListener> listener = mListener.promote();
2653 if (listener != NULL) {
2654 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002655 CaptureResultExtras());
2656 }
2657
2658 // Save stack trace. View by dumping it later.
2659 CameraTraces::saveTrace();
2660 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002661}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662
2663/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002664 * In-flight request management
2665 */
2666
Jianing Weicb0652e2014-03-12 18:29:36 -07002667status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002668 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002669 bool hasAppCallback, nsecs_t maxExpectedDuration,
2670 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002671 ATRACE_CALL();
2672 Mutex::Autolock l(mInFlightLock);
2673
2674 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002675 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002676 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002677 if (res < 0) return res;
2678
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002679 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002680 // hold mLock to prevent race with disconnect
2681 Mutex::Autolock l(mLock);
2682 if (mStatusTracker != nullptr) {
2683 mStatusTracker->markComponentActive(mInFlightStatusId);
2684 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002685 }
2686
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002687 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002688 return OK;
2689}
2690
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002691void Camera3Device::returnOutputBuffers(
2692 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2693 nsecs_t timestamp) {
2694 for (size_t i = 0; i < numBuffers; i++)
2695 {
2696 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2697 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2698 // Note: stream may be deallocated at this point, if this buffer was
2699 // the last reference to it.
2700 if (res != OK) {
2701 ALOGE("Can't return buffer to its stream: %s (%d)",
2702 strerror(-res), res);
2703 }
2704 }
2705}
2706
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002707void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002708 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002709 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002710 mInFlightMap.removeItemsAt(idx, 1);
2711
2712 // Indicate idle inFlightMap to the status tracker
2713 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002714 // hold mLock to prevent race with disconnect
2715 Mutex::Autolock l(mLock);
2716 if (mStatusTracker != nullptr) {
2717 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2718 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002719 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002720 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002721}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002722
2723void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2724
2725 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2726 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2727
2728 nsecs_t sensorTimestamp = request.sensorTimestamp;
2729 nsecs_t shutterTimestamp = request.shutterTimestamp;
2730
2731 // Check if it's okay to remove the request from InFlightMap:
2732 // In the case of a successful request:
2733 // all input and output buffers, all result metadata, shutter callback
2734 // arrived.
2735 // In the case of a unsuccessful request:
2736 // all input and output buffers arrived.
2737 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002738 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002739 (request.haveResultMetadata && shutterTimestamp != 0))) {
2740 ATRACE_ASYNC_END("frame capture", frameNumber);
2741
Shuzhen Wang403044a2017-02-26 23:29:04 -08002742 // Sanity check - if sensor timestamp matches shutter timestamp in the
2743 // case of request having callback.
2744 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002745 sensorTimestamp != shutterTimestamp) {
2746 SET_ERR("sensor timestamp (%" PRId64
2747 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2748 sensorTimestamp, frameNumber, shutterTimestamp);
2749 }
2750
2751 // for an unsuccessful request, it may have pending output buffers to
2752 // return.
2753 assert(request.requestStatus != OK ||
2754 request.pendingOutputBuffers.size() == 0);
2755 returnOutputBuffers(request.pendingOutputBuffers.array(),
2756 request.pendingOutputBuffers.size(), 0);
2757
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002758 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002759 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2760 }
2761
2762 // Sanity check - if we have too many in-flight frames, something has
2763 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002764 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002765 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002766 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2767 kInFlightWarnLimitHighSpeed) {
2768 CLOGE("In-flight list too large for high speed configuration: %zu",
2769 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002770 }
2771}
2772
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002773void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002774 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002775 { // First return buffers cached in mInFlightMap
2776 Mutex::Autolock l(mInFlightLock);
2777 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2778 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2779 returnOutputBuffers(request.pendingOutputBuffers.array(),
2780 request.pendingOutputBuffers.size(), 0);
2781 }
2782 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002783 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002784 }
2785
2786 // Then return all inflight buffers not returned by HAL
2787 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2788 mInterface->getInflightBufferKeys(&inflightKeys);
2789
2790 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2791 for (auto& pair : inflightKeys) {
2792 int32_t frameNumber = pair.first;
2793 int32_t streamId = pair.second;
2794 buffer_handle_t* buffer;
2795 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2796 if (res != OK) {
2797 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2798 __FUNCTION__, frameNumber, streamId);
2799 continue;
2800 }
2801
2802 camera3_stream_buffer_t streamBuffer;
2803 streamBuffer.buffer = buffer;
2804 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2805 streamBuffer.acquire_fence = -1;
2806 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002807
2808 // First check if the buffer belongs to deleted stream
2809 bool streamDeleted = false;
2810 for (auto& stream : mDeletedStreams) {
2811 if (streamId == stream->getId()) {
2812 streamDeleted = true;
2813 // Return buffer to deleted stream
2814 camera3_stream* halStream = stream->asHalStream();
2815 streamBuffer.stream = halStream;
2816 switch (halStream->stream_type) {
2817 case CAMERA3_STREAM_OUTPUT:
2818 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2819 if (res != OK) {
2820 ALOGE("%s: Can't return output buffer for frame %d to"
2821 " stream %d: %s (%d)", __FUNCTION__,
2822 frameNumber, streamId, strerror(-res), res);
2823 }
2824 break;
2825 case CAMERA3_STREAM_INPUT:
2826 res = stream->returnInputBuffer(streamBuffer);
2827 if (res != OK) {
2828 ALOGE("%s: Can't return input buffer for frame %d to"
2829 " stream %d: %s (%d)", __FUNCTION__,
2830 frameNumber, streamId, strerror(-res), res);
2831 }
2832 break;
2833 default: // Bi-direcitonal stream is deprecated
2834 ALOGE("%s: stream %d has unknown stream type %d",
2835 __FUNCTION__, streamId, halStream->stream_type);
2836 break;
2837 }
2838 break;
2839 }
2840 }
2841 if (streamDeleted) {
2842 continue;
2843 }
2844
2845 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002846 if (streamId == inputStreamId) {
2847 streamBuffer.stream = mInputStream->asHalStream();
2848 res = mInputStream->returnInputBuffer(streamBuffer);
2849 if (res != OK) {
2850 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002851 " stream %d: %s (%d)", __FUNCTION__,
2852 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002853 }
2854 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002855 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2856 if (idx == NAME_NOT_FOUND) {
2857 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2858 continue;
2859 }
2860 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002861 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2862 }
2863 }
2864}
2865
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002866void Camera3Device::insertResultLocked(CaptureResult *result,
2867 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002868 if (result == nullptr) return;
2869
Emilian Peev71c73a22017-03-21 16:35:51 +00002870 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2871 result->mMetadata.getAndLock());
2872 set_camera_metadata_vendor_id(meta, mVendorTagId);
2873 result->mMetadata.unlock(meta);
2874
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002875 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2876 (int32_t*)&frameNumber, 1) != OK) {
2877 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2878 return;
2879 }
2880
2881 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2882 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2883 return;
2884 }
2885
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002886 // Valid result, insert into queue
2887 List<CaptureResult>::iterator queuedResult =
2888 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2889 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2890 ", burstId = %" PRId32, __FUNCTION__,
2891 queuedResult->mResultExtras.requestId,
2892 queuedResult->mResultExtras.frameNumber,
2893 queuedResult->mResultExtras.burstId);
2894
2895 mResultSignal.signal();
2896}
2897
2898
2899void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002900 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002901 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002902 Mutex::Autolock l(mOutputLock);
2903
2904 CaptureResult captureResult;
2905 captureResult.mResultExtras = resultExtras;
2906 captureResult.mMetadata = partialResult;
2907
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002908 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002909}
2910
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002911
2912void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2913 CaptureResultExtras &resultExtras,
2914 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002915 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002916 bool reprocess,
2917 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002918 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002919 if (pendingMetadata.isEmpty())
2920 return;
2921
2922 Mutex::Autolock l(mOutputLock);
2923
2924 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002925 if (reprocess) {
2926 if (frameNumber < mNextReprocessResultFrameNumber) {
2927 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002928 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002929 frameNumber, mNextReprocessResultFrameNumber);
2930 return;
2931 }
2932 mNextReprocessResultFrameNumber = frameNumber + 1;
2933 } else {
2934 if (frameNumber < mNextResultFrameNumber) {
2935 SET_ERR("Out-of-order capture result metadata submitted! "
2936 "(got frame number %d, expecting %d)",
2937 frameNumber, mNextResultFrameNumber);
2938 return;
2939 }
2940 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002941 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002942
2943 CaptureResult captureResult;
2944 captureResult.mResultExtras = resultExtras;
2945 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002946 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002947
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002948 // Append any previous partials to form a complete result
2949 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2950 captureResult.mMetadata.append(collectedPartialResult);
2951 }
2952
2953 captureResult.mMetadata.sort();
2954
2955 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002956 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2957 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002958 SET_ERR("No timestamp provided by HAL for frame %d!",
2959 frameNumber);
2960 return;
2961 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002962 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
2963 camera_metadata_entry timestamp =
2964 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2965 if (timestamp.count == 0) {
2966 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
2967 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
2968 return;
2969 }
2970 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002971
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002972 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2973 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2974
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002975 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002976}
2977
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002978/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002979 * Camera HAL device callback methods
2980 */
2981
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002982void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002983 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002984
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002985 status_t res;
2986
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002987 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002988 if (result->result == NULL && result->num_output_buffers == 0 &&
2989 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002990 SET_ERR("No result data provided by HAL for frame %d",
2991 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002992 return;
2993 }
Zhijun He204e3292014-07-14 17:09:23 -07002994
Zhijun He204e3292014-07-14 17:09:23 -07002995 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002996 result->result != NULL &&
2997 result->partial_result != 1) {
2998 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2999 " if partial result is not supported",
3000 frameNumber, result->partial_result);
3001 return;
3002 }
3003
3004 bool isPartialResult = false;
3005 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003006 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003007
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003008 // Get shutter timestamp and resultExtras from list of in-flight requests,
3009 // where it was added by the shutter notification for this frame. If the
3010 // shutter timestamp isn't received yet, append the output buffers to the
3011 // in-flight request and they will be returned when the shutter timestamp
3012 // arrives. Update the in-flight status and remove the in-flight entry if
3013 // all result data and shutter timestamp have been received.
3014 nsecs_t shutterTimestamp = 0;
3015
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003016 {
3017 Mutex::Autolock l(mInFlightLock);
3018 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3019 if (idx == NAME_NOT_FOUND) {
3020 SET_ERR("Unknown frame number for capture result: %d",
3021 frameNumber);
3022 return;
3023 }
3024 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3026 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003027 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003028 __FUNCTION__, request.resultExtras.requestId,
3029 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003030 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003031 // Always update the partial count to the latest one if it's not 0
3032 // (buffers only). When framework aggregates adjacent partial results
3033 // into one, the latest partial count will be used.
3034 if (result->partial_result != 0)
3035 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003036
3037 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003038 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003039 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3040 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3041 " the range of [1, %d] when metadata is included in the result",
3042 frameNumber, result->partial_result, mNumPartialResults);
3043 return;
3044 }
3045 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003046 if (isPartialResult && result->num_physcam_metadata) {
3047 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3048 " physical camera result", frameNumber);
3049 return;
3050 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003051 if (isPartialResult) {
3052 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003053 }
3054
Shuzhen Wang4a472662017-02-26 23:29:04 -08003055 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003056 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003057 sendPartialCaptureResult(result->result, request.resultExtras,
3058 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003059 }
3060 }
3061
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003062 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003063 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003064
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003065 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003066 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003067 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3068 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3069 request.physicalCameraIds.size(), result->num_physcam_metadata);
3070 return;
3071 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003072 if (request.haveResultMetadata) {
3073 SET_ERR("Called multiple times with metadata for frame %d",
3074 frameNumber);
3075 return;
3076 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003077 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3078 String8 physicalId(result->physcam_ids[i]);
3079 std::set<String8>::iterator cameraIdIter =
3080 request.physicalCameraIds.find(physicalId);
3081 if (cameraIdIter != request.physicalCameraIds.end()) {
3082 request.physicalCameraIds.erase(cameraIdIter);
3083 } else {
3084 SET_ERR("Total result for frame %d has already returned for camera %s",
3085 frameNumber, physicalId.c_str());
3086 return;
3087 }
3088 }
Zhijun He204e3292014-07-14 17:09:23 -07003089 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003090 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003091 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003092 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003093 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003094 request.haveResultMetadata = true;
3095 }
3096
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003097 uint32_t numBuffersReturned = result->num_output_buffers;
3098 if (result->input_buffer != NULL) {
3099 if (hasInputBufferInRequest) {
3100 numBuffersReturned += 1;
3101 } else {
3102 ALOGW("%s: Input buffer should be NULL if there is no input"
3103 " buffer sent in the request",
3104 __FUNCTION__);
3105 }
3106 }
3107 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003108 if (request.numBuffersLeft < 0) {
3109 SET_ERR("Too many buffers returned for frame %d",
3110 frameNumber);
3111 return;
3112 }
3113
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003114 camera_metadata_ro_entry_t entry;
3115 res = find_camera_metadata_ro_entry(result->result,
3116 ANDROID_SENSOR_TIMESTAMP, &entry);
3117 if (res == OK && entry.count == 1) {
3118 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003119 }
3120
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003121 // If shutter event isn't received yet, append the output buffers to
3122 // the in-flight request. Otherwise, return the output buffers to
3123 // streams.
3124 if (shutterTimestamp == 0) {
3125 request.pendingOutputBuffers.appendArray(result->output_buffers,
3126 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003127 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003128 returnOutputBuffers(result->output_buffers,
3129 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003130 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003131
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003132 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003133 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3134 CameraMetadata physicalMetadata;
3135 physicalMetadata.append(result->physcam_metadata[i]);
3136 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3137 physicalMetadata});
3138 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003139 if (shutterTimestamp == 0) {
3140 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003141 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003142 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003143 CameraMetadata metadata;
3144 metadata = result->result;
3145 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003146 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003147 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003148 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003149 }
3150
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003151 removeInFlightRequestIfReadyLocked(idx);
3152 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003153
Zhijun Hef0d962a2014-06-30 10:24:11 -07003154 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003155 if (hasInputBufferInRequest) {
3156 Camera3Stream *stream =
3157 Camera3Stream::cast(result->input_buffer->stream);
3158 res = stream->returnInputBuffer(*(result->input_buffer));
3159 // Note: stream may be deallocated at this point, if this buffer was the
3160 // last reference to it.
3161 if (res != OK) {
3162 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3163 " its stream:%s (%d)", __FUNCTION__,
3164 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003165 }
3166 } else {
3167 ALOGW("%s: Input buffer should be NULL if there is no input"
3168 " buffer sent in the request, skipping input buffer return.",
3169 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003170 }
3171 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003172}
3173
3174void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003175 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003176 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003177 {
3178 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003179 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003180 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003181
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003182 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003183 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003184 return;
3185 }
3186
3187 switch (msg->type) {
3188 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003189 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003190 break;
3191 }
3192 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003193 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003194 break;
3195 }
3196 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003197 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003198 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003199 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003200}
3201
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003202void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003203 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003204 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003205 // Map camera HAL error codes to ICameraDeviceCallback error codes
3206 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003207 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003208 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003209 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003210 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003211 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003212 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003213 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003214 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003215 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003216 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003217 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003218 };
3219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003220 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003221 ((msg.error_code >= 0) &&
3222 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3223 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003224 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003225
3226 int streamId = 0;
3227 if (msg.error_stream != NULL) {
3228 Camera3Stream *stream =
3229 Camera3Stream::cast(msg.error_stream);
3230 streamId = stream->getId();
3231 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003232 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3233 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003234 streamId, msg.error_code);
3235
3236 CaptureResultExtras resultExtras;
3237 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003238 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003239 // SET_ERR calls notifyError
3240 SET_ERR("Camera HAL reported serious device error");
3241 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003242 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3243 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3244 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003245 {
3246 Mutex::Autolock l(mInFlightLock);
3247 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3248 if (idx >= 0) {
3249 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3250 r.requestStatus = msg.error_code;
3251 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003252 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3253 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3254 errorCode) {
3255 r.skipResultMetadata = true;
3256 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003257 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3258 errorCode) {
3259 // In case of missing result check whether the buffers
3260 // returned. If they returned, then remove inflight
3261 // request.
3262 removeInFlightRequestIfReadyLocked(idx);
3263 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003264 } else {
3265 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003266 ALOGE("Camera %s: %s: cannot find in-flight request on "
3267 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003268 resultExtras.frameNumber);
3269 }
3270 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003271 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003272 if (listener != NULL) {
3273 listener->notifyError(errorCode, resultExtras);
3274 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003275 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003276 }
3277 break;
3278 default:
3279 // SET_ERR calls notifyError
3280 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3281 break;
3282 }
3283}
3284
3285void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003286 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003287 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003289
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003290 // Set timestamp for the request in the in-flight tracking
3291 // and get the request ID to send upstream
3292 {
3293 Mutex::Autolock l(mInFlightLock);
3294 idx = mInFlightMap.indexOfKey(msg.frame_number);
3295 if (idx >= 0) {
3296 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003297
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003298 // Verify ordering of shutter notifications
3299 {
3300 Mutex::Autolock l(mOutputLock);
3301 // TODO: need to track errors for tighter bounds on expected frame number.
3302 if (r.hasInputBuffer) {
3303 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3304 SET_ERR("Shutter notification out-of-order. Expected "
3305 "notification for frame %d, got frame %d",
3306 mNextReprocessShutterFrameNumber, msg.frame_number);
3307 return;
3308 }
3309 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3310 } else {
3311 if (msg.frame_number < mNextShutterFrameNumber) {
3312 SET_ERR("Shutter notification out-of-order. Expected "
3313 "notification for frame %d, got frame %d",
3314 mNextShutterFrameNumber, msg.frame_number);
3315 return;
3316 }
3317 mNextShutterFrameNumber = msg.frame_number + 1;
3318 }
3319 }
3320
Shuzhen Wang4a472662017-02-26 23:29:04 -08003321 r.shutterTimestamp = msg.timestamp;
3322 if (r.hasCallback) {
3323 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003324 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003325 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003326 // Call listener, if any
3327 if (listener != NULL) {
3328 listener->notifyShutter(r.resultExtras, msg.timestamp);
3329 }
3330 // send pending result and buffers
3331 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3332 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003333 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003334 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003335 returnOutputBuffers(r.pendingOutputBuffers.array(),
3336 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3337 r.pendingOutputBuffers.clear();
3338
3339 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003340 }
3341 }
3342 if (idx < 0) {
3343 SET_ERR("Shutter notification for non-existent frame number %d",
3344 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003345 }
3346}
3347
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003348CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003349 ALOGV("%s", __FUNCTION__);
3350
Igor Murashkin1e479c02013-09-06 16:55:14 -07003351 CameraMetadata retVal;
3352
3353 if (mRequestThread != NULL) {
3354 retVal = mRequestThread->getLatestRequest();
3355 }
3356
Igor Murashkin1e479c02013-09-06 16:55:14 -07003357 return retVal;
3358}
3359
Jianing Weicb0652e2014-03-12 18:29:36 -07003360
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003361void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3362 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3363 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3364}
3365
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003366/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003367 * HalInterface inner class methods
3368 */
3369
Yifan Hongf79b5542017-04-11 14:44:25 -07003370Camera3Device::HalInterface::HalInterface(
3371 sp<ICameraDeviceSession> &session,
3372 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003373 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003374 mRequestMetadataQueue(queue) {
3375 // Check with hardware service manager if we can downcast these interfaces
3376 // Somewhat expensive, so cache the results at startup
3377 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3378 if (castResult_3_4.isOk()) {
3379 mHidlSession_3_4 = castResult_3_4;
3380 }
3381 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3382 if (castResult_3_3.isOk()) {
3383 mHidlSession_3_3 = castResult_3_3;
3384 }
3385}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003386
Emilian Peev31abd0a2017-05-11 18:37:46 +01003387Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003388
3389Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003390 mHidlSession(other.mHidlSession),
3391 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003392
3393bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003394 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003395}
3396
3397void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003398 mHidlSession_3_4.clear();
3399 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003400 mHidlSession.clear();
3401}
3402
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003403bool Camera3Device::HalInterface::supportBatchRequest() {
3404 return mHidlSession != nullptr;
3405}
3406
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003407status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3408 camera3_request_template_t templateId,
3409 /*out*/ camera_metadata_t **requestTemplate) {
3410 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3411 if (!valid()) return INVALID_OPERATION;
3412 status_t res = OK;
3413
Emilian Peev31abd0a2017-05-11 18:37:46 +01003414 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003415
3416 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003417 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003418 status = s;
3419 if (status == common::V1_0::Status::OK) {
3420 const camera_metadata *r =
3421 reinterpret_cast<const camera_metadata_t*>(request.data());
3422 size_t expectedSize = request.size();
3423 int ret = validate_camera_metadata_structure(r, &expectedSize);
3424 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3425 *requestTemplate = clone_camera_metadata(r);
3426 if (*requestTemplate == nullptr) {
3427 ALOGE("%s: Unable to clone camera metadata received from HAL",
3428 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003429 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003431 } else {
3432 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3433 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003434 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003435 }
3436 };
3437 hardware::Return<void> err;
3438 if (mHidlSession_3_4 != nullptr) {
3439 device::V3_4::RequestTemplate id;
3440 switch (templateId) {
3441 case CAMERA3_TEMPLATE_PREVIEW:
3442 id = device::V3_4::RequestTemplate::PREVIEW;
3443 break;
3444 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3445 id = device::V3_4::RequestTemplate::STILL_CAPTURE;
3446 break;
3447 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3448 id = device::V3_4::RequestTemplate::VIDEO_RECORD;
3449 break;
3450 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3451 id = device::V3_4::RequestTemplate::VIDEO_SNAPSHOT;
3452 break;
3453 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3454 id = device::V3_4::RequestTemplate::ZERO_SHUTTER_LAG;
3455 break;
3456 case CAMERA3_TEMPLATE_MANUAL:
3457 id = device::V3_4::RequestTemplate::MANUAL;
3458 break;
3459 case CAMERA3_TEMPLATE_MOTION_TRACKING_PREVIEW:
3460 id = device::V3_4::RequestTemplate::MOTION_TRACKING_PREVIEW;
3461 break;
3462 case CAMERA3_TEMPLATE_MOTION_TRACKING_BEST:
3463 id = device::V3_4::RequestTemplate::MOTION_TRACKING_BEST;
3464 break;
3465 default:
3466 // Unknown template ID
3467 return BAD_VALUE;
3468 }
3469 err = mHidlSession_3_4->constructDefaultRequestSettings_3_4(id, requestCallback);
3470 } else {
3471 RequestTemplate id;
3472 switch (templateId) {
3473 case CAMERA3_TEMPLATE_PREVIEW:
3474 id = RequestTemplate::PREVIEW;
3475 break;
3476 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3477 id = RequestTemplate::STILL_CAPTURE;
3478 break;
3479 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3480 id = RequestTemplate::VIDEO_RECORD;
3481 break;
3482 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3483 id = RequestTemplate::VIDEO_SNAPSHOT;
3484 break;
3485 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3486 id = RequestTemplate::ZERO_SHUTTER_LAG;
3487 break;
3488 case CAMERA3_TEMPLATE_MANUAL:
3489 id = RequestTemplate::MANUAL;
3490 break;
3491 default:
3492 // Unknown template ID, or this HAL is too old to support it
3493 return BAD_VALUE;
3494 }
3495 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
3496 }
3497
Emilian Peev31abd0a2017-05-11 18:37:46 +01003498 if (!err.isOk()) {
3499 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3500 res = DEAD_OBJECT;
3501 } else {
3502 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003503 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003505 return res;
3506}
3507
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003508status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003509 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003510 ATRACE_NAME("CameraHal::configureStreams");
3511 if (!valid()) return INVALID_OPERATION;
3512 status_t res = OK;
3513
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514 // Convert stream config to HIDL
3515 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003516 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3517 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3518 requestedConfiguration3_2.streams.resize(config->num_streams);
3519 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003520 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003521 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3522 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003524
Emilian Peev31abd0a2017-05-11 18:37:46 +01003525 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3526 cam3stream->setBufferFreedListener(this);
3527 int streamId = cam3stream->getId();
3528 StreamType streamType;
3529 switch (src->stream_type) {
3530 case CAMERA3_STREAM_OUTPUT:
3531 streamType = StreamType::OUTPUT;
3532 break;
3533 case CAMERA3_STREAM_INPUT:
3534 streamType = StreamType::INPUT;
3535 break;
3536 default:
3537 ALOGE("%s: Stream %d: Unsupported stream type %d",
3538 __FUNCTION__, streamId, config->streams[i]->stream_type);
3539 return BAD_VALUE;
3540 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003541 dst3_2.id = streamId;
3542 dst3_2.streamType = streamType;
3543 dst3_2.width = src->width;
3544 dst3_2.height = src->height;
3545 dst3_2.format = mapToPixelFormat(src->format);
3546 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3547 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3548 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3549 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003550 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003551 if (src->physical_camera_id != nullptr) {
3552 dst3_4.physicalCameraId = src->physical_camera_id;
3553 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003554
3555 activeStreams.insert(streamId);
3556 // Create Buffer ID map if necessary
3557 if (mBufferIdMaps.count(streamId) == 0) {
3558 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3559 }
3560 }
3561 // remove BufferIdMap for deleted streams
3562 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3563 int streamId = it->first;
3564 bool active = activeStreams.count(streamId) > 0;
3565 if (!active) {
3566 it = mBufferIdMaps.erase(it);
3567 } else {
3568 ++it;
3569 }
3570 }
3571
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003572 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003573 res = mapToStreamConfigurationMode(
3574 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003575 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003576 if (res != OK) {
3577 return res;
3578 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003579 requestedConfiguration3_2.operationMode = operationMode;
3580 requestedConfiguration3_4.operationMode = operationMode;
3581 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003582 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3583 get_camera_metadata_size(sessionParams));
3584
Emilian Peev31abd0a2017-05-11 18:37:46 +01003585 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003586 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003587 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003588
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003589 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003590 if (mHidlSession_3_4 != nullptr) {
3591 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003592 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003593 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003594 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003595 [&status, &finalConfiguration3_4]
3596 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3597 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003598 status = s;
3599 });
3600 if (!err.isOk()) {
3601 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3602 return DEAD_OBJECT;
3603 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003604 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3605 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3606 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3607 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003608 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003609 // We do; use v3.3 for the call
3610 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003611 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003612 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003613 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003614 finalConfiguration = halConfiguration;
3615 status = s;
3616 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003617 if (!err.isOk()) {
3618 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3619 return DEAD_OBJECT;
3620 }
3621 } else {
3622 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3623 ALOGV("%s: v3.2 device found", __FUNCTION__);
3624 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003625 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003626 [&status, &finalConfiguration_3_2]
3627 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3628 finalConfiguration_3_2 = halConfiguration;
3629 status = s;
3630 });
3631 if (!err.isOk()) {
3632 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3633 return DEAD_OBJECT;
3634 }
3635 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3636 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3637 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3638 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003639 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003640 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003641 }
3642
3643 if (status != common::V1_0::Status::OK ) {
3644 return CameraProviderManager::mapToStatusT(status);
3645 }
3646
3647 // And convert output stream configuration from HIDL
3648
3649 for (size_t i = 0; i < config->num_streams; i++) {
3650 camera3_stream_t *dst = config->streams[i];
3651 int streamId = Camera3Stream::cast(dst)->getId();
3652
3653 // Start scan at i, with the assumption that the stream order matches
3654 size_t realIdx = i;
3655 bool found = false;
3656 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003657 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003658 found = true;
3659 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003660 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003661 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3662 }
3663 if (!found) {
3664 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3665 __FUNCTION__, streamId);
3666 return INVALID_OPERATION;
3667 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003668 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003669
Emilian Peev710c1422017-08-30 11:19:38 +01003670 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3671 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003672 dstStream->setDataSpaceOverride(false);
3673 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3674 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3675
Emilian Peev31abd0a2017-05-11 18:37:46 +01003676 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3677 if (dst->format != overrideFormat) {
3678 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3679 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003680 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003681 if (dst->data_space != overrideDataSpace) {
3682 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3683 streamId, dst->format);
3684 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003685 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003686 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003687 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3688
Emilian Peev31abd0a2017-05-11 18:37:46 +01003689 // Override allowed with IMPLEMENTATION_DEFINED
3690 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003691 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003692 }
3693
Emilian Peev31abd0a2017-05-11 18:37:46 +01003694 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003695 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003696 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003697 __FUNCTION__, streamId);
3698 return INVALID_OPERATION;
3699 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003700 dstStream->setUsage(
3701 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003702 } else {
3703 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003704 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003705 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3706 __FUNCTION__, streamId);
3707 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003708 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003709 dstStream->setUsage(
3710 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003711 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003712 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003713 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003714
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003715 return res;
3716}
3717
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003718void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3719 /*out*/device::V3_2::CaptureRequest* captureRequest,
3720 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003721 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722 if (captureRequest == nullptr || handlesCreated == nullptr) {
3723 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3724 __FUNCTION__, captureRequest, handlesCreated);
3725 return;
3726 }
3727
3728 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003729
3730 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003731
3732 {
3733 std::lock_guard<std::mutex> lock(mInflightLock);
3734 if (request->input_buffer != nullptr) {
3735 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3736 buffer_handle_t buf = *(request->input_buffer->buffer);
3737 auto pair = getBufferId(buf, streamId);
3738 bool isNewBuffer = pair.first;
3739 uint64_t bufferId = pair.second;
3740 captureRequest->inputBuffer.streamId = streamId;
3741 captureRequest->inputBuffer.bufferId = bufferId;
3742 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3743 captureRequest->inputBuffer.status = BufferStatus::OK;
3744 native_handle_t *acquireFence = nullptr;
3745 if (request->input_buffer->acquire_fence != -1) {
3746 acquireFence = native_handle_create(1,0);
3747 acquireFence->data[0] = request->input_buffer->acquire_fence;
3748 handlesCreated->push_back(acquireFence);
3749 }
3750 captureRequest->inputBuffer.acquireFence = acquireFence;
3751 captureRequest->inputBuffer.releaseFence = nullptr;
3752
3753 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3754 request->input_buffer->buffer,
3755 request->input_buffer->acquire_fence);
3756 } else {
3757 captureRequest->inputBuffer.streamId = -1;
3758 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3759 }
3760
3761 captureRequest->outputBuffers.resize(request->num_output_buffers);
3762 for (size_t i = 0; i < request->num_output_buffers; i++) {
3763 const camera3_stream_buffer_t *src = request->output_buffers + i;
3764 StreamBuffer &dst = captureRequest->outputBuffers[i];
3765 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3766 buffer_handle_t buf = *(src->buffer);
3767 auto pair = getBufferId(buf, streamId);
3768 bool isNewBuffer = pair.first;
3769 dst.streamId = streamId;
3770 dst.bufferId = pair.second;
3771 dst.buffer = isNewBuffer ? buf : nullptr;
3772 dst.status = BufferStatus::OK;
3773 native_handle_t *acquireFence = nullptr;
3774 if (src->acquire_fence != -1) {
3775 acquireFence = native_handle_create(1,0);
3776 acquireFence->data[0] = src->acquire_fence;
3777 handlesCreated->push_back(acquireFence);
3778 }
3779 dst.acquireFence = acquireFence;
3780 dst.releaseFence = nullptr;
3781
3782 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3783 src->buffer, src->acquire_fence);
3784 }
3785 }
3786}
3787
3788status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3789 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3790 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3791 if (!valid()) return INVALID_OPERATION;
3792
Emilian Peevaebbe412018-01-15 13:53:24 +00003793 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3794 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3795 if (castResult_3_4.isOk()) {
3796 hidlSession_3_4 = castResult_3_4;
3797 }
3798
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003799 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003800 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003801 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003802 if (hidlSession_3_4 != nullptr) {
3803 captureRequests_3_4.resize(batchSize);
3804 } else {
3805 captureRequests.resize(batchSize);
3806 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003807 std::vector<native_handle_t*> handlesCreated;
3808
3809 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003810 if (hidlSession_3_4 != nullptr) {
3811 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3812 /*out*/&handlesCreated);
3813 } else {
3814 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3815 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 }
3817
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003818 std::vector<device::V3_2::BufferCache> cachesToRemove;
3819 {
3820 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3821 for (auto& pair : mFreedBuffers) {
3822 // The stream might have been removed since onBufferFreed
3823 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3824 cachesToRemove.push_back({pair.first, pair.second});
3825 }
3826 }
3827 mFreedBuffers.clear();
3828 }
3829
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003830 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3831 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003832
3833 // Write metadata to FMQ.
3834 for (size_t i = 0; i < batchSize; i++) {
3835 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003836 device::V3_2::CaptureRequest* captureRequest;
3837 if (hidlSession_3_4 != nullptr) {
3838 captureRequest = &captureRequests_3_4[i].v3_2;
3839 } else {
3840 captureRequest = &captureRequests[i];
3841 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003842
3843 if (request->settings != nullptr) {
3844 size_t settingsSize = get_camera_metadata_size(request->settings);
3845 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3846 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3847 captureRequest->settings.resize(0);
3848 captureRequest->fmqSettingsSize = settingsSize;
3849 } else {
3850 if (mRequestMetadataQueue != nullptr) {
3851 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3852 }
3853 captureRequest->settings.setToExternal(
3854 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3855 get_camera_metadata_size(request->settings));
3856 captureRequest->fmqSettingsSize = 0u;
3857 }
3858 } else {
3859 // A null request settings maps to a size-0 CameraMetadata
3860 captureRequest->settings.resize(0);
3861 captureRequest->fmqSettingsSize = 0u;
3862 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003863
3864 if (hidlSession_3_4 != nullptr) {
3865 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3866 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003867 if (request->physcam_settings != nullptr) {
3868 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3869 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3870 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3871 settingsSize)) {
3872 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3873 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3874 settingsSize;
3875 } else {
3876 if (mRequestMetadataQueue != nullptr) {
3877 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3878 }
3879 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3880 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3881 request->physcam_settings[j])),
3882 get_camera_metadata_size(request->physcam_settings[j]));
3883 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003884 }
Emilian Peev00420d22018-02-05 21:33:13 +00003885 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003886 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003887 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003888 }
3889 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3890 request->physcam_id[j];
3891 }
3892 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003893 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003894
3895 hardware::details::return_status err;
3896 if (hidlSession_3_4 != nullptr) {
3897 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003898 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3899 status = s;
3900 *numRequestProcessed = n;
3901 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003902 } else {
3903 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3904 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3905 status = s;
3906 *numRequestProcessed = n;
3907 });
3908 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003909 if (!err.isOk()) {
3910 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3911 return DEAD_OBJECT;
3912 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003913 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3914 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3915 __FUNCTION__, *numRequestProcessed, batchSize);
3916 status = common::V1_0::Status::INTERNAL_ERROR;
3917 }
3918
3919 for (auto& handle : handlesCreated) {
3920 native_handle_delete(handle);
3921 }
3922 return CameraProviderManager::mapToStatusT(status);
3923}
3924
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003925status_t Camera3Device::HalInterface::processCaptureRequest(
3926 camera3_capture_request_t *request) {
3927 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003928 if (!valid()) return INVALID_OPERATION;
3929 status_t res = OK;
3930
Emilian Peev31abd0a2017-05-11 18:37:46 +01003931 uint32_t numRequestProcessed = 0;
3932 std::vector<camera3_capture_request_t*> requests(1);
3933 requests[0] = request;
3934 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3935
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003936 return res;
3937}
3938
3939status_t Camera3Device::HalInterface::flush() {
3940 ATRACE_NAME("CameraHal::flush");
3941 if (!valid()) return INVALID_OPERATION;
3942 status_t res = OK;
3943
Emilian Peev31abd0a2017-05-11 18:37:46 +01003944 auto err = mHidlSession->flush();
3945 if (!err.isOk()) {
3946 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3947 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003948 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003949 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003950 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003951
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003952 return res;
3953}
3954
Emilian Peev31abd0a2017-05-11 18:37:46 +01003955status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003956 ATRACE_NAME("CameraHal::dump");
3957 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003958
Emilian Peev31abd0a2017-05-11 18:37:46 +01003959 // Handled by CameraProviderManager::dump
3960
3961 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003962}
3963
3964status_t Camera3Device::HalInterface::close() {
3965 ATRACE_NAME("CameraHal::close()");
3966 if (!valid()) return INVALID_OPERATION;
3967 status_t res = OK;
3968
Emilian Peev31abd0a2017-05-11 18:37:46 +01003969 auto err = mHidlSession->close();
3970 // Interface will be dead shortly anyway, so don't log errors
3971 if (!err.isOk()) {
3972 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003973 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003974
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003975 return res;
3976}
3977
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003978void Camera3Device::HalInterface::getInflightBufferKeys(
3979 std::vector<std::pair<int32_t, int32_t>>* out) {
3980 std::lock_guard<std::mutex> lock(mInflightLock);
3981 out->clear();
3982 out->reserve(mInflightBufferMap.size());
3983 for (auto& pair : mInflightBufferMap) {
3984 uint64_t key = pair.first;
3985 int32_t streamId = key & 0xFFFFFFFF;
3986 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3987 out->push_back(std::make_pair(frameNumber, streamId));
3988 }
3989 return;
3990}
3991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003993 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003995 auto pair = std::make_pair(buffer, acquireFence);
3996 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997 return OK;
3998}
3999
4000status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004001 int32_t frameNumber, int32_t streamId,
4002 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003 std::lock_guard<std::mutex> lock(mInflightLock);
4004
4005 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4006 auto it = mInflightBufferMap.find(key);
4007 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004008 auto pair = it->second;
4009 *buffer = pair.first;
4010 int acquireFence = pair.second;
4011 if (acquireFence > 0) {
4012 ::close(acquireFence);
4013 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004014 mInflightBufferMap.erase(it);
4015 return OK;
4016}
4017
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004018std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4019 const buffer_handle_t& buf, int streamId) {
4020 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4021
4022 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4023 auto it = bIdMap.find(buf);
4024 if (it == bIdMap.end()) {
4025 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004026 ALOGV("stream %d now have %zu buffer caches, buf %p",
4027 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004028 return std::make_pair(true, mNextBufferId - 1);
4029 } else {
4030 return std::make_pair(false, it->second);
4031 }
4032}
4033
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004034void Camera3Device::HalInterface::onBufferFreed(
4035 int streamId, const native_handle_t* handle) {
4036 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4037 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4038 auto mapIt = mBufferIdMaps.find(streamId);
4039 if (mapIt == mBufferIdMaps.end()) {
4040 // streamId might be from a deleted stream here
4041 ALOGI("%s: stream %d has been removed",
4042 __FUNCTION__, streamId);
4043 return;
4044 }
4045 BufferIdMap& bIdMap = mapIt->second;
4046 auto it = bIdMap.find(handle);
4047 if (it == bIdMap.end()) {
4048 ALOGW("%s: cannot find buffer %p in stream %d",
4049 __FUNCTION__, handle, streamId);
4050 return;
4051 } else {
4052 bufferId = it->second;
4053 bIdMap.erase(it);
4054 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4055 __FUNCTION__, streamId, bIdMap.size(), handle);
4056 }
4057 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4058}
4059
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004060/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004061 * RequestThread inner class methods
4062 */
4063
4064Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004065 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004066 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004067 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004068 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004069 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004070 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004071 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004072 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004073 mReconfigured(false),
4074 mDoPause(false),
4075 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004076 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004077 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004078 mCurrentAfTriggerId(0),
4079 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004080 mRepeatingLastFrameNumber(
4081 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004082 mPrepareVideoStream(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004083 mRequestLatency(kRequestLatencyBinSize),
4084 mSessionParamKeys(sessionParamKeys),
4085 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004086 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004087}
4088
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004089Camera3Device::RequestThread::~RequestThread() {}
4090
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004091void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004092 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004093 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004094 Mutex::Autolock l(mRequestLock);
4095 mListener = listener;
4096}
4097
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004098void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4099 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004100 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004101 Mutex::Autolock l(mRequestLock);
4102 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004103 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004104 // Prepare video stream for high speed recording.
4105 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004106}
4107
Jianing Wei90e59c92014-03-12 18:29:36 -07004108status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004109 List<sp<CaptureRequest> > &requests,
4110 /*out*/
4111 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004112 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004113 Mutex::Autolock l(mRequestLock);
4114 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4115 ++it) {
4116 mRequestQueue.push_back(*it);
4117 }
4118
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004119 if (lastFrameNumber != NULL) {
4120 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4121 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4122 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4123 *lastFrameNumber);
4124 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004125
Jianing Wei90e59c92014-03-12 18:29:36 -07004126 unpauseForNewRequests();
4127
4128 return OK;
4129}
4130
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004131
4132status_t Camera3Device::RequestThread::queueTrigger(
4133 RequestTrigger trigger[],
4134 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004135 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004136 Mutex::Autolock l(mTriggerMutex);
4137 status_t ret;
4138
4139 for (size_t i = 0; i < count; ++i) {
4140 ret = queueTriggerLocked(trigger[i]);
4141
4142 if (ret != OK) {
4143 return ret;
4144 }
4145 }
4146
4147 return OK;
4148}
4149
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004150const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4151 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004152 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004153 if (d != nullptr) return d->mId;
4154 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004155}
4156
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004157status_t Camera3Device::RequestThread::queueTriggerLocked(
4158 RequestTrigger trigger) {
4159
4160 uint32_t tag = trigger.metadataTag;
4161 ssize_t index = mTriggerMap.indexOfKey(tag);
4162
4163 switch (trigger.getTagType()) {
4164 case TYPE_BYTE:
4165 // fall-through
4166 case TYPE_INT32:
4167 break;
4168 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004169 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4170 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004171 return INVALID_OPERATION;
4172 }
4173
4174 /**
4175 * Collect only the latest trigger, since we only have 1 field
4176 * in the request settings per trigger tag, and can't send more than 1
4177 * trigger per request.
4178 */
4179 if (index != NAME_NOT_FOUND) {
4180 mTriggerMap.editValueAt(index) = trigger;
4181 } else {
4182 mTriggerMap.add(tag, trigger);
4183 }
4184
4185 return OK;
4186}
4187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004188status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004189 const RequestList &requests,
4190 /*out*/
4191 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004192 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004193 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004194 if (lastFrameNumber != NULL) {
4195 *lastFrameNumber = mRepeatingLastFrameNumber;
4196 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 mRepeatingRequests.clear();
4198 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4199 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004200
4201 unpauseForNewRequests();
4202
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004203 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004204 return OK;
4205}
4206
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004207bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004208 if (mRepeatingRequests.empty()) {
4209 return false;
4210 }
4211 int32_t requestId = requestIn->mResultExtras.requestId;
4212 const RequestList &repeatRequests = mRepeatingRequests;
4213 // All repeating requests are guaranteed to have same id so only check first quest
4214 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4215 return (firstRequest->mResultExtras.requestId == requestId);
4216}
4217
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004218status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004219 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004221 return clearRepeatingRequestsLocked(lastFrameNumber);
4222
4223}
4224
4225status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004226 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004227 if (lastFrameNumber != NULL) {
4228 *lastFrameNumber = mRepeatingLastFrameNumber;
4229 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004230 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004231 return OK;
4232}
4233
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004234status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004235 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004236 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004237 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004238 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004239
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004240 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004241
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004242 // Send errors for all requests pending in the request queue, including
4243 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004244 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004245 if (listener != NULL) {
4246 for (RequestList::iterator it = mRequestQueue.begin();
4247 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004248 // Abort the input buffers for reprocess requests.
4249 if ((*it)->mInputStream != NULL) {
4250 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004251 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4252 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004253 if (res != OK) {
4254 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4255 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4256 } else {
4257 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4258 if (res != OK) {
4259 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4260 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4261 }
4262 }
4263 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004264 // Set the frame number this request would have had, if it
4265 // had been submitted; this frame number will not be reused.
4266 // The requestId and burstId fields were set when the request was
4267 // submitted originally (in convertMetadataListToRequestListLocked)
4268 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004269 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004270 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004271 }
4272 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004273 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004274
4275 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004276 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004277 if (lastFrameNumber != NULL) {
4278 *lastFrameNumber = mRepeatingLastFrameNumber;
4279 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004280 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004281 return OK;
4282}
4283
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004284status_t Camera3Device::RequestThread::flush() {
4285 ATRACE_CALL();
4286 Mutex::Autolock l(mFlushLock);
4287
Emilian Peev08dd2452017-04-06 16:55:14 +01004288 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004289}
4290
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004291void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004292 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004293 Mutex::Autolock l(mPauseLock);
4294 mDoPause = paused;
4295 mDoPauseSignal.signal();
4296}
4297
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004298status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4299 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004300 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004301 Mutex::Autolock l(mLatestRequestMutex);
4302 status_t res;
4303 while (mLatestRequestId != requestId) {
4304 nsecs_t startTime = systemTime();
4305
4306 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4307 if (res != OK) return res;
4308
4309 timeout -= (systemTime() - startTime);
4310 }
4311
4312 return OK;
4313}
4314
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004315void Camera3Device::RequestThread::requestExit() {
4316 // Call parent to set up shutdown
4317 Thread::requestExit();
4318 // The exit from any possible waits
4319 mDoPauseSignal.signal();
4320 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004321
4322 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4323 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004324}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004325
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004326void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004327 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004328 bool surfaceAbandoned = false;
4329 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004330 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004331 {
4332 Mutex::Autolock l(mRequestLock);
4333 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4334 // repeating requests.
4335 for (const auto& request : mRepeatingRequests) {
4336 for (const auto& s : request->mOutputStreams) {
4337 if (s->isAbandoned()) {
4338 surfaceAbandoned = true;
4339 clearRepeatingRequestsLocked(&lastFrameNumber);
4340 break;
4341 }
4342 }
4343 if (surfaceAbandoned) {
4344 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004345 }
4346 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004347 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004348 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004349
4350 if (listener != NULL && surfaceAbandoned) {
4351 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004352 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004353}
4354
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004355bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004356 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004357 status_t res;
4358 size_t batchSize = mNextRequests.size();
4359 std::vector<camera3_capture_request_t*> requests(batchSize);
4360 uint32_t numRequestProcessed = 0;
4361 for (size_t i = 0; i < batchSize; i++) {
4362 requests[i] = &mNextRequests.editItemAt(i).halRequest;
4363 }
4364
4365 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
4366 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4367
4368 bool triggerRemoveFailed = false;
4369 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4370 for (size_t i = 0; i < numRequestProcessed; i++) {
4371 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4372 nextRequest.submitted = true;
4373
4374
4375 // Update the latest request sent to HAL
4376 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4377 Mutex::Autolock al(mLatestRequestMutex);
4378
4379 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4380 mLatestRequest.acquire(cloned);
4381
4382 sp<Camera3Device> parent = mParent.promote();
4383 if (parent != NULL) {
4384 parent->monitorMetadata(TagMonitor::REQUEST,
4385 nextRequest.halRequest.frame_number,
4386 0, mLatestRequest);
4387 }
4388 }
4389
4390 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004391 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4392 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004393 }
4394
Emilian Peevaebbe412018-01-15 13:53:24 +00004395 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4396
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004397 if (!triggerRemoveFailed) {
4398 // Remove any previously queued triggers (after unlock)
4399 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4400 if (removeTriggerRes != OK) {
4401 triggerRemoveFailed = true;
4402 triggerFailedRequest = nextRequest;
4403 }
4404 }
4405 }
4406
4407 if (triggerRemoveFailed) {
4408 SET_ERR("RequestThread: Unable to remove triggers "
4409 "(capture request %d, HAL device: %s (%d)",
4410 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4411 cleanUpFailedRequests(/*sendRequestError*/ false);
4412 return false;
4413 }
4414
4415 if (res != OK) {
4416 // Should only get a failure here for malformed requests or device-level
4417 // errors, so consider all errors fatal. Bad metadata failures should
4418 // come through notify.
4419 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4420 mNextRequests[numRequestProcessed].halRequest.frame_number,
4421 strerror(-res), res);
4422 cleanUpFailedRequests(/*sendRequestError*/ false);
4423 return false;
4424 }
4425 return true;
4426}
4427
4428bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4429 status_t res;
4430
4431 for (auto& nextRequest : mNextRequests) {
4432 // Submit request and block until ready for next one
4433 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4434 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4435
4436 if (res != OK) {
4437 // Should only get a failure here for malformed requests or device-level
4438 // errors, so consider all errors fatal. Bad metadata failures should
4439 // come through notify.
4440 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4441 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4442 res);
4443 cleanUpFailedRequests(/*sendRequestError*/ false);
4444 return false;
4445 }
4446
4447 // Mark that the request has be submitted successfully.
4448 nextRequest.submitted = true;
4449
4450 // Update the latest request sent to HAL
4451 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4452 Mutex::Autolock al(mLatestRequestMutex);
4453
4454 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4455 mLatestRequest.acquire(cloned);
4456
4457 sp<Camera3Device> parent = mParent.promote();
4458 if (parent != NULL) {
4459 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4460 0, mLatestRequest);
4461 }
4462 }
4463
4464 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004465 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4466 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004467 }
4468
Emilian Peevaebbe412018-01-15 13:53:24 +00004469 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4470
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004471 // Remove any previously queued triggers (after unlock)
4472 res = removeTriggers(mPrevRequest);
4473 if (res != OK) {
4474 SET_ERR("RequestThread: Unable to remove triggers "
4475 "(capture request %d, HAL device: %s (%d)",
4476 nextRequest.halRequest.frame_number, strerror(-res), res);
4477 cleanUpFailedRequests(/*sendRequestError*/ false);
4478 return false;
4479 }
4480 }
4481 return true;
4482}
4483
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004484nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4485 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4486 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4487 find_camera_metadata_ro_entry(request,
4488 ANDROID_CONTROL_AE_MODE,
4489 &e);
4490 if (e.count == 0) return maxExpectedDuration;
4491
4492 switch (e.data.u8[0]) {
4493 case ANDROID_CONTROL_AE_MODE_OFF:
4494 find_camera_metadata_ro_entry(request,
4495 ANDROID_SENSOR_EXPOSURE_TIME,
4496 &e);
4497 if (e.count > 0) {
4498 maxExpectedDuration = e.data.i64[0];
4499 }
4500 find_camera_metadata_ro_entry(request,
4501 ANDROID_SENSOR_FRAME_DURATION,
4502 &e);
4503 if (e.count > 0) {
4504 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4505 }
4506 break;
4507 default:
4508 find_camera_metadata_ro_entry(request,
4509 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4510 &e);
4511 if (e.count > 1) {
4512 maxExpectedDuration = 1e9 / e.data.u8[0];
4513 }
4514 break;
4515 }
4516
4517 return maxExpectedDuration;
4518}
4519
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004520bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4521 ATRACE_CALL();
4522 bool updatesDetected = false;
4523
4524 for (auto tag : mSessionParamKeys) {
4525 camera_metadata_ro_entry entry = settings.find(tag);
4526 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4527
4528 if (entry.count > 0) {
4529 bool isDifferent = false;
4530 if (lastEntry.count > 0) {
4531 // Have a last value, compare to see if changed
4532 if (lastEntry.type == entry.type &&
4533 lastEntry.count == entry.count) {
4534 // Same type and count, compare values
4535 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4536 size_t entryBytes = bytesPerValue * lastEntry.count;
4537 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4538 if (cmp != 0) {
4539 isDifferent = true;
4540 }
4541 } else {
4542 // Count or type has changed
4543 isDifferent = true;
4544 }
4545 } else {
4546 // No last entry, so always consider to be different
4547 isDifferent = true;
4548 }
4549
4550 if (isDifferent) {
4551 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
4552 mLatestSessionParams.update(entry);
4553 updatesDetected = true;
4554 }
4555 } else if (lastEntry.count > 0) {
4556 // Value has been removed
4557 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4558 mLatestSessionParams.erase(tag);
4559 updatesDetected = true;
4560 }
4561 }
4562
4563 return updatesDetected;
4564}
4565
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004566bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004567 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004568 status_t res;
4569
4570 // Handle paused state.
4571 if (waitIfPaused()) {
4572 return true;
4573 }
4574
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004575 // Wait for the next batch of requests.
4576 waitForNextRequestBatch();
4577 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004578 return true;
4579 }
4580
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004581 // Get the latest request ID, if any
4582 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004583 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004584 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004585 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004586 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004587 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004588 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4589 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004590 }
4591
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004592 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4593 // or a single request from streaming or burst. In either case the first element
4594 // should contain the latest camera settings that we need to check for any session
4595 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004596 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004597 res = OK;
4598
4599 //Input stream buffers are already acquired at this point so an input stream
4600 //will not be able to move to idle state unless we force it.
4601 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4602 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4603 if (res != OK) {
4604 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4605 cleanUpFailedRequests(/*sendRequestError*/ false);
4606 return false;
4607 }
4608 }
4609
4610 if (res == OK) {
4611 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4612 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004613 sp<Camera3Device> parent = mParent.promote();
4614 if (parent != nullptr) {
4615 parent->pauseStateNotify(true);
4616 }
4617
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004618 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4619
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004620 if (parent != nullptr) {
4621 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4622 }
4623
4624 statusTracker->markComponentActive(mStatusId);
4625 setPaused(false);
4626 }
4627
4628 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4629 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4630 if (res != OK) {
4631 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4632 cleanUpFailedRequests(/*sendRequestError*/ false);
4633 return false;
4634 }
4635 }
4636 }
4637 }
4638
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004639 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004640 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004641 if (res == TIMED_OUT) {
4642 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004643 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004644 // Check if any stream is abandoned.
4645 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004646 return true;
4647 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004648 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004649 return false;
4650 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004651
Zhijun Hecc27e112013-10-03 16:12:43 -07004652 // Inform waitUntilRequestProcessed thread of a new request ID
4653 {
4654 Mutex::Autolock al(mLatestRequestMutex);
4655
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004656 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004657 mLatestRequestSignal.signal();
4658 }
4659
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004660 // Submit a batch of requests to HAL.
4661 // Use flush lock only when submitting multilple requests in a batch.
4662 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4663 // which may take a long time to finish so synchronizing flush() and
4664 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4665 // For now, only synchronize for high speed recording and we should figure something out for
4666 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004667 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004668
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004669 if (useFlushLock) {
4670 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004671 }
4672
Zhijun Hef0645c12016-08-02 00:58:11 -07004673 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004674 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004675
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004676 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004677 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004678 if (mInterface->supportBatchRequest()) {
4679 submitRequestSuccess = sendRequestsBatch();
4680 } else {
4681 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004682 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004683 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4684 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004685
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004686 if (useFlushLock) {
4687 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004688 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004689
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004690 // Unset as current request
4691 {
4692 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004693 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004694 }
4695
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004696 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004697}
4698
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004699status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004700 ATRACE_CALL();
4701
Shuzhen Wang4a472662017-02-26 23:29:04 -08004702 for (size_t i = 0; i < mNextRequests.size(); i++) {
4703 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004704 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4705 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4706 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4707
4708 // Prepare a request to HAL
4709 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4710
4711 // Insert any queued triggers (before metadata is locked)
4712 status_t res = insertTriggers(captureRequest);
4713
4714 if (res < 0) {
4715 SET_ERR("RequestThread: Unable to insert triggers "
4716 "(capture request %d, HAL device: %s (%d)",
4717 halRequest->frame_number, strerror(-res), res);
4718 return INVALID_OPERATION;
4719 }
4720 int triggerCount = res;
4721 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4722 mPrevTriggers = triggerCount;
4723
4724 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004725 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4726 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004727 /**
4728 * HAL workaround:
4729 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4730 */
4731 res = addDummyTriggerIds(captureRequest);
4732 if (res != OK) {
4733 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4734 "(capture request %d, HAL device: %s (%d)",
4735 halRequest->frame_number, strerror(-res), res);
4736 return INVALID_OPERATION;
4737 }
4738
4739 /**
4740 * The request should be presorted so accesses in HAL
4741 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4742 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004743 captureRequest->mSettingsList.begin()->metadata.sort();
4744 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004745 mPrevRequest = captureRequest;
4746 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4747
4748 IF_ALOGV() {
4749 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4750 find_camera_metadata_ro_entry(
4751 halRequest->settings,
4752 ANDROID_CONTROL_AF_TRIGGER,
4753 &e
4754 );
4755 if (e.count > 0) {
4756 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4757 __FUNCTION__,
4758 halRequest->frame_number,
4759 e.data.u8[0]);
4760 }
4761 }
4762 } else {
4763 // leave request.settings NULL to indicate 'reuse latest given'
4764 ALOGVV("%s: Request settings are REUSED",
4765 __FUNCTION__);
4766 }
4767
Emilian Peevaebbe412018-01-15 13:53:24 +00004768 if (captureRequest->mSettingsList.size() > 1) {
4769 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4770 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004771 if (newRequest) {
4772 halRequest->physcam_settings =
4773 new const camera_metadata* [halRequest->num_physcam_settings];
4774 } else {
4775 halRequest->physcam_settings = nullptr;
4776 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004777 auto it = ++captureRequest->mSettingsList.begin();
4778 size_t i = 0;
4779 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4780 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004781 if (newRequest) {
4782 it->metadata.sort();
4783 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4784 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004785 }
4786 }
4787
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004788 uint32_t totalNumBuffers = 0;
4789
4790 // Fill in buffers
4791 if (captureRequest->mInputStream != NULL) {
4792 halRequest->input_buffer = &captureRequest->mInputBuffer;
4793 totalNumBuffers += 1;
4794 } else {
4795 halRequest->input_buffer = NULL;
4796 }
4797
4798 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4799 captureRequest->mOutputStreams.size());
4800 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004801 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004802 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4803 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004804
4805 // Prepare video buffers for high speed recording on the first video request.
4806 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4807 // Only try to prepare video stream on the first video request.
4808 mPrepareVideoStream = false;
4809
4810 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4811 while (res == NOT_ENOUGH_DATA) {
4812 res = outputStream->prepareNextBuffer();
4813 }
4814 if (res != OK) {
4815 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4816 __FUNCTION__, strerror(-res), res);
4817 outputStream->cancelPrepare();
4818 }
4819 }
4820
Shuzhen Wang4a472662017-02-26 23:29:04 -08004821 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4822 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004823 if (res != OK) {
4824 // Can't get output buffer from gralloc queue - this could be due to
4825 // abandoned queue or other consumer misbehavior, so not a fatal
4826 // error
4827 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4828 " %s (%d)", strerror(-res), res);
4829
4830 return TIMED_OUT;
4831 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004832
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004833 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4834
4835 if (!physicalCameraId.isEmpty()) {
4836 // Physical stream isn't supported for input request.
4837 if (halRequest->input_buffer) {
4838 CLOGE("Physical stream is not supported for input request");
4839 return INVALID_OPERATION;
4840 }
4841 requestedPhysicalCameras.insert(physicalCameraId);
4842 }
4843 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004844 }
4845 totalNumBuffers += halRequest->num_output_buffers;
4846
4847 // Log request in the in-flight queue
4848 sp<Camera3Device> parent = mParent.promote();
4849 if (parent == NULL) {
4850 // Should not happen, and nowhere to send errors to, so just log it
4851 CLOGE("RequestThread: Parent is gone");
4852 return INVALID_OPERATION;
4853 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004854
4855 // If this request list is for constrained high speed recording (not
4856 // preview), and the current request is not the last one in the batch,
4857 // do not send callback to the app.
4858 bool hasCallback = true;
4859 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4860 hasCallback = false;
4861 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004862 res = parent->registerInFlight(halRequest->frame_number,
4863 totalNumBuffers, captureRequest->mResultExtras,
4864 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004865 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004866 calculateMaxExpectedDuration(halRequest->settings),
4867 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004868 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4869 ", burstId = %" PRId32 ".",
4870 __FUNCTION__,
4871 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4872 captureRequest->mResultExtras.burstId);
4873 if (res != OK) {
4874 SET_ERR("RequestThread: Unable to register new in-flight request:"
4875 " %s (%d)", strerror(-res), res);
4876 return INVALID_OPERATION;
4877 }
4878 }
4879
4880 return OK;
4881}
4882
Igor Murashkin1e479c02013-09-06 16:55:14 -07004883CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004884 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004885 Mutex::Autolock al(mLatestRequestMutex);
4886
4887 ALOGV("RequestThread::%s", __FUNCTION__);
4888
4889 return mLatestRequest;
4890}
4891
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004892bool Camera3Device::RequestThread::isStreamPending(
4893 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004894 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004895 Mutex::Autolock l(mRequestLock);
4896
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004897 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004898 if (!nextRequest.submitted) {
4899 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4900 if (stream == s) return true;
4901 }
4902 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004903 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004904 }
4905
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004906 for (const auto& request : mRequestQueue) {
4907 for (const auto& s : request->mOutputStreams) {
4908 if (stream == s) return true;
4909 }
4910 if (stream == request->mInputStream) return true;
4911 }
4912
4913 for (const auto& request : mRepeatingRequests) {
4914 for (const auto& s : request->mOutputStreams) {
4915 if (stream == s) return true;
4916 }
4917 if (stream == request->mInputStream) return true;
4918 }
4919
4920 return false;
4921}
Jianing Weicb0652e2014-03-12 18:29:36 -07004922
Emilian Peev40ead602017-09-26 15:46:36 +01004923bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4924 ATRACE_CALL();
4925 Mutex::Autolock l(mRequestLock);
4926
4927 for (const auto& nextRequest : mNextRequests) {
4928 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4929 if (s.first == streamId) {
4930 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4931 if (it != s.second.end()) {
4932 return true;
4933 }
4934 }
4935 }
4936 }
4937
4938 for (const auto& request : mRequestQueue) {
4939 for (const auto& s : request->mOutputSurfaces) {
4940 if (s.first == streamId) {
4941 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4942 if (it != s.second.end()) {
4943 return true;
4944 }
4945 }
4946 }
4947 }
4948
4949 for (const auto& request : mRepeatingRequests) {
4950 for (const auto& s : request->mOutputSurfaces) {
4951 if (s.first == streamId) {
4952 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4953 if (it != s.second.end()) {
4954 return true;
4955 }
4956 }
4957 }
4958 }
4959
4960 return false;
4961}
4962
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004963nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004964 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004965 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004966 return mExpectedInflightDuration > kMinInflightDuration ?
4967 mExpectedInflightDuration : kMinInflightDuration;
4968}
4969
Emilian Peevaebbe412018-01-15 13:53:24 +00004970void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4971 camera3_capture_request_t *halRequest) {
4972 if ((request == nullptr) || (halRequest == nullptr)) {
4973 ALOGE("%s: Invalid request!", __FUNCTION__);
4974 return;
4975 }
4976
4977 if (halRequest->num_physcam_settings > 0) {
4978 if (halRequest->physcam_id != nullptr) {
4979 delete [] halRequest->physcam_id;
4980 halRequest->physcam_id = nullptr;
4981 }
4982 if (halRequest->physcam_settings != nullptr) {
4983 auto it = ++(request->mSettingsList.begin());
4984 size_t i = 0;
4985 for (; it != request->mSettingsList.end(); it++, i++) {
4986 it->metadata.unlock(halRequest->physcam_settings[i]);
4987 }
4988 delete [] halRequest->physcam_settings;
4989 halRequest->physcam_settings = nullptr;
4990 }
4991 }
4992}
4993
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004994void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4995 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004996 return;
4997 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004998
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004999 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005000 // Skip the ones that have been submitted successfully.
5001 if (nextRequest.submitted) {
5002 continue;
5003 }
5004
5005 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5006 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5007 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5008
5009 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005010 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005011 }
5012
Emilian Peevaebbe412018-01-15 13:53:24 +00005013 cleanupPhysicalSettings(captureRequest, halRequest);
5014
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005015 if (captureRequest->mInputStream != NULL) {
5016 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5017 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5018 }
5019
5020 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005021 //Buffers that failed processing could still have
5022 //valid acquire fence.
5023 int acquireFence = (*outputBuffers)[i].acquire_fence;
5024 if (0 <= acquireFence) {
5025 close(acquireFence);
5026 outputBuffers->editItemAt(i).acquire_fence = -1;
5027 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005028 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5029 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5030 }
5031
5032 if (sendRequestError) {
5033 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005034 sp<NotificationListener> listener = mListener.promote();
5035 if (listener != NULL) {
5036 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005037 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005038 captureRequest->mResultExtras);
5039 }
5040 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005041
5042 // Remove yet-to-be submitted inflight request from inflightMap
5043 {
5044 sp<Camera3Device> parent = mParent.promote();
5045 if (parent != NULL) {
5046 Mutex::Autolock l(parent->mInFlightLock);
5047 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5048 if (idx >= 0) {
5049 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5050 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5051 parent->removeInFlightMapEntryLocked(idx);
5052 }
5053 }
5054 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005055 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005056
5057 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005058 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005059}
5060
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005061void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005062 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005063 // Optimized a bit for the simple steady-state case (single repeating
5064 // request), to avoid putting that request in the queue temporarily.
5065 Mutex::Autolock l(mRequestLock);
5066
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005067 assert(mNextRequests.empty());
5068
5069 NextRequest nextRequest;
5070 nextRequest.captureRequest = waitForNextRequestLocked();
5071 if (nextRequest.captureRequest == nullptr) {
5072 return;
5073 }
5074
5075 nextRequest.halRequest = camera3_capture_request_t();
5076 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005077 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078
5079 // Wait for additional requests
5080 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5081
5082 for (size_t i = 1; i < batchSize; i++) {
5083 NextRequest additionalRequest;
5084 additionalRequest.captureRequest = waitForNextRequestLocked();
5085 if (additionalRequest.captureRequest == nullptr) {
5086 break;
5087 }
5088
5089 additionalRequest.halRequest = camera3_capture_request_t();
5090 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005091 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005092 }
5093
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005094 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005095 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005096 mNextRequests.size(), batchSize);
5097 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005098 }
5099
5100 return;
5101}
5102
5103sp<Camera3Device::CaptureRequest>
5104 Camera3Device::RequestThread::waitForNextRequestLocked() {
5105 status_t res;
5106 sp<CaptureRequest> nextRequest;
5107
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005108 while (mRequestQueue.empty()) {
5109 if (!mRepeatingRequests.empty()) {
5110 // Always atomically enqueue all requests in a repeating request
5111 // list. Guarantees a complete in-sequence set of captures to
5112 // application.
5113 const RequestList &requests = mRepeatingRequests;
5114 RequestList::const_iterator firstRequest =
5115 requests.begin();
5116 nextRequest = *firstRequest;
5117 mRequestQueue.insert(mRequestQueue.end(),
5118 ++firstRequest,
5119 requests.end());
5120 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005121
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005122 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005123
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005124 break;
5125 }
5126
5127 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5128
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005129 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5130 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005131 Mutex::Autolock pl(mPauseLock);
5132 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005133 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005134 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005135 // Let the tracker know
5136 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5137 if (statusTracker != 0) {
5138 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5139 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005140 }
5141 // Stop waiting for now and let thread management happen
5142 return NULL;
5143 }
5144 }
5145
5146 if (nextRequest == NULL) {
5147 // Don't have a repeating request already in hand, so queue
5148 // must have an entry now.
5149 RequestList::iterator firstRequest =
5150 mRequestQueue.begin();
5151 nextRequest = *firstRequest;
5152 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005153 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5154 sp<NotificationListener> listener = mListener.promote();
5155 if (listener != NULL) {
5156 listener->notifyRequestQueueEmpty();
5157 }
5158 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005159 }
5160
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005161 // In case we've been unpaused by setPaused clearing mDoPause, need to
5162 // update internal pause state (capture/setRepeatingRequest unpause
5163 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005164 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005165 if (mPaused) {
5166 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5167 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5168 if (statusTracker != 0) {
5169 statusTracker->markComponentActive(mStatusId);
5170 }
5171 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005172 mPaused = false;
5173
5174 // Check if we've reconfigured since last time, and reset the preview
5175 // request if so. Can't use 'NULL request == repeat' across configure calls.
5176 if (mReconfigured) {
5177 mPrevRequest.clear();
5178 mReconfigured = false;
5179 }
5180
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005181 if (nextRequest != NULL) {
5182 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005183 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5184 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005185
5186 // Since RequestThread::clear() removes buffers from the input stream,
5187 // get the right buffer here before unlocking mRequestLock
5188 if (nextRequest->mInputStream != NULL) {
5189 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5190 if (res != OK) {
5191 // Can't get input buffer from gralloc queue - this could be due to
5192 // disconnected queue or other producer misbehavior, so not a fatal
5193 // error
5194 ALOGE("%s: Can't get input buffer, skipping request:"
5195 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005196
5197 sp<NotificationListener> listener = mListener.promote();
5198 if (listener != NULL) {
5199 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005200 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005201 nextRequest->mResultExtras);
5202 }
5203 return NULL;
5204 }
5205 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005206 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005207
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005208 return nextRequest;
5209}
5210
5211bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005212 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005213 status_t res;
5214 Mutex::Autolock l(mPauseLock);
5215 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005216 if (mPaused == false) {
5217 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005218 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5219 // Let the tracker know
5220 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5221 if (statusTracker != 0) {
5222 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5223 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005226 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005227 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005228 return true;
5229 }
5230 }
5231 // We don't set mPaused to false here, because waitForNextRequest needs
5232 // to further manage the paused state in case of starvation.
5233 return false;
5234}
5235
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005236void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005237 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005238 // With work to do, mark thread as unpaused.
5239 // If paused by request (setPaused), don't resume, to avoid
5240 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005241 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005242 Mutex::Autolock p(mPauseLock);
5243 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005244 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5245 if (mPaused) {
5246 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5247 if (statusTracker != 0) {
5248 statusTracker->markComponentActive(mStatusId);
5249 }
5250 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005251 mPaused = false;
5252 }
5253}
5254
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005255void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5256 sp<Camera3Device> parent = mParent.promote();
5257 if (parent != NULL) {
5258 va_list args;
5259 va_start(args, fmt);
5260
5261 parent->setErrorStateV(fmt, args);
5262
5263 va_end(args);
5264 }
5265}
5266
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005267status_t Camera3Device::RequestThread::insertTriggers(
5268 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005269 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005270 Mutex::Autolock al(mTriggerMutex);
5271
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005272 sp<Camera3Device> parent = mParent.promote();
5273 if (parent == NULL) {
5274 CLOGE("RequestThread: Parent is gone");
5275 return DEAD_OBJECT;
5276 }
5277
Emilian Peevaebbe412018-01-15 13:53:24 +00005278 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005279 size_t count = mTriggerMap.size();
5280
5281 for (size_t i = 0; i < count; ++i) {
5282 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005283 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005284
5285 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5286 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5287 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005288 if (isAeTrigger) {
5289 request->mResultExtras.precaptureTriggerId = triggerId;
5290 mCurrentPreCaptureTriggerId = triggerId;
5291 } else {
5292 request->mResultExtras.afTriggerId = triggerId;
5293 mCurrentAfTriggerId = triggerId;
5294 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005295 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005296 }
5297
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005298 camera_metadata_entry entry = metadata.find(tag);
5299
5300 if (entry.count > 0) {
5301 /**
5302 * Already has an entry for this trigger in the request.
5303 * Rewrite it with our requested trigger value.
5304 */
5305 RequestTrigger oldTrigger = trigger;
5306
5307 oldTrigger.entryValue = entry.data.u8[0];
5308
5309 mTriggerReplacedMap.add(tag, oldTrigger);
5310 } else {
5311 /**
5312 * More typical, no trigger entry, so we just add it
5313 */
5314 mTriggerRemovedMap.add(tag, trigger);
5315 }
5316
5317 status_t res;
5318
5319 switch (trigger.getTagType()) {
5320 case TYPE_BYTE: {
5321 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5322 res = metadata.update(tag,
5323 &entryValue,
5324 /*count*/1);
5325 break;
5326 }
5327 case TYPE_INT32:
5328 res = metadata.update(tag,
5329 &trigger.entryValue,
5330 /*count*/1);
5331 break;
5332 default:
5333 ALOGE("%s: Type not supported: 0x%x",
5334 __FUNCTION__,
5335 trigger.getTagType());
5336 return INVALID_OPERATION;
5337 }
5338
5339 if (res != OK) {
5340 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5341 ", value %d", __FUNCTION__, trigger.getTagName(),
5342 trigger.entryValue);
5343 return res;
5344 }
5345
5346 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5347 trigger.getTagName(),
5348 trigger.entryValue);
5349 }
5350
5351 mTriggerMap.clear();
5352
5353 return count;
5354}
5355
5356status_t Camera3Device::RequestThread::removeTriggers(
5357 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005358 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005359 Mutex::Autolock al(mTriggerMutex);
5360
Emilian Peevaebbe412018-01-15 13:53:24 +00005361 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005362
5363 /**
5364 * Replace all old entries with their old values.
5365 */
5366 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5367 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5368
5369 status_t res;
5370
5371 uint32_t tag = trigger.metadataTag;
5372 switch (trigger.getTagType()) {
5373 case TYPE_BYTE: {
5374 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5375 res = metadata.update(tag,
5376 &entryValue,
5377 /*count*/1);
5378 break;
5379 }
5380 case TYPE_INT32:
5381 res = metadata.update(tag,
5382 &trigger.entryValue,
5383 /*count*/1);
5384 break;
5385 default:
5386 ALOGE("%s: Type not supported: 0x%x",
5387 __FUNCTION__,
5388 trigger.getTagType());
5389 return INVALID_OPERATION;
5390 }
5391
5392 if (res != OK) {
5393 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5394 ", trigger value %d", __FUNCTION__,
5395 trigger.getTagName(), trigger.entryValue);
5396 return res;
5397 }
5398 }
5399 mTriggerReplacedMap.clear();
5400
5401 /**
5402 * Remove all new entries.
5403 */
5404 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5405 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5406 status_t res = metadata.erase(trigger.metadataTag);
5407
5408 if (res != OK) {
5409 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5410 ", trigger value %d", __FUNCTION__,
5411 trigger.getTagName(), trigger.entryValue);
5412 return res;
5413 }
5414 }
5415 mTriggerRemovedMap.clear();
5416
5417 return OK;
5418}
5419
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005420status_t Camera3Device::RequestThread::addDummyTriggerIds(
5421 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005422 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005423 static const int32_t dummyTriggerId = 1;
5424 status_t res;
5425
Emilian Peevaebbe412018-01-15 13:53:24 +00005426 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005427
5428 // If AF trigger is active, insert a dummy AF trigger ID if none already
5429 // exists
5430 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5431 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5432 if (afTrigger.count > 0 &&
5433 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5434 afId.count == 0) {
5435 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5436 if (res != OK) return res;
5437 }
5438
5439 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5440 // if none already exists
5441 camera_metadata_entry pcTrigger =
5442 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5443 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5444 if (pcTrigger.count > 0 &&
5445 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5446 pcId.count == 0) {
5447 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5448 &dummyTriggerId, 1);
5449 if (res != OK) return res;
5450 }
5451
5452 return OK;
5453}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005454
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005455/**
5456 * PreparerThread inner class methods
5457 */
5458
5459Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005460 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005461 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005462}
5463
5464Camera3Device::PreparerThread::~PreparerThread() {
5465 Thread::requestExitAndWait();
5466 if (mCurrentStream != nullptr) {
5467 mCurrentStream->cancelPrepare();
5468 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5469 mCurrentStream.clear();
5470 }
5471 clear();
5472}
5473
Ruben Brunkc78ac262015-08-13 17:58:46 -07005474status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005475 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005476 status_t res;
5477
5478 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005479 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005480
Ruben Brunkc78ac262015-08-13 17:58:46 -07005481 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005482 if (res == OK) {
5483 // No preparation needed, fire listener right off
5484 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005485 if (listener != NULL) {
5486 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005487 }
5488 return OK;
5489 } else if (res != NOT_ENOUGH_DATA) {
5490 return res;
5491 }
5492
5493 // Need to prepare, start up thread if necessary
5494 if (!mActive) {
5495 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5496 // isn't running
5497 Thread::requestExitAndWait();
5498 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5499 if (res != OK) {
5500 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005501 if (listener != NULL) {
5502 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005503 }
5504 return res;
5505 }
5506 mCancelNow = false;
5507 mActive = true;
5508 ALOGV("%s: Preparer stream started", __FUNCTION__);
5509 }
5510
5511 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005512 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005513 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5514
5515 return OK;
5516}
5517
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005518void Camera3Device::PreparerThread::pause() {
5519 ATRACE_CALL();
5520
5521 Mutex::Autolock l(mLock);
5522
5523 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5524 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5525 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5526 int currentMaxCount = mCurrentMaxCount;
5527 mPendingStreams.clear();
5528 mCancelNow = true;
5529 while (mActive) {
5530 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5531 if (res == TIMED_OUT) {
5532 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5533 return;
5534 } else if (res != OK) {
5535 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5536 return;
5537 }
5538 }
5539
5540 //Check whether the prepare thread was able to complete the current
5541 //stream. In case work is still pending emplace it along with the rest
5542 //of the streams in the pending list.
5543 if (currentStream != nullptr) {
5544 if (!mCurrentPrepareComplete) {
5545 pendingStreams.emplace(currentMaxCount, currentStream);
5546 }
5547 }
5548
5549 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5550 for (const auto& it : mPendingStreams) {
5551 it.second->cancelPrepare();
5552 }
5553}
5554
5555status_t Camera3Device::PreparerThread::resume() {
5556 ATRACE_CALL();
5557 status_t res;
5558
5559 Mutex::Autolock l(mLock);
5560 sp<NotificationListener> listener = mListener.promote();
5561
5562 if (mActive) {
5563 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5564 return NO_INIT;
5565 }
5566
5567 auto it = mPendingStreams.begin();
5568 for (; it != mPendingStreams.end();) {
5569 res = it->second->startPrepare(it->first);
5570 if (res == OK) {
5571 if (listener != NULL) {
5572 listener->notifyPrepared(it->second->getId());
5573 }
5574 it = mPendingStreams.erase(it);
5575 } else if (res != NOT_ENOUGH_DATA) {
5576 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5577 res, strerror(-res));
5578 it = mPendingStreams.erase(it);
5579 } else {
5580 it++;
5581 }
5582 }
5583
5584 if (mPendingStreams.empty()) {
5585 return OK;
5586 }
5587
5588 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5589 if (res != OK) {
5590 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5591 __FUNCTION__, res, strerror(-res));
5592 return res;
5593 }
5594 mCancelNow = false;
5595 mActive = true;
5596 ALOGV("%s: Preparer stream started", __FUNCTION__);
5597
5598 return OK;
5599}
5600
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005601status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005602 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005603 Mutex::Autolock l(mLock);
5604
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005605 for (const auto& it : mPendingStreams) {
5606 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005607 }
5608 mPendingStreams.clear();
5609 mCancelNow = true;
5610
5611 return OK;
5612}
5613
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005614void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005615 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005616 Mutex::Autolock l(mLock);
5617 mListener = listener;
5618}
5619
5620bool Camera3Device::PreparerThread::threadLoop() {
5621 status_t res;
5622 {
5623 Mutex::Autolock l(mLock);
5624 if (mCurrentStream == nullptr) {
5625 // End thread if done with work
5626 if (mPendingStreams.empty()) {
5627 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5628 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5629 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5630 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005631 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005632 return false;
5633 }
5634
5635 // Get next stream to prepare
5636 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005637 mCurrentStream = it->second;
5638 mCurrentMaxCount = it->first;
5639 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005640 mPendingStreams.erase(it);
5641 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5642 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5643 } else if (mCancelNow) {
5644 mCurrentStream->cancelPrepare();
5645 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5646 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5647 mCurrentStream.clear();
5648 mCancelNow = false;
5649 return true;
5650 }
5651 }
5652
5653 res = mCurrentStream->prepareNextBuffer();
5654 if (res == NOT_ENOUGH_DATA) return true;
5655 if (res != OK) {
5656 // Something bad happened; try to recover by cancelling prepare and
5657 // signalling listener anyway
5658 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5659 mCurrentStream->getId(), res, strerror(-res));
5660 mCurrentStream->cancelPrepare();
5661 }
5662
5663 // This stream has finished, notify listener
5664 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005665 sp<NotificationListener> listener = mListener.promote();
5666 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005667 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5668 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005669 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005670 }
5671
5672 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5673 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005674 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005675
5676 return true;
5677}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005678
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005679/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005680 * Static callback forwarding methods from HAL to instance
5681 */
5682
5683void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5684 const camera3_capture_result *result) {
5685 Camera3Device *d =
5686 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005687
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005688 d->processCaptureResult(result);
5689}
5690
5691void Camera3Device::sNotify(const camera3_callback_ops *cb,
5692 const camera3_notify_msg *msg) {
5693 Camera3Device *d =
5694 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5695 d->notify(msg);
5696}
5697
5698}; // namespace android