blob: d9bcba36bb96908bc9cbd3a898f014d9f5133ef4 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010080 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
81 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082{
83 ATRACE_CALL();
84 camera3_callback_ops::notify = &sNotify;
85 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093 disconnect();
94}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
124 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Yifan Hongf79b5542017-04-11 14:44:25 -0700129 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700130 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
131 [&queue](const auto& descriptor) {
132 queue = std::make_shared<RequestMetadataQueue>(descriptor);
133 if (!queue->isValid() || queue->availableToWrite() <= 0) {
134 ALOGE("HAL returns empty request metadata fmq, not use it");
135 queue = nullptr;
136 // don't use the queue onwards.
137 }
138 });
139 if (!requestQueueRet.isOk()) {
140 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
141 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700142 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700144
145 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700146 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700147 [&resQueue](const auto& descriptor) {
148 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
149 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700150 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700151 resQueue = nullptr;
152 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700153 }
154 });
155 if (!resultQueueRet.isOk()) {
156 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
157 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700158 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700160 IF_ALOGV() {
161 session->interfaceChain([](
162 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
163 ALOGV("Session interface chain:");
164 for (auto iface : interfaceChain) {
165 ALOGV(" %s", iface.c_str());
166 }
167 });
168 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700169
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700170 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000171 std::string providerType;
172 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000173 mTagMonitor.initialize(mVendorTagId);
174 if (!monitorTags.isEmpty()) {
175 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
176 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800177
178 return initializeCommonLocked();
179}
180
181status_t Camera3Device::initializeCommonLocked() {
182
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700183 /** Start up status tracker thread */
184 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800185 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700186 if (res != OK) {
187 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
188 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800189 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700190 mStatusTracker.clear();
191 return res;
192 }
193
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700194 /** Register in-flight map to the status tracker */
195 mInFlightStatusId = mStatusTracker->addComponent();
196
Zhijun He125684a2015-12-26 15:07:30 -0800197 /** Create buffer manager */
198 mBufferManager = new Camera3BufferManager();
199
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000200 Vector<int32_t> sessionParamKeys;
201 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
202 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
203 if (sessionKeysEntry.count > 0) {
204 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
205 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700206 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000207 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800208 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800209 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700210 SET_ERR_L("Unable to start request queue thread: %s (%d)",
211 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800212 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800213 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800214 return res;
215 }
216
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700217 mPreparerThread = new PreparerThread();
218
Ruben Brunk183f0562015-08-12 12:55:02 -0700219 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800220 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700221 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700222 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700223 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800224
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800225 // Measure the clock domain offset between camera and video/hw_composer
226 camera_metadata_entry timestampSource =
227 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
228 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
229 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
230 mTimestampOffset = getMonoToBoottimeOffset();
231 }
232
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700233 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100234 camera_metadata_entry partialResultsCount =
235 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
236 if (partialResultsCount.count > 0) {
237 mNumPartialResults = partialResultsCount.data.i32[0];
238 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700239 }
240
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700241 camera_metadata_entry configs =
242 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
243 for (uint32_t i = 0; i < configs.count; i += 4) {
244 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
245 configs.data.i32[i + 3] ==
246 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
247 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
248 configs.data.i32[i + 2]));
249 }
250 }
251
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800252 return OK;
253}
254
255status_t Camera3Device::disconnect() {
256 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700257 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800258
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700259 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800260
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700261 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700262 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700263 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 {
265 Mutex::Autolock l(mLock);
266 if (mStatus == STATUS_UNINITIALIZED) return res;
267
268 if (mStatus == STATUS_ACTIVE ||
269 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
270 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700271 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700273 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700275 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700277 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
278 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 // Continue to close device even in case of error
280 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700281 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800282 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800283
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284 if (mStatus == STATUS_ERROR) {
285 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287
288 if (mStatusTracker != NULL) {
289 mStatusTracker->requestExit();
290 }
291
292 if (mRequestThread != NULL) {
293 mRequestThread->requestExit();
294 }
295
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700296 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
297 for (size_t i = 0; i < mOutputStreams.size(); i++) {
298 streams.push_back(mOutputStreams[i]);
299 }
300 if (mInputStream != nullptr) {
301 streams.push_back(mInputStream);
302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700303 }
304
305 // Joining done without holding mLock, otherwise deadlocks may ensue
306 // as the threads try to access parent state
307 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
308 // HAL may be in a bad state, so waiting for request thread
309 // (which may be stuck in the HAL processCaptureRequest call)
310 // could be dangerous.
311 mRequestThread->join();
312 }
313
314 if (mStatusTracker != NULL) {
315 mStatusTracker->join();
316 }
317
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800318 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 {
320 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800321 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700322 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800323 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700324 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800325
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700326 // Call close without internal mutex held, as the HAL close may need to
327 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800328 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700329
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700330 flushInflightRequests();
331
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700332 {
333 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800334 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700335 mOutputStreams.clear();
336 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700337 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700338 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700339 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700340 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700342 for (auto& weakStream : streams) {
343 sp<Camera3StreamInterface> stream = weakStream.promote();
344 if (stream != nullptr) {
345 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
346 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
347 }
348 }
349
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700350 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700351 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800352}
353
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354// For dumping/debugging only -
355// try to acquire a lock a few times, eventually give up to proceed with
356// debug/dump operations
357bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
358 bool gotLock = false;
359 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
360 if (lock.tryLock() == NO_ERROR) {
361 gotLock = true;
362 break;
363 } else {
364 usleep(kDumpSleepDuration);
365 }
366 }
367 return gotLock;
368}
369
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700370Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
371 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100372 const int STREAM_CONFIGURATION_SIZE = 4;
373 const int STREAM_FORMAT_OFFSET = 0;
374 const int STREAM_WIDTH_OFFSET = 1;
375 const int STREAM_HEIGHT_OFFSET = 2;
376 const int STREAM_IS_INPUT_OFFSET = 3;
377 camera_metadata_ro_entry_t availableStreamConfigs =
378 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
379 if (availableStreamConfigs.count == 0 ||
380 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
381 return Size(0, 0);
382 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700383
Emilian Peev08dd2452017-04-06 16:55:14 +0100384 // Get max jpeg size (area-wise).
385 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
386 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
387 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
388 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
389 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
390 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
391 && format == HAL_PIXEL_FORMAT_BLOB &&
392 (width * height > maxJpegWidth * maxJpegHeight)) {
393 maxJpegWidth = width;
394 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700395 }
396 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100397
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700398 return Size(maxJpegWidth, maxJpegHeight);
399}
400
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800401nsecs_t Camera3Device::getMonoToBoottimeOffset() {
402 // try three times to get the clock offset, choose the one
403 // with the minimum gap in measurements.
404 const int tries = 3;
405 nsecs_t bestGap, measured;
406 for (int i = 0; i < tries; ++i) {
407 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
408 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
409 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
410 const nsecs_t gap = tmono2 - tmono;
411 if (i == 0 || gap < bestGap) {
412 bestGap = gap;
413 measured = tbase - ((tmono + tmono2) >> 1);
414 }
415 }
416 return measured;
417}
418
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800419hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
420 int frameworkFormat) {
421 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
422}
423
424DataspaceFlags Camera3Device::mapToHidlDataspace(
425 android_dataspace dataSpace) {
426 return dataSpace;
427}
428
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700429BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100430 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700431 return usage;
432}
433
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800434StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
435 switch (rotation) {
436 case CAMERA3_STREAM_ROTATION_0:
437 return StreamRotation::ROTATION_0;
438 case CAMERA3_STREAM_ROTATION_90:
439 return StreamRotation::ROTATION_90;
440 case CAMERA3_STREAM_ROTATION_180:
441 return StreamRotation::ROTATION_180;
442 case CAMERA3_STREAM_ROTATION_270:
443 return StreamRotation::ROTATION_270;
444 }
445 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
446 return StreamRotation::ROTATION_0;
447}
448
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800449status_t Camera3Device::mapToStreamConfigurationMode(
450 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
451 if (mode == nullptr) return BAD_VALUE;
452 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
453 switch(operationMode) {
454 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
455 *mode = StreamConfigurationMode::NORMAL_MODE;
456 break;
457 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
458 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
459 break;
460 default:
461 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
462 return BAD_VALUE;
463 }
464 } else {
465 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800466 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800467 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800468}
469
470camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
471 switch (status) {
472 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
473 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
474 }
475 return CAMERA3_BUFFER_STATUS_ERROR;
476}
477
478int Camera3Device::mapToFrameworkFormat(
479 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
480 return static_cast<uint32_t>(pixelFormat);
481}
482
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700483android_dataspace Camera3Device::mapToFrameworkDataspace(
484 DataspaceFlags dataSpace) {
485 return static_cast<android_dataspace>(dataSpace);
486}
487
Emilian Peev050f5dc2017-05-18 14:43:56 +0100488uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700489 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700490 return usage;
491}
492
Emilian Peev050f5dc2017-05-18 14:43:56 +0100493uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700494 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700495 return usage;
496}
497
Zhijun Hef7da0962014-04-24 13:27:56 -0700498ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700499 // Get max jpeg size (area-wise).
500 Size maxJpegResolution = getMaxJpegResolution();
501 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
503 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700504 return BAD_VALUE;
505 }
506
Zhijun Hef7da0962014-04-24 13:27:56 -0700507 // Get max jpeg buffer size
508 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700509 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
510 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
512 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700513 return BAD_VALUE;
514 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700515 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800516 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700517
518 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700519 float scaleFactor = ((float) (width * height)) /
520 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800521 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
522 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700523 if (jpegBufferSize > maxJpegBufferSize) {
524 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700525 }
526
527 return jpegBufferSize;
528}
529
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700530ssize_t Camera3Device::getPointCloudBufferSize() const {
531 const int FLOATS_PER_POINT=4;
532 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
533 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
535 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700536 return BAD_VALUE;
537 }
538 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
539 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
540 return maxBytesForPointCloud;
541}
542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800543ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800544 const int PER_CONFIGURATION_SIZE = 3;
545 const int WIDTH_OFFSET = 0;
546 const int HEIGHT_OFFSET = 1;
547 const int SIZE_OFFSET = 2;
548 camera_metadata_ro_entry rawOpaqueSizes =
549 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800550 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800551 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
553 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800554 return BAD_VALUE;
555 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700556
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800557 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
558 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
559 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
560 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
561 }
562 }
563
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800564 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
565 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800566 return BAD_VALUE;
567}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700568
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800569status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
570 ATRACE_CALL();
571 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700572
573 // Try to lock, but continue in case of failure (to avoid blocking in
574 // deadlocks)
575 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
576 bool gotLock = tryLockSpinRightRound(mLock);
577
578 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
580 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700581 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
583 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700584
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800585 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700586
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800587 String16 templatesOption("-t");
588 int n = args.size();
589 for (int i = 0; i < n; i++) {
590 if (args[i] == templatesOption) {
591 dumpTemplates = true;
592 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000593 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700594 if (i + 1 < n) {
595 String8 monitorTags = String8(args[i + 1]);
596 if (monitorTags == "off") {
597 mTagMonitor.disableMonitoring();
598 } else {
599 mTagMonitor.parseTagsToMonitor(monitorTags);
600 }
601 } else {
602 mTagMonitor.disableMonitoring();
603 }
604 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800605 }
606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800607 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800608
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800609 const char *status =
610 mStatus == STATUS_ERROR ? "ERROR" :
611 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700612 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
613 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800614 mStatus == STATUS_ACTIVE ? "ACTIVE" :
615 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700616
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700618 if (mStatus == STATUS_ERROR) {
619 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
620 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800621 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800622 const char *mode =
623 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
624 mOperatingMode == static_cast<int>(
625 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
626 "CUSTOM";
627 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800628
629 if (mInputStream != NULL) {
630 write(fd, lines.string(), lines.size());
631 mInputStream->dump(fd, args);
632 } else {
633 lines.appendFormat(" No input stream.\n");
634 write(fd, lines.string(), lines.size());
635 }
636 for (size_t i = 0; i < mOutputStreams.size(); i++) {
637 mOutputStreams[i]->dump(fd,args);
638 }
639
Zhijun He431503c2016-03-07 17:30:16 -0800640 if (mBufferManager != NULL) {
641 lines = String8(" Camera3 Buffer Manager:\n");
642 write(fd, lines.string(), lines.size());
643 mBufferManager->dump(fd, args);
644 }
Zhijun He125684a2015-12-26 15:07:30 -0800645
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700646 lines = String8(" In-flight requests:\n");
647 if (mInFlightMap.size() == 0) {
648 lines.append(" None\n");
649 } else {
650 for (size_t i = 0; i < mInFlightMap.size(); i++) {
651 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700652 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700653 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800654 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700655 r.numBuffersLeft);
656 }
657 }
658 write(fd, lines.string(), lines.size());
659
Shuzhen Wang686f6442017-06-20 16:16:04 -0700660 if (mRequestThread != NULL) {
661 mRequestThread->dumpCaptureRequestLatency(fd,
662 " ProcessCaptureRequest latency histogram:");
663 }
664
Igor Murashkin1e479c02013-09-06 16:55:14 -0700665 {
666 lines = String8(" Last request sent:\n");
667 write(fd, lines.string(), lines.size());
668
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700669 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700670 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
671 }
672
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800674 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800675 "TEMPLATE_PREVIEW",
676 "TEMPLATE_STILL_CAPTURE",
677 "TEMPLATE_VIDEO_RECORD",
678 "TEMPLATE_VIDEO_SNAPSHOT",
679 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800680 "TEMPLATE_MANUAL",
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) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001554 ALOGW("%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 Peev811d2952018-05-25 11:08:40 +01001601 // In case the client doesn't include any session parameter, try a
1602 // speculative configuration using the values from the last cached
1603 // default request.
1604 if (sessionParams.isEmpty() &&
1605 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1606 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1607 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1608 mLastTemplateId);
1609 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1610 operatingMode);
1611 }
1612
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001613 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1614}
1615
1616status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1617 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001618 //Filter out any incoming session parameters
1619 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001620 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1621 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001622 CameraMetadata filteredParams(availableSessionKeys.count);
1623 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1624 filteredParams.getAndLock());
1625 set_camera_metadata_vendor_id(meta, mVendorTagId);
1626 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001627 if (availableSessionKeys.count > 0) {
1628 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1629 camera_metadata_ro_entry entry = params.find(
1630 availableSessionKeys.data.i32[i]);
1631 if (entry.count > 0) {
1632 filteredParams.update(entry);
1633 }
1634 }
1635 }
1636
1637 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001638}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001639
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001640status_t Camera3Device::getInputBufferProducer(
1641 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001642 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001643 Mutex::Autolock il(mInterfaceLock);
1644 Mutex::Autolock l(mLock);
1645
1646 if (producer == NULL) {
1647 return BAD_VALUE;
1648 } else if (mInputStream == NULL) {
1649 return INVALID_OPERATION;
1650 }
1651
1652 return mInputStream->getInputBufferProducer(producer);
1653}
1654
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001655status_t Camera3Device::createDefaultRequest(int templateId,
1656 CameraMetadata *request) {
1657 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001658 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001659
1660 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1661 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1662 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1663 return BAD_VALUE;
1664 }
1665
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001666 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001667
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001668 {
1669 Mutex::Autolock l(mLock);
1670 switch (mStatus) {
1671 case STATUS_ERROR:
1672 CLOGE("Device has encountered a serious error");
1673 return INVALID_OPERATION;
1674 case STATUS_UNINITIALIZED:
1675 CLOGE("Device is not initialized!");
1676 return INVALID_OPERATION;
1677 case STATUS_UNCONFIGURED:
1678 case STATUS_CONFIGURED:
1679 case STATUS_ACTIVE:
1680 // OK
1681 break;
1682 default:
1683 SET_ERR_L("Unexpected status: %d", mStatus);
1684 return INVALID_OPERATION;
1685 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001687 if (!mRequestTemplateCache[templateId].isEmpty()) {
1688 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001689 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001690 return OK;
1691 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001692 }
1693
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001694 camera_metadata_t *rawRequest;
1695 status_t res = mInterface->constructDefaultRequestSettings(
1696 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697
1698 {
1699 Mutex::Autolock l(mLock);
1700 if (res == BAD_VALUE) {
1701 ALOGI("%s: template %d is not supported on this camera device",
1702 __FUNCTION__, templateId);
1703 return res;
1704 } else if (res != OK) {
1705 CLOGE("Unable to construct request template %d: %s (%d)",
1706 templateId, strerror(-res), res);
1707 return res;
1708 }
1709
1710 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1711 mRequestTemplateCache[templateId].acquire(rawRequest);
1712
1713 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001714 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001715 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716 return OK;
1717}
1718
1719status_t Camera3Device::waitUntilDrained() {
1720 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001721 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001722 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001725 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001726}
1727
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001728status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001729 switch (mStatus) {
1730 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001731 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732 ALOGV("%s: Already idle", __FUNCTION__);
1733 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001734 case STATUS_CONFIGURED:
1735 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736 case STATUS_ERROR:
1737 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001738 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001739 break;
1740 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001741 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 return INVALID_OPERATION;
1743 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001744 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1745 maxExpectedDuration);
1746 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001747 if (res != OK) {
1748 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1749 res);
1750 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001751 return res;
1752}
1753
Ruben Brunk183f0562015-08-12 12:55:02 -07001754
1755void Camera3Device::internalUpdateStatusLocked(Status status) {
1756 mStatus = status;
1757 mRecentStatusUpdates.add(mStatus);
1758 mStatusChanged.broadcast();
1759}
1760
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001761void Camera3Device::pauseStateNotify(bool enable) {
1762 Mutex::Autolock il(mInterfaceLock);
1763 Mutex::Autolock l(mLock);
1764
1765 mPauseStateNotify = enable;
1766}
1767
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001769status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001770 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001772 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1773 maxExpectedDuration);
1774 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001775 if (res != OK) {
1776 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001777 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778 }
1779
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780 return res;
1781}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001782
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001783// Resume after internalPauseAndWaitLocked
1784status_t Camera3Device::internalResumeLocked() {
1785 status_t res;
1786
1787 mRequestThread->setPaused(false);
1788
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001789 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1790 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1792 if (res != OK) {
1793 SET_ERR_L("Can't transition to active in %f seconds!",
1794 kActiveTimeout/1e9);
1795 }
1796 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001798}
1799
Ruben Brunk183f0562015-08-12 12:55:02 -07001800status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001801 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001802
1803 size_t startIndex = 0;
1804 if (mStatusWaiters == 0) {
1805 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1806 // this status list
1807 mRecentStatusUpdates.clear();
1808 } else {
1809 // If other threads are waiting on updates to this status list, set the position of the
1810 // first element that this list will check rather than clearing the list.
1811 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 }
1813
Ruben Brunk183f0562015-08-12 12:55:02 -07001814 mStatusWaiters++;
1815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001816 bool stateSeen = false;
1817 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001818 if (active == (mStatus == STATUS_ACTIVE)) {
1819 // Desired state is current
1820 break;
1821 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822
1823 res = mStatusChanged.waitRelative(mLock, timeout);
1824 if (res != OK) break;
1825
Ruben Brunk183f0562015-08-12 12:55:02 -07001826 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1827 // transitions.
1828 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1829 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1830 __FUNCTION__);
1831
1832 // Encountered desired state since we began waiting
1833 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001834 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1835 stateSeen = true;
1836 break;
1837 }
1838 }
1839 } while (!stateSeen);
1840
Ruben Brunk183f0562015-08-12 12:55:02 -07001841 mStatusWaiters--;
1842
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 return res;
1844}
1845
1846
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001847status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001848 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001849 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001850
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001851 if (listener != NULL && mListener != NULL) {
1852 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1853 }
1854 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001855 mRequestThread->setNotificationListener(listener);
1856 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001857
1858 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001859}
1860
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001861bool Camera3Device::willNotify3A() {
1862 return false;
1863}
1864
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001865status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001866 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001867 status_t res;
1868 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001869
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001870 while (mResultQueue.empty()) {
1871 res = mResultSignal.waitRelative(mOutputLock, timeout);
1872 if (res == TIMED_OUT) {
1873 return res;
1874 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001875 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1876 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001877 return res;
1878 }
1879 }
1880 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001881}
1882
Jianing Weicb0652e2014-03-12 18:29:36 -07001883status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001884 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001885 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001887 if (mResultQueue.empty()) {
1888 return NOT_ENOUGH_DATA;
1889 }
1890
Jianing Weicb0652e2014-03-12 18:29:36 -07001891 if (frame == NULL) {
1892 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1893 return BAD_VALUE;
1894 }
1895
1896 CaptureResult &result = *(mResultQueue.begin());
1897 frame->mResultExtras = result.mResultExtras;
1898 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001899 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001900 mResultQueue.erase(mResultQueue.begin());
1901
1902 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903}
1904
1905status_t Camera3Device::triggerAutofocus(uint32_t id) {
1906 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001907 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001908
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001909 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1910 // Mix-in this trigger into the next request and only the next request.
1911 RequestTrigger trigger[] = {
1912 {
1913 ANDROID_CONTROL_AF_TRIGGER,
1914 ANDROID_CONTROL_AF_TRIGGER_START
1915 },
1916 {
1917 ANDROID_CONTROL_AF_TRIGGER_ID,
1918 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001919 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001920 };
1921
1922 return mRequestThread->queueTrigger(trigger,
1923 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924}
1925
1926status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1927 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001928 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001929
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001930 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1931 // Mix-in this trigger into the next request and only the next request.
1932 RequestTrigger trigger[] = {
1933 {
1934 ANDROID_CONTROL_AF_TRIGGER,
1935 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1936 },
1937 {
1938 ANDROID_CONTROL_AF_TRIGGER_ID,
1939 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001940 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001941 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001942
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001943 return mRequestThread->queueTrigger(trigger,
1944 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001945}
1946
1947status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1948 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001951 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1952 // Mix-in this trigger into the next request and only the next request.
1953 RequestTrigger trigger[] = {
1954 {
1955 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1956 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1957 },
1958 {
1959 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1960 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001961 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001962 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001964 return mRequestThread->queueTrigger(trigger,
1965 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001966}
1967
Jianing Weicb0652e2014-03-12 18:29:36 -07001968status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001969 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001970 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001971 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001972
Zhijun He7ef20392014-04-21 16:04:17 -07001973 {
1974 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001975 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001976 }
1977
Emilian Peev08dd2452017-04-06 16:55:14 +01001978 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001979}
1980
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001981status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001982 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1983}
1984
1985status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001986 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001987 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001988 Mutex::Autolock il(mInterfaceLock);
1989 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001990
1991 sp<Camera3StreamInterface> stream;
1992 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1993 if (outputStreamIdx == NAME_NOT_FOUND) {
1994 CLOGE("Stream %d does not exist", streamId);
1995 return BAD_VALUE;
1996 }
1997
1998 stream = mOutputStreams.editValueAt(outputStreamIdx);
1999
2000 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002001 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002002 return BAD_VALUE;
2003 }
2004
2005 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002006 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002007 return BAD_VALUE;
2008 }
2009
Ruben Brunkc78ac262015-08-13 17:58:46 -07002010 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002011}
2012
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002013status_t Camera3Device::tearDown(int streamId) {
2014 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002015 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002016 Mutex::Autolock il(mInterfaceLock);
2017 Mutex::Autolock l(mLock);
2018
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002019 sp<Camera3StreamInterface> stream;
2020 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2021 if (outputStreamIdx == NAME_NOT_FOUND) {
2022 CLOGE("Stream %d does not exist", streamId);
2023 return BAD_VALUE;
2024 }
2025
2026 stream = mOutputStreams.editValueAt(outputStreamIdx);
2027
2028 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2029 CLOGE("Stream %d is a target of a in-progress request", streamId);
2030 return BAD_VALUE;
2031 }
2032
2033 return stream->tearDown();
2034}
2035
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002036status_t Camera3Device::addBufferListenerForStream(int streamId,
2037 wp<Camera3StreamBufferListener> listener) {
2038 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002039 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002040 Mutex::Autolock il(mInterfaceLock);
2041 Mutex::Autolock l(mLock);
2042
2043 sp<Camera3StreamInterface> stream;
2044 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2045 if (outputStreamIdx == NAME_NOT_FOUND) {
2046 CLOGE("Stream %d does not exist", streamId);
2047 return BAD_VALUE;
2048 }
2049
2050 stream = mOutputStreams.editValueAt(outputStreamIdx);
2051 stream->addBufferListener(listener);
2052
2053 return OK;
2054}
2055
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002057 * Methods called by subclasses
2058 */
2059
2060void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002061 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002062 {
2063 // Need mLock to safely update state and synchronize to current
2064 // state of methods in flight.
2065 Mutex::Autolock l(mLock);
2066 // We can get various system-idle notices from the status tracker
2067 // while starting up. Only care about them if we've actually sent
2068 // in some requests recently.
2069 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2070 return;
2071 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002072 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2073 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002074 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002075
2076 // Skip notifying listener if we're doing some user-transparent
2077 // state changes
2078 if (mPauseStateNotify) return;
2079 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002080
2081 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002082 {
2083 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002084 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002085 }
2086 if (idle && listener != NULL) {
2087 listener->notifyIdle();
2088 }
2089}
2090
Shuzhen Wang758c2152017-01-10 18:26:18 -08002091status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002092 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002093 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002094 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2095 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002096
2097 if (surfaceIds == nullptr) {
2098 return BAD_VALUE;
2099 }
2100
Zhijun He5d677d12016-05-29 16:52:39 -07002101 Mutex::Autolock il(mInterfaceLock);
2102 Mutex::Autolock l(mLock);
2103
Shuzhen Wang758c2152017-01-10 18:26:18 -08002104 if (consumers.size() == 0) {
2105 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002106 return BAD_VALUE;
2107 }
2108
2109 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2110 if (idx == NAME_NOT_FOUND) {
2111 CLOGE("Stream %d is unknown", streamId);
2112 return idx;
2113 }
2114 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002115 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002116 if (res != OK) {
2117 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2118 return res;
2119 }
2120
Emilian Peev40ead602017-09-26 15:46:36 +01002121 for (auto &consumer : consumers) {
2122 int id = stream->getSurfaceId(consumer);
2123 if (id < 0) {
2124 CLOGE("Invalid surface id!");
2125 return BAD_VALUE;
2126 }
2127 surfaceIds->push_back(id);
2128 }
2129
Shuzhen Wang0129d522016-10-30 22:43:41 -07002130 if (stream->isConsumerConfigurationDeferred()) {
2131 if (!stream->isConfiguring()) {
2132 CLOGE("Stream %d was already fully configured.", streamId);
2133 return INVALID_OPERATION;
2134 }
Zhijun He5d677d12016-05-29 16:52:39 -07002135
Shuzhen Wang0129d522016-10-30 22:43:41 -07002136 res = stream->finishConfiguration();
2137 if (res != OK) {
2138 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2139 stream->getId(), strerror(-res), res);
2140 return res;
2141 }
Zhijun He5d677d12016-05-29 16:52:39 -07002142 }
2143
2144 return OK;
2145}
2146
Emilian Peev40ead602017-09-26 15:46:36 +01002147status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2148 const std::vector<OutputStreamInfo> &outputInfo,
2149 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2150 Mutex::Autolock il(mInterfaceLock);
2151 Mutex::Autolock l(mLock);
2152
2153 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2154 if (idx == NAME_NOT_FOUND) {
2155 CLOGE("Stream %d is unknown", streamId);
2156 return idx;
2157 }
2158
2159 for (const auto &it : removedSurfaceIds) {
2160 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2161 CLOGE("Shared surface still part of a pending request!");
2162 return -EBUSY;
2163 }
2164 }
2165
2166 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2167 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2168 if (res != OK) {
2169 CLOGE("Stream %d failed to update stream (error %d %s) ",
2170 streamId, res, strerror(-res));
2171 if (res == UNKNOWN_ERROR) {
2172 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2173 __FUNCTION__);
2174 }
2175 return res;
2176 }
2177
2178 return res;
2179}
2180
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002181status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2182 Mutex::Autolock il(mInterfaceLock);
2183 Mutex::Autolock l(mLock);
2184
2185 int idx = mOutputStreams.indexOfKey(streamId);
2186 if (idx == NAME_NOT_FOUND) {
2187 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2188 return BAD_VALUE;
2189 }
2190
2191 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2192 return stream->dropBuffers(dropping);
2193}
2194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002196 * Camera3Device private methods
2197 */
2198
2199sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002200 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002201 ATRACE_CALL();
2202 status_t res;
2203
2204 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002205 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002206
2207 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002208 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002209 if (inputStreams.count > 0) {
2210 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002211 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002212 CLOGE("Request references unknown input stream %d",
2213 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002214 return NULL;
2215 }
2216 // Lazy completion of stream configuration (allocation/registration)
2217 // on first use
2218 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002219 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002221 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002222 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002223 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224 return NULL;
2225 }
2226 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002227 // Check if stream is being prepared
2228 if (mInputStream->isPreparing()) {
2229 CLOGE("Request references an input stream that's being prepared!");
2230 return NULL;
2231 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002232
2233 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002234 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235 }
2236
2237 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002238 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002240 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241 return NULL;
2242 }
2243
2244 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002245 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002247 CLOGE("Request references unknown stream %d",
2248 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 return NULL;
2250 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002251 sp<Camera3OutputStreamInterface> stream =
2252 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253
Zhijun He5d677d12016-05-29 16:52:39 -07002254 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002255 auto iter = surfaceMap.find(streams.data.i32[i]);
2256 if (iter != surfaceMap.end()) {
2257 const std::vector<size_t>& surfaces = iter->second;
2258 for (const auto& surface : surfaces) {
2259 if (stream->isConsumerConfigurationDeferred(surface)) {
2260 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2261 "due to deferred consumer", stream->getId(), surface);
2262 return NULL;
2263 }
2264 }
2265 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002266 }
2267
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 // Lazy completion of stream configuration (allocation/registration)
2269 // on first use
2270 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002271 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002272 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002273 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2274 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275 return NULL;
2276 }
2277 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002278 // Check if stream is being prepared
2279 if (stream->isPreparing()) {
2280 CLOGE("Request references an output stream that's being prepared!");
2281 return NULL;
2282 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002283
2284 newRequest->mOutputStreams.push(stream);
2285 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002286 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002287 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288
2289 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002290}
2291
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002292bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2293 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2294 Size size = mSupportedOpaqueInputSizes[i];
2295 if (size.width == width && size.height == height) {
2296 return true;
2297 }
2298 }
2299
2300 return false;
2301}
2302
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002303void Camera3Device::cancelStreamsConfigurationLocked() {
2304 int res = OK;
2305 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2306 res = mInputStream->cancelConfiguration();
2307 if (res != OK) {
2308 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2309 mInputStream->getId(), strerror(-res), res);
2310 }
2311 }
2312
2313 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2314 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2315 if (outputStream->isConfiguring()) {
2316 res = outputStream->cancelConfiguration();
2317 if (res != OK) {
2318 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2319 outputStream->getId(), strerror(-res), res);
2320 }
2321 }
2322 }
2323
2324 // Return state to that at start of call, so that future configures
2325 // properly clean things up
2326 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2327 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002328
2329 res = mPreparerThread->resume();
2330 if (res != OK) {
2331 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2332 }
2333}
2334
2335bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2336 ATRACE_CALL();
2337 bool ret = false;
2338
2339 Mutex::Autolock il(mInterfaceLock);
2340 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2341
2342 Mutex::Autolock l(mLock);
2343 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2344 if (rc == NO_ERROR) {
2345 mNeedConfig = true;
2346 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2347 if (rc == NO_ERROR) {
2348 ret = true;
2349 mPauseStateNotify = false;
2350 //Moving to active state while holding 'mLock' is important.
2351 //There could be pending calls to 'create-/deleteStream' which
2352 //will trigger another stream configuration while the already
2353 //present streams end up with outstanding buffers that will
2354 //not get drained.
2355 internalUpdateStatusLocked(STATUS_ACTIVE);
2356 } else {
2357 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2358 __FUNCTION__, rc);
2359 }
2360 } else {
2361 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2362 }
2363
2364 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002365}
2366
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002367status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002368 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 ATRACE_CALL();
2370 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002371
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002372 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002373 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374 return INVALID_OPERATION;
2375 }
2376
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002377 if (operatingMode < 0) {
2378 CLOGE("Invalid operating mode: %d", operatingMode);
2379 return BAD_VALUE;
2380 }
2381
2382 bool isConstrainedHighSpeed =
2383 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2384 operatingMode;
2385
2386 if (mOperatingMode != operatingMode) {
2387 mNeedConfig = true;
2388 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2389 mOperatingMode = operatingMode;
2390 }
2391
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002392 if (!mNeedConfig) {
2393 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2394 return OK;
2395 }
2396
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002397 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2398 // adding a dummy stream instead.
2399 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2400 if (mOutputStreams.size() == 0) {
2401 addDummyStreamLocked();
2402 } else {
2403 tryRemoveDummyStreamLocked();
2404 }
2405
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002407 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002409 mPreparerThread->pause();
2410
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002412 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2414
2415 Vector<camera3_stream_t*> streams;
2416 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002417 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002418
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002419
2420 if (mInputStream != NULL) {
2421 camera3_stream_t *inputStream;
2422 inputStream = mInputStream->startConfiguration();
2423 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002424 CLOGE("Can't start input stream configuration");
2425 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426 return INVALID_OPERATION;
2427 }
2428 streams.add(inputStream);
2429 }
2430
2431 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002432
2433 // Don't configure bidi streams twice, nor add them twice to the list
2434 if (mOutputStreams[i].get() ==
2435 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2436
2437 config.num_streams--;
2438 continue;
2439 }
2440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441 camera3_stream_t *outputStream;
2442 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2443 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002444 CLOGE("Can't start output stream configuration");
2445 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 return INVALID_OPERATION;
2447 }
2448 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002449
2450 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2451 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002452 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2453 // always occupy the initial entry.
2454 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002455 getJpegBufferSize(outputStream->width, outputStream->height));
2456 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457 }
2458
2459 config.streams = streams.editArray();
2460
2461 // Do the HAL configuration; will potentially touch stream
2462 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002463
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002464 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002465 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002466 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002468 if (res == BAD_VALUE) {
2469 // HAL rejected this set of streams as unsupported, clean up config
2470 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002471 CLOGE("Set of requested inputs/outputs not supported by HAL");
2472 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002473 return BAD_VALUE;
2474 } else if (res != OK) {
2475 // Some other kind of error from configure_streams - this is not
2476 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002477 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2478 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002479 return res;
2480 }
2481
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002482 // Finish all stream configuration immediately.
2483 // TODO: Try to relax this later back to lazy completion, which should be
2484 // faster
2485
Igor Murashkin073f8572013-05-02 14:59:28 -07002486 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002487 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002488 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002489 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002490 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002491 cancelStreamsConfigurationLocked();
2492 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002493 }
2494 }
2495
2496 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002497 sp<Camera3OutputStreamInterface> outputStream =
2498 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002499 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002500 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002501 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002503 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 cancelStreamsConfigurationLocked();
2505 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002506 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002507 }
2508 }
2509
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002510 // Request thread needs to know to avoid using repeat-last-settings protocol
2511 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002512 if (notifyRequestThread) {
2513 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2514 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002515
Zhijun He90f7c372016-08-16 16:19:43 -07002516 char value[PROPERTY_VALUE_MAX];
2517 property_get("camera.fifo.disable", value, "0");
2518 int32_t disableFifo = atoi(value);
2519 if (disableFifo != 1) {
2520 // Boost priority of request thread to SCHED_FIFO.
2521 pid_t requestThreadTid = mRequestThread->getTid();
2522 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002523 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002524 if (res != OK) {
2525 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2526 strerror(-res), res);
2527 } else {
2528 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2529 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002530 }
2531
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002532 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002533 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2534 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2535 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2536 sessionParams.unlock(newSessionParams);
2537 mSessionParams.unlock(currentSessionParams);
2538 if (updateSessionParams) {
2539 mSessionParams = sessionParams;
2540 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002541
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002542 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002543
Ruben Brunk183f0562015-08-12 12:55:02 -07002544 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2545 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002546
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002547 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002548
Zhijun He0a210512014-07-24 13:45:15 -07002549 // tear down the deleted streams after configure streams.
2550 mDeletedStreams.clear();
2551
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002552 auto rc = mPreparerThread->resume();
2553 if (rc != OK) {
2554 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2555 return rc;
2556 }
2557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002558 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002559}
2560
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002561status_t Camera3Device::addDummyStreamLocked() {
2562 ATRACE_CALL();
2563 status_t res;
2564
2565 if (mDummyStreamId != NO_STREAM) {
2566 // Should never be adding a second dummy stream when one is already
2567 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002568 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2569 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002570 return INVALID_OPERATION;
2571 }
2572
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002573 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002574
2575 sp<Camera3OutputStreamInterface> dummyStream =
2576 new Camera3DummyStream(mNextStreamId);
2577
2578 res = mOutputStreams.add(mNextStreamId, dummyStream);
2579 if (res < 0) {
2580 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2581 return res;
2582 }
2583
2584 mDummyStreamId = mNextStreamId;
2585 mNextStreamId++;
2586
2587 return OK;
2588}
2589
2590status_t Camera3Device::tryRemoveDummyStreamLocked() {
2591 ATRACE_CALL();
2592 status_t res;
2593
2594 if (mDummyStreamId == NO_STREAM) return OK;
2595 if (mOutputStreams.size() == 1) return OK;
2596
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002597 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002598
2599 // Ok, have a dummy stream and there's at least one other output stream,
2600 // so remove the dummy
2601
2602 sp<Camera3StreamInterface> deletedStream;
2603 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2604 if (outputStreamIdx == NAME_NOT_FOUND) {
2605 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2606 return INVALID_OPERATION;
2607 }
2608
2609 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2610 mOutputStreams.removeItemsAt(outputStreamIdx);
2611
2612 // Free up the stream endpoint so that it can be used by some other stream
2613 res = deletedStream->disconnect();
2614 if (res != OK) {
2615 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2616 // fall through since we want to still list the stream as deleted.
2617 }
2618 mDeletedStreams.add(deletedStream);
2619 mDummyStreamId = NO_STREAM;
2620
2621 return res;
2622}
2623
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002624void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002625 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002626 Mutex::Autolock l(mLock);
2627 va_list args;
2628 va_start(args, fmt);
2629
2630 setErrorStateLockedV(fmt, args);
2631
2632 va_end(args);
2633}
2634
2635void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002636 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002637 Mutex::Autolock l(mLock);
2638 setErrorStateLockedV(fmt, args);
2639}
2640
2641void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2642 va_list args;
2643 va_start(args, fmt);
2644
2645 setErrorStateLockedV(fmt, args);
2646
2647 va_end(args);
2648}
2649
2650void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002651 // Print out all error messages to log
2652 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002653 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002654
2655 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002656 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002657
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002658 mErrorCause = errorCause;
2659
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002660 if (mRequestThread != nullptr) {
2661 mRequestThread->setPaused(true);
2662 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002663 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002664
2665 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002666 sp<NotificationListener> listener = mListener.promote();
2667 if (listener != NULL) {
2668 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002669 CaptureResultExtras());
2670 }
2671
2672 // Save stack trace. View by dumping it later.
2673 CameraTraces::saveTrace();
2674 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002675}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002676
2677/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002678 * In-flight request management
2679 */
2680
Jianing Weicb0652e2014-03-12 18:29:36 -07002681status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002682 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002683 bool hasAppCallback, nsecs_t maxExpectedDuration,
2684 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002685 ATRACE_CALL();
2686 Mutex::Autolock l(mInFlightLock);
2687
2688 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002689 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002690 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002691 if (res < 0) return res;
2692
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002693 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002694 // hold mLock to prevent race with disconnect
2695 Mutex::Autolock l(mLock);
2696 if (mStatusTracker != nullptr) {
2697 mStatusTracker->markComponentActive(mInFlightStatusId);
2698 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002699 }
2700
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002701 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002702 return OK;
2703}
2704
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002705void Camera3Device::returnOutputBuffers(
2706 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2707 nsecs_t timestamp) {
2708 for (size_t i = 0; i < numBuffers; i++)
2709 {
2710 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2711 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2712 // Note: stream may be deallocated at this point, if this buffer was
2713 // the last reference to it.
2714 if (res != OK) {
2715 ALOGE("Can't return buffer to its stream: %s (%d)",
2716 strerror(-res), res);
2717 }
2718 }
2719}
2720
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002721void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002722 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002723 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002724 mInFlightMap.removeItemsAt(idx, 1);
2725
2726 // Indicate idle inFlightMap to the status tracker
2727 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002728 // hold mLock to prevent race with disconnect
2729 Mutex::Autolock l(mLock);
2730 if (mStatusTracker != nullptr) {
2731 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2732 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002733 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002734 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002735}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002736
2737void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2738
2739 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2740 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2741
2742 nsecs_t sensorTimestamp = request.sensorTimestamp;
2743 nsecs_t shutterTimestamp = request.shutterTimestamp;
2744
2745 // Check if it's okay to remove the request from InFlightMap:
2746 // In the case of a successful request:
2747 // all input and output buffers, all result metadata, shutter callback
2748 // arrived.
2749 // In the case of a unsuccessful request:
2750 // all input and output buffers arrived.
2751 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002752 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002753 (request.haveResultMetadata && shutterTimestamp != 0))) {
2754 ATRACE_ASYNC_END("frame capture", frameNumber);
2755
Shuzhen Wang403044a2017-02-26 23:29:04 -08002756 // Sanity check - if sensor timestamp matches shutter timestamp in the
2757 // case of request having callback.
2758 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002759 sensorTimestamp != shutterTimestamp) {
2760 SET_ERR("sensor timestamp (%" PRId64
2761 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2762 sensorTimestamp, frameNumber, shutterTimestamp);
2763 }
2764
2765 // for an unsuccessful request, it may have pending output buffers to
2766 // return.
2767 assert(request.requestStatus != OK ||
2768 request.pendingOutputBuffers.size() == 0);
2769 returnOutputBuffers(request.pendingOutputBuffers.array(),
2770 request.pendingOutputBuffers.size(), 0);
2771
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002772 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002773 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2774 }
2775
2776 // Sanity check - if we have too many in-flight frames, something has
2777 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002778 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002779 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002780 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2781 kInFlightWarnLimitHighSpeed) {
2782 CLOGE("In-flight list too large for high speed configuration: %zu",
2783 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002784 }
2785}
2786
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002787void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002788 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002789 { // First return buffers cached in mInFlightMap
2790 Mutex::Autolock l(mInFlightLock);
2791 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2792 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2793 returnOutputBuffers(request.pendingOutputBuffers.array(),
2794 request.pendingOutputBuffers.size(), 0);
2795 }
2796 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002797 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002798 }
2799
2800 // Then return all inflight buffers not returned by HAL
2801 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2802 mInterface->getInflightBufferKeys(&inflightKeys);
2803
2804 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2805 for (auto& pair : inflightKeys) {
2806 int32_t frameNumber = pair.first;
2807 int32_t streamId = pair.second;
2808 buffer_handle_t* buffer;
2809 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2810 if (res != OK) {
2811 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2812 __FUNCTION__, frameNumber, streamId);
2813 continue;
2814 }
2815
2816 camera3_stream_buffer_t streamBuffer;
2817 streamBuffer.buffer = buffer;
2818 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2819 streamBuffer.acquire_fence = -1;
2820 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002821
2822 // First check if the buffer belongs to deleted stream
2823 bool streamDeleted = false;
2824 for (auto& stream : mDeletedStreams) {
2825 if (streamId == stream->getId()) {
2826 streamDeleted = true;
2827 // Return buffer to deleted stream
2828 camera3_stream* halStream = stream->asHalStream();
2829 streamBuffer.stream = halStream;
2830 switch (halStream->stream_type) {
2831 case CAMERA3_STREAM_OUTPUT:
2832 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2833 if (res != OK) {
2834 ALOGE("%s: Can't return output buffer for frame %d to"
2835 " stream %d: %s (%d)", __FUNCTION__,
2836 frameNumber, streamId, strerror(-res), res);
2837 }
2838 break;
2839 case CAMERA3_STREAM_INPUT:
2840 res = stream->returnInputBuffer(streamBuffer);
2841 if (res != OK) {
2842 ALOGE("%s: Can't return input buffer for frame %d to"
2843 " stream %d: %s (%d)", __FUNCTION__,
2844 frameNumber, streamId, strerror(-res), res);
2845 }
2846 break;
2847 default: // Bi-direcitonal stream is deprecated
2848 ALOGE("%s: stream %d has unknown stream type %d",
2849 __FUNCTION__, streamId, halStream->stream_type);
2850 break;
2851 }
2852 break;
2853 }
2854 }
2855 if (streamDeleted) {
2856 continue;
2857 }
2858
2859 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002860 if (streamId == inputStreamId) {
2861 streamBuffer.stream = mInputStream->asHalStream();
2862 res = mInputStream->returnInputBuffer(streamBuffer);
2863 if (res != OK) {
2864 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002865 " stream %d: %s (%d)", __FUNCTION__,
2866 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002867 }
2868 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002869 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2870 if (idx == NAME_NOT_FOUND) {
2871 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2872 continue;
2873 }
2874 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002875 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2876 }
2877 }
2878}
2879
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002880void Camera3Device::insertResultLocked(CaptureResult *result,
2881 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002882 if (result == nullptr) return;
2883
Emilian Peev71c73a22017-03-21 16:35:51 +00002884 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2885 result->mMetadata.getAndLock());
2886 set_camera_metadata_vendor_id(meta, mVendorTagId);
2887 result->mMetadata.unlock(meta);
2888
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002889 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2890 (int32_t*)&frameNumber, 1) != OK) {
2891 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2892 return;
2893 }
2894
2895 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2896 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2897 return;
2898 }
2899
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002900 // Valid result, insert into queue
2901 List<CaptureResult>::iterator queuedResult =
2902 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2903 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2904 ", burstId = %" PRId32, __FUNCTION__,
2905 queuedResult->mResultExtras.requestId,
2906 queuedResult->mResultExtras.frameNumber,
2907 queuedResult->mResultExtras.burstId);
2908
2909 mResultSignal.signal();
2910}
2911
2912
2913void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002914 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002915 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002916 Mutex::Autolock l(mOutputLock);
2917
2918 CaptureResult captureResult;
2919 captureResult.mResultExtras = resultExtras;
2920 captureResult.mMetadata = partialResult;
2921
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002922 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002923}
2924
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002925
2926void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2927 CaptureResultExtras &resultExtras,
2928 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002929 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002930 bool reprocess,
2931 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002932 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002933 if (pendingMetadata.isEmpty())
2934 return;
2935
2936 Mutex::Autolock l(mOutputLock);
2937
2938 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002939 if (reprocess) {
2940 if (frameNumber < mNextReprocessResultFrameNumber) {
2941 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002942 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002943 frameNumber, mNextReprocessResultFrameNumber);
2944 return;
2945 }
2946 mNextReprocessResultFrameNumber = frameNumber + 1;
2947 } else {
2948 if (frameNumber < mNextResultFrameNumber) {
2949 SET_ERR("Out-of-order capture result metadata submitted! "
2950 "(got frame number %d, expecting %d)",
2951 frameNumber, mNextResultFrameNumber);
2952 return;
2953 }
2954 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002955 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002956
2957 CaptureResult captureResult;
2958 captureResult.mResultExtras = resultExtras;
2959 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002960 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002961
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002962 // Append any previous partials to form a complete result
2963 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2964 captureResult.mMetadata.append(collectedPartialResult);
2965 }
2966
2967 captureResult.mMetadata.sort();
2968
2969 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002970 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2971 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002972 SET_ERR("No timestamp provided by HAL for frame %d!",
2973 frameNumber);
2974 return;
2975 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002976 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
2977 camera_metadata_entry timestamp =
2978 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2979 if (timestamp.count == 0) {
2980 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
2981 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
2982 return;
2983 }
2984 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002985
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002986 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2987 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2988
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002989 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002990}
2991
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002992/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002993 * Camera HAL device callback methods
2994 */
2995
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002996void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002997 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002998
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002999 status_t res;
3000
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003001 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003002 if (result->result == NULL && result->num_output_buffers == 0 &&
3003 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003004 SET_ERR("No result data provided by HAL for frame %d",
3005 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003006 return;
3007 }
Zhijun He204e3292014-07-14 17:09:23 -07003008
Zhijun He204e3292014-07-14 17:09:23 -07003009 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003010 result->result != NULL &&
3011 result->partial_result != 1) {
3012 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3013 " if partial result is not supported",
3014 frameNumber, result->partial_result);
3015 return;
3016 }
3017
3018 bool isPartialResult = false;
3019 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003020 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003021
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003022 // Get shutter timestamp and resultExtras from list of in-flight requests,
3023 // where it was added by the shutter notification for this frame. If the
3024 // shutter timestamp isn't received yet, append the output buffers to the
3025 // in-flight request and they will be returned when the shutter timestamp
3026 // arrives. Update the in-flight status and remove the in-flight entry if
3027 // all result data and shutter timestamp have been received.
3028 nsecs_t shutterTimestamp = 0;
3029
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003030 {
3031 Mutex::Autolock l(mInFlightLock);
3032 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3033 if (idx == NAME_NOT_FOUND) {
3034 SET_ERR("Unknown frame number for capture result: %d",
3035 frameNumber);
3036 return;
3037 }
3038 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003039 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3040 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003041 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003042 __FUNCTION__, request.resultExtras.requestId,
3043 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003044 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003045 // Always update the partial count to the latest one if it's not 0
3046 // (buffers only). When framework aggregates adjacent partial results
3047 // into one, the latest partial count will be used.
3048 if (result->partial_result != 0)
3049 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003050
3051 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003052 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003053 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3054 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3055 " the range of [1, %d] when metadata is included in the result",
3056 frameNumber, result->partial_result, mNumPartialResults);
3057 return;
3058 }
3059 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003060 if (isPartialResult && result->num_physcam_metadata) {
3061 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3062 " physical camera result", frameNumber);
3063 return;
3064 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003065 if (isPartialResult) {
3066 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003067 }
3068
Shuzhen Wang4a472662017-02-26 23:29:04 -08003069 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003070 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003071 sendPartialCaptureResult(result->result, request.resultExtras,
3072 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003073 }
3074 }
3075
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003076 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003077 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003078
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003079 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003080 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003081 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3082 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3083 request.physicalCameraIds.size(), result->num_physcam_metadata);
3084 return;
3085 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003086 if (request.haveResultMetadata) {
3087 SET_ERR("Called multiple times with metadata for frame %d",
3088 frameNumber);
3089 return;
3090 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003091 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3092 String8 physicalId(result->physcam_ids[i]);
3093 std::set<String8>::iterator cameraIdIter =
3094 request.physicalCameraIds.find(physicalId);
3095 if (cameraIdIter != request.physicalCameraIds.end()) {
3096 request.physicalCameraIds.erase(cameraIdIter);
3097 } else {
3098 SET_ERR("Total result for frame %d has already returned for camera %s",
3099 frameNumber, physicalId.c_str());
3100 return;
3101 }
3102 }
Zhijun He204e3292014-07-14 17:09:23 -07003103 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003104 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003105 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003106 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003107 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003108 request.haveResultMetadata = true;
3109 }
3110
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003111 uint32_t numBuffersReturned = result->num_output_buffers;
3112 if (result->input_buffer != NULL) {
3113 if (hasInputBufferInRequest) {
3114 numBuffersReturned += 1;
3115 } else {
3116 ALOGW("%s: Input buffer should be NULL if there is no input"
3117 " buffer sent in the request",
3118 __FUNCTION__);
3119 }
3120 }
3121 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003122 if (request.numBuffersLeft < 0) {
3123 SET_ERR("Too many buffers returned for frame %d",
3124 frameNumber);
3125 return;
3126 }
3127
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003128 camera_metadata_ro_entry_t entry;
3129 res = find_camera_metadata_ro_entry(result->result,
3130 ANDROID_SENSOR_TIMESTAMP, &entry);
3131 if (res == OK && entry.count == 1) {
3132 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003133 }
3134
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003135 // If shutter event isn't received yet, append the output buffers to
3136 // the in-flight request. Otherwise, return the output buffers to
3137 // streams.
3138 if (shutterTimestamp == 0) {
3139 request.pendingOutputBuffers.appendArray(result->output_buffers,
3140 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003141 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003142 returnOutputBuffers(result->output_buffers,
3143 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003144 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003145
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003146 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003147 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3148 CameraMetadata physicalMetadata;
3149 physicalMetadata.append(result->physcam_metadata[i]);
3150 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3151 physicalMetadata});
3152 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003153 if (shutterTimestamp == 0) {
3154 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003155 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003156 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003157 CameraMetadata metadata;
3158 metadata = result->result;
3159 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003160 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003161 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003162 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003163 }
3164
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003165 removeInFlightRequestIfReadyLocked(idx);
3166 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003167
Zhijun Hef0d962a2014-06-30 10:24:11 -07003168 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003169 if (hasInputBufferInRequest) {
3170 Camera3Stream *stream =
3171 Camera3Stream::cast(result->input_buffer->stream);
3172 res = stream->returnInputBuffer(*(result->input_buffer));
3173 // Note: stream may be deallocated at this point, if this buffer was the
3174 // last reference to it.
3175 if (res != OK) {
3176 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3177 " its stream:%s (%d)", __FUNCTION__,
3178 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003179 }
3180 } else {
3181 ALOGW("%s: Input buffer should be NULL if there is no input"
3182 " buffer sent in the request, skipping input buffer return.",
3183 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003184 }
3185 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003186}
3187
3188void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003189 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003190 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003191 {
3192 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003193 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003194 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003195
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003196 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003197 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003198 return;
3199 }
3200
3201 switch (msg->type) {
3202 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003203 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003204 break;
3205 }
3206 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003207 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003208 break;
3209 }
3210 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003211 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003212 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003213 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003214}
3215
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003216void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003217 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003218 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003219 // Map camera HAL error codes to ICameraDeviceCallback error codes
3220 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003221 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003222 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003223 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003224 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003225 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003226 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003227 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003228 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003229 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003230 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003231 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003232 };
3233
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003234 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003235 ((msg.error_code >= 0) &&
3236 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3237 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003238 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003239
3240 int streamId = 0;
3241 if (msg.error_stream != NULL) {
3242 Camera3Stream *stream =
3243 Camera3Stream::cast(msg.error_stream);
3244 streamId = stream->getId();
3245 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003246 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3247 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003248 streamId, msg.error_code);
3249
3250 CaptureResultExtras resultExtras;
3251 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003252 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003253 // SET_ERR calls notifyError
3254 SET_ERR("Camera HAL reported serious device error");
3255 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003256 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3257 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3258 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003259 {
3260 Mutex::Autolock l(mInFlightLock);
3261 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3262 if (idx >= 0) {
3263 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3264 r.requestStatus = msg.error_code;
3265 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003266 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3267 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3268 errorCode) {
3269 r.skipResultMetadata = true;
3270 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003271 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3272 errorCode) {
3273 // In case of missing result check whether the buffers
3274 // returned. If they returned, then remove inflight
3275 // request.
3276 removeInFlightRequestIfReadyLocked(idx);
3277 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003278 } else {
3279 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003280 ALOGE("Camera %s: %s: cannot find in-flight request on "
3281 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003282 resultExtras.frameNumber);
3283 }
3284 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003285 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003286 if (listener != NULL) {
3287 listener->notifyError(errorCode, resultExtras);
3288 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003289 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003290 }
3291 break;
3292 default:
3293 // SET_ERR calls notifyError
3294 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3295 break;
3296 }
3297}
3298
3299void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003300 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003301 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003302 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003303
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003304 // Set timestamp for the request in the in-flight tracking
3305 // and get the request ID to send upstream
3306 {
3307 Mutex::Autolock l(mInFlightLock);
3308 idx = mInFlightMap.indexOfKey(msg.frame_number);
3309 if (idx >= 0) {
3310 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003311
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003312 // Verify ordering of shutter notifications
3313 {
3314 Mutex::Autolock l(mOutputLock);
3315 // TODO: need to track errors for tighter bounds on expected frame number.
3316 if (r.hasInputBuffer) {
3317 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3318 SET_ERR("Shutter notification out-of-order. Expected "
3319 "notification for frame %d, got frame %d",
3320 mNextReprocessShutterFrameNumber, msg.frame_number);
3321 return;
3322 }
3323 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3324 } else {
3325 if (msg.frame_number < mNextShutterFrameNumber) {
3326 SET_ERR("Shutter notification out-of-order. Expected "
3327 "notification for frame %d, got frame %d",
3328 mNextShutterFrameNumber, msg.frame_number);
3329 return;
3330 }
3331 mNextShutterFrameNumber = msg.frame_number + 1;
3332 }
3333 }
3334
Shuzhen Wang4a472662017-02-26 23:29:04 -08003335 r.shutterTimestamp = msg.timestamp;
3336 if (r.hasCallback) {
3337 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003338 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003339 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003340 // Call listener, if any
3341 if (listener != NULL) {
3342 listener->notifyShutter(r.resultExtras, msg.timestamp);
3343 }
3344 // send pending result and buffers
3345 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3346 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003347 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003348 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003349 returnOutputBuffers(r.pendingOutputBuffers.array(),
3350 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3351 r.pendingOutputBuffers.clear();
3352
3353 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003354 }
3355 }
3356 if (idx < 0) {
3357 SET_ERR("Shutter notification for non-existent frame number %d",
3358 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003359 }
3360}
3361
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003362CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003363 ALOGV("%s", __FUNCTION__);
3364
Igor Murashkin1e479c02013-09-06 16:55:14 -07003365 CameraMetadata retVal;
3366
3367 if (mRequestThread != NULL) {
3368 retVal = mRequestThread->getLatestRequest();
3369 }
3370
Igor Murashkin1e479c02013-09-06 16:55:14 -07003371 return retVal;
3372}
3373
Jianing Weicb0652e2014-03-12 18:29:36 -07003374
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003375void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3376 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3377 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3378}
3379
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003380/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003381 * HalInterface inner class methods
3382 */
3383
Yifan Hongf79b5542017-04-11 14:44:25 -07003384Camera3Device::HalInterface::HalInterface(
3385 sp<ICameraDeviceSession> &session,
3386 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003387 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003388 mRequestMetadataQueue(queue) {
3389 // Check with hardware service manager if we can downcast these interfaces
3390 // Somewhat expensive, so cache the results at startup
3391 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3392 if (castResult_3_4.isOk()) {
3393 mHidlSession_3_4 = castResult_3_4;
3394 }
3395 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3396 if (castResult_3_3.isOk()) {
3397 mHidlSession_3_3 = castResult_3_3;
3398 }
3399}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003400
Emilian Peev31abd0a2017-05-11 18:37:46 +01003401Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003402
3403Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003404 mHidlSession(other.mHidlSession),
3405 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003406
3407bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003408 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003409}
3410
3411void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003412 mHidlSession_3_4.clear();
3413 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003414 mHidlSession.clear();
3415}
3416
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003417bool Camera3Device::HalInterface::supportBatchRequest() {
3418 return mHidlSession != nullptr;
3419}
3420
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003421status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3422 camera3_request_template_t templateId,
3423 /*out*/ camera_metadata_t **requestTemplate) {
3424 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3425 if (!valid()) return INVALID_OPERATION;
3426 status_t res = OK;
3427
Emilian Peev31abd0a2017-05-11 18:37:46 +01003428 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003429
3430 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003431 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003432 status = s;
3433 if (status == common::V1_0::Status::OK) {
3434 const camera_metadata *r =
3435 reinterpret_cast<const camera_metadata_t*>(request.data());
3436 size_t expectedSize = request.size();
3437 int ret = validate_camera_metadata_structure(r, &expectedSize);
3438 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3439 *requestTemplate = clone_camera_metadata(r);
3440 if (*requestTemplate == nullptr) {
3441 ALOGE("%s: Unable to clone camera metadata received from HAL",
3442 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003443 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003444 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003445 } else {
3446 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3447 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003448 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003449 }
3450 };
3451 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003452 RequestTemplate id;
3453 switch (templateId) {
3454 case CAMERA3_TEMPLATE_PREVIEW:
3455 id = RequestTemplate::PREVIEW;
3456 break;
3457 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3458 id = RequestTemplate::STILL_CAPTURE;
3459 break;
3460 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3461 id = RequestTemplate::VIDEO_RECORD;
3462 break;
3463 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3464 id = RequestTemplate::VIDEO_SNAPSHOT;
3465 break;
3466 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3467 id = RequestTemplate::ZERO_SHUTTER_LAG;
3468 break;
3469 case CAMERA3_TEMPLATE_MANUAL:
3470 id = RequestTemplate::MANUAL;
3471 break;
3472 default:
3473 // Unknown template ID, or this HAL is too old to support it
3474 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003475 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003476 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003477
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 if (!err.isOk()) {
3479 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3480 res = DEAD_OBJECT;
3481 } else {
3482 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003483 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003484
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003485 return res;
3486}
3487
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003488status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003489 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003490 ATRACE_NAME("CameraHal::configureStreams");
3491 if (!valid()) return INVALID_OPERATION;
3492 status_t res = OK;
3493
Emilian Peev31abd0a2017-05-11 18:37:46 +01003494 // Convert stream config to HIDL
3495 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003496 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3497 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3498 requestedConfiguration3_2.streams.resize(config->num_streams);
3499 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003500 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003501 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3502 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003503 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003504
Emilian Peev31abd0a2017-05-11 18:37:46 +01003505 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3506 cam3stream->setBufferFreedListener(this);
3507 int streamId = cam3stream->getId();
3508 StreamType streamType;
3509 switch (src->stream_type) {
3510 case CAMERA3_STREAM_OUTPUT:
3511 streamType = StreamType::OUTPUT;
3512 break;
3513 case CAMERA3_STREAM_INPUT:
3514 streamType = StreamType::INPUT;
3515 break;
3516 default:
3517 ALOGE("%s: Stream %d: Unsupported stream type %d",
3518 __FUNCTION__, streamId, config->streams[i]->stream_type);
3519 return BAD_VALUE;
3520 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003521 dst3_2.id = streamId;
3522 dst3_2.streamType = streamType;
3523 dst3_2.width = src->width;
3524 dst3_2.height = src->height;
3525 dst3_2.format = mapToPixelFormat(src->format);
3526 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3527 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3528 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3529 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003530 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003531 if (src->physical_camera_id != nullptr) {
3532 dst3_4.physicalCameraId = src->physical_camera_id;
3533 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003534
3535 activeStreams.insert(streamId);
3536 // Create Buffer ID map if necessary
3537 if (mBufferIdMaps.count(streamId) == 0) {
3538 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3539 }
3540 }
3541 // remove BufferIdMap for deleted streams
3542 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3543 int streamId = it->first;
3544 bool active = activeStreams.count(streamId) > 0;
3545 if (!active) {
3546 it = mBufferIdMaps.erase(it);
3547 } else {
3548 ++it;
3549 }
3550 }
3551
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003552 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 res = mapToStreamConfigurationMode(
3554 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003555 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003556 if (res != OK) {
3557 return res;
3558 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003559 requestedConfiguration3_2.operationMode = operationMode;
3560 requestedConfiguration3_4.operationMode = operationMode;
3561 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003562 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3563 get_camera_metadata_size(sessionParams));
3564
Emilian Peev31abd0a2017-05-11 18:37:46 +01003565 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003566 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003567 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003568
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003569 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003570 if (mHidlSession_3_4 != nullptr) {
3571 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003572 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003573 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003574 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003575 [&status, &finalConfiguration3_4]
3576 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3577 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003578 status = s;
3579 });
3580 if (!err.isOk()) {
3581 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3582 return DEAD_OBJECT;
3583 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003584 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3585 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3586 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3587 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003588 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003589 // We do; use v3.3 for the call
3590 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003591 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003592 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003593 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003594 finalConfiguration = halConfiguration;
3595 status = s;
3596 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003597 if (!err.isOk()) {
3598 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3599 return DEAD_OBJECT;
3600 }
3601 } else {
3602 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3603 ALOGV("%s: v3.2 device found", __FUNCTION__);
3604 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003605 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003606 [&status, &finalConfiguration_3_2]
3607 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3608 finalConfiguration_3_2 = halConfiguration;
3609 status = s;
3610 });
3611 if (!err.isOk()) {
3612 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3613 return DEAD_OBJECT;
3614 }
3615 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3616 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3617 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3618 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003619 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003620 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003621 }
3622
3623 if (status != common::V1_0::Status::OK ) {
3624 return CameraProviderManager::mapToStatusT(status);
3625 }
3626
3627 // And convert output stream configuration from HIDL
3628
3629 for (size_t i = 0; i < config->num_streams; i++) {
3630 camera3_stream_t *dst = config->streams[i];
3631 int streamId = Camera3Stream::cast(dst)->getId();
3632
3633 // Start scan at i, with the assumption that the stream order matches
3634 size_t realIdx = i;
3635 bool found = false;
3636 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003637 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003638 found = true;
3639 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003640 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003641 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3642 }
3643 if (!found) {
3644 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3645 __FUNCTION__, streamId);
3646 return INVALID_OPERATION;
3647 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003648 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003649
Emilian Peev710c1422017-08-30 11:19:38 +01003650 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3651 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003652 dstStream->setDataSpaceOverride(false);
3653 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3654 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3655
Emilian Peev31abd0a2017-05-11 18:37:46 +01003656 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3657 if (dst->format != overrideFormat) {
3658 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3659 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003660 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003661 if (dst->data_space != overrideDataSpace) {
3662 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3663 streamId, dst->format);
3664 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003665 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003666 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003667 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3668
Emilian Peev31abd0a2017-05-11 18:37:46 +01003669 // Override allowed with IMPLEMENTATION_DEFINED
3670 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003671 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003672 }
3673
Emilian Peev31abd0a2017-05-11 18:37:46 +01003674 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003675 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003676 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003677 __FUNCTION__, streamId);
3678 return INVALID_OPERATION;
3679 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003680 dstStream->setUsage(
3681 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003682 } else {
3683 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003684 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003685 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3686 __FUNCTION__, streamId);
3687 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003688 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003689 dstStream->setUsage(
3690 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003691 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003692 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003693 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003694
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003695 return res;
3696}
3697
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003698void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3699 /*out*/device::V3_2::CaptureRequest* captureRequest,
3700 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003701 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003702 if (captureRequest == nullptr || handlesCreated == nullptr) {
3703 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3704 __FUNCTION__, captureRequest, handlesCreated);
3705 return;
3706 }
3707
3708 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003709
3710 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003711
3712 {
3713 std::lock_guard<std::mutex> lock(mInflightLock);
3714 if (request->input_buffer != nullptr) {
3715 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3716 buffer_handle_t buf = *(request->input_buffer->buffer);
3717 auto pair = getBufferId(buf, streamId);
3718 bool isNewBuffer = pair.first;
3719 uint64_t bufferId = pair.second;
3720 captureRequest->inputBuffer.streamId = streamId;
3721 captureRequest->inputBuffer.bufferId = bufferId;
3722 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3723 captureRequest->inputBuffer.status = BufferStatus::OK;
3724 native_handle_t *acquireFence = nullptr;
3725 if (request->input_buffer->acquire_fence != -1) {
3726 acquireFence = native_handle_create(1,0);
3727 acquireFence->data[0] = request->input_buffer->acquire_fence;
3728 handlesCreated->push_back(acquireFence);
3729 }
3730 captureRequest->inputBuffer.acquireFence = acquireFence;
3731 captureRequest->inputBuffer.releaseFence = nullptr;
3732
3733 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3734 request->input_buffer->buffer,
3735 request->input_buffer->acquire_fence);
3736 } else {
3737 captureRequest->inputBuffer.streamId = -1;
3738 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3739 }
3740
3741 captureRequest->outputBuffers.resize(request->num_output_buffers);
3742 for (size_t i = 0; i < request->num_output_buffers; i++) {
3743 const camera3_stream_buffer_t *src = request->output_buffers + i;
3744 StreamBuffer &dst = captureRequest->outputBuffers[i];
3745 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3746 buffer_handle_t buf = *(src->buffer);
3747 auto pair = getBufferId(buf, streamId);
3748 bool isNewBuffer = pair.first;
3749 dst.streamId = streamId;
3750 dst.bufferId = pair.second;
3751 dst.buffer = isNewBuffer ? buf : nullptr;
3752 dst.status = BufferStatus::OK;
3753 native_handle_t *acquireFence = nullptr;
3754 if (src->acquire_fence != -1) {
3755 acquireFence = native_handle_create(1,0);
3756 acquireFence->data[0] = src->acquire_fence;
3757 handlesCreated->push_back(acquireFence);
3758 }
3759 dst.acquireFence = acquireFence;
3760 dst.releaseFence = nullptr;
3761
3762 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3763 src->buffer, src->acquire_fence);
3764 }
3765 }
3766}
3767
3768status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3769 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3770 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3771 if (!valid()) return INVALID_OPERATION;
3772
Emilian Peevaebbe412018-01-15 13:53:24 +00003773 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3774 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3775 if (castResult_3_4.isOk()) {
3776 hidlSession_3_4 = castResult_3_4;
3777 }
3778
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003779 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003780 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003781 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003782 if (hidlSession_3_4 != nullptr) {
3783 captureRequests_3_4.resize(batchSize);
3784 } else {
3785 captureRequests.resize(batchSize);
3786 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003787 std::vector<native_handle_t*> handlesCreated;
3788
3789 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003790 if (hidlSession_3_4 != nullptr) {
3791 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3792 /*out*/&handlesCreated);
3793 } else {
3794 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3795 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003796 }
3797
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003798 std::vector<device::V3_2::BufferCache> cachesToRemove;
3799 {
3800 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3801 for (auto& pair : mFreedBuffers) {
3802 // The stream might have been removed since onBufferFreed
3803 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3804 cachesToRemove.push_back({pair.first, pair.second});
3805 }
3806 }
3807 mFreedBuffers.clear();
3808 }
3809
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003810 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3811 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003812
3813 // Write metadata to FMQ.
3814 for (size_t i = 0; i < batchSize; i++) {
3815 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003816 device::V3_2::CaptureRequest* captureRequest;
3817 if (hidlSession_3_4 != nullptr) {
3818 captureRequest = &captureRequests_3_4[i].v3_2;
3819 } else {
3820 captureRequest = &captureRequests[i];
3821 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003822
3823 if (request->settings != nullptr) {
3824 size_t settingsSize = get_camera_metadata_size(request->settings);
3825 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3826 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3827 captureRequest->settings.resize(0);
3828 captureRequest->fmqSettingsSize = settingsSize;
3829 } else {
3830 if (mRequestMetadataQueue != nullptr) {
3831 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3832 }
3833 captureRequest->settings.setToExternal(
3834 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3835 get_camera_metadata_size(request->settings));
3836 captureRequest->fmqSettingsSize = 0u;
3837 }
3838 } else {
3839 // A null request settings maps to a size-0 CameraMetadata
3840 captureRequest->settings.resize(0);
3841 captureRequest->fmqSettingsSize = 0u;
3842 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003843
3844 if (hidlSession_3_4 != nullptr) {
3845 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3846 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003847 if (request->physcam_settings != nullptr) {
3848 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3849 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3850 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3851 settingsSize)) {
3852 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3853 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3854 settingsSize;
3855 } else {
3856 if (mRequestMetadataQueue != nullptr) {
3857 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3858 }
3859 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3860 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3861 request->physcam_settings[j])),
3862 get_camera_metadata_size(request->physcam_settings[j]));
3863 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003864 }
Emilian Peev00420d22018-02-05 21:33:13 +00003865 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003866 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003867 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003868 }
3869 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3870 request->physcam_id[j];
3871 }
3872 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003873 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003874
3875 hardware::details::return_status err;
3876 if (hidlSession_3_4 != nullptr) {
3877 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003878 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3879 status = s;
3880 *numRequestProcessed = n;
3881 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003882 } else {
3883 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3884 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3885 status = s;
3886 *numRequestProcessed = n;
3887 });
3888 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003889 if (!err.isOk()) {
3890 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3891 return DEAD_OBJECT;
3892 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003893 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3894 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3895 __FUNCTION__, *numRequestProcessed, batchSize);
3896 status = common::V1_0::Status::INTERNAL_ERROR;
3897 }
3898
3899 for (auto& handle : handlesCreated) {
3900 native_handle_delete(handle);
3901 }
3902 return CameraProviderManager::mapToStatusT(status);
3903}
3904
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003905status_t Camera3Device::HalInterface::processCaptureRequest(
3906 camera3_capture_request_t *request) {
3907 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003908 if (!valid()) return INVALID_OPERATION;
3909 status_t res = OK;
3910
Emilian Peev31abd0a2017-05-11 18:37:46 +01003911 uint32_t numRequestProcessed = 0;
3912 std::vector<camera3_capture_request_t*> requests(1);
3913 requests[0] = request;
3914 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3915
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003916 return res;
3917}
3918
3919status_t Camera3Device::HalInterface::flush() {
3920 ATRACE_NAME("CameraHal::flush");
3921 if (!valid()) return INVALID_OPERATION;
3922 status_t res = OK;
3923
Emilian Peev31abd0a2017-05-11 18:37:46 +01003924 auto err = mHidlSession->flush();
3925 if (!err.isOk()) {
3926 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3927 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003928 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003929 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003930 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003931
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003932 return res;
3933}
3934
Emilian Peev31abd0a2017-05-11 18:37:46 +01003935status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003936 ATRACE_NAME("CameraHal::dump");
3937 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003938
Emilian Peev31abd0a2017-05-11 18:37:46 +01003939 // Handled by CameraProviderManager::dump
3940
3941 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003942}
3943
3944status_t Camera3Device::HalInterface::close() {
3945 ATRACE_NAME("CameraHal::close()");
3946 if (!valid()) return INVALID_OPERATION;
3947 status_t res = OK;
3948
Emilian Peev31abd0a2017-05-11 18:37:46 +01003949 auto err = mHidlSession->close();
3950 // Interface will be dead shortly anyway, so don't log errors
3951 if (!err.isOk()) {
3952 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003953 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003955 return res;
3956}
3957
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003958void Camera3Device::HalInterface::getInflightBufferKeys(
3959 std::vector<std::pair<int32_t, int32_t>>* out) {
3960 std::lock_guard<std::mutex> lock(mInflightLock);
3961 out->clear();
3962 out->reserve(mInflightBufferMap.size());
3963 for (auto& pair : mInflightBufferMap) {
3964 uint64_t key = pair.first;
3965 int32_t streamId = key & 0xFFFFFFFF;
3966 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3967 out->push_back(std::make_pair(frameNumber, streamId));
3968 }
3969 return;
3970}
3971
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003973 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003975 auto pair = std::make_pair(buffer, acquireFence);
3976 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977 return OK;
3978}
3979
3980status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003981 int32_t frameNumber, int32_t streamId,
3982 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003983 std::lock_guard<std::mutex> lock(mInflightLock);
3984
3985 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3986 auto it = mInflightBufferMap.find(key);
3987 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003988 auto pair = it->second;
3989 *buffer = pair.first;
3990 int acquireFence = pair.second;
3991 if (acquireFence > 0) {
3992 ::close(acquireFence);
3993 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 mInflightBufferMap.erase(it);
3995 return OK;
3996}
3997
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003998std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3999 const buffer_handle_t& buf, int streamId) {
4000 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4001
4002 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4003 auto it = bIdMap.find(buf);
4004 if (it == bIdMap.end()) {
4005 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004006 ALOGV("stream %d now have %zu buffer caches, buf %p",
4007 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004008 return std::make_pair(true, mNextBufferId - 1);
4009 } else {
4010 return std::make_pair(false, it->second);
4011 }
4012}
4013
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004014void Camera3Device::HalInterface::onBufferFreed(
4015 int streamId, const native_handle_t* handle) {
4016 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4017 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4018 auto mapIt = mBufferIdMaps.find(streamId);
4019 if (mapIt == mBufferIdMaps.end()) {
4020 // streamId might be from a deleted stream here
4021 ALOGI("%s: stream %d has been removed",
4022 __FUNCTION__, streamId);
4023 return;
4024 }
4025 BufferIdMap& bIdMap = mapIt->second;
4026 auto it = bIdMap.find(handle);
4027 if (it == bIdMap.end()) {
4028 ALOGW("%s: cannot find buffer %p in stream %d",
4029 __FUNCTION__, handle, streamId);
4030 return;
4031 } else {
4032 bufferId = it->second;
4033 bIdMap.erase(it);
4034 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4035 __FUNCTION__, streamId, bIdMap.size(), handle);
4036 }
4037 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4038}
4039
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004040/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004041 * RequestThread inner class methods
4042 */
4043
4044Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004045 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004046 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004047 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004048 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004049 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004050 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004051 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004052 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004053 mReconfigured(false),
4054 mDoPause(false),
4055 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004056 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004057 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004058 mCurrentAfTriggerId(0),
4059 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004060 mRepeatingLastFrameNumber(
4061 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004062 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004063 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004064 mRequestLatency(kRequestLatencyBinSize),
4065 mSessionParamKeys(sessionParamKeys),
4066 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004067 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004068}
4069
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004070Camera3Device::RequestThread::~RequestThread() {}
4071
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004072void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004073 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004074 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004075 Mutex::Autolock l(mRequestLock);
4076 mListener = listener;
4077}
4078
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004079void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4080 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004081 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004082 Mutex::Autolock l(mRequestLock);
4083 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004084 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004085 // Prepare video stream for high speed recording.
4086 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004087 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004088}
4089
Jianing Wei90e59c92014-03-12 18:29:36 -07004090status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004091 List<sp<CaptureRequest> > &requests,
4092 /*out*/
4093 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004094 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004095 Mutex::Autolock l(mRequestLock);
4096 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4097 ++it) {
4098 mRequestQueue.push_back(*it);
4099 }
4100
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004101 if (lastFrameNumber != NULL) {
4102 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4103 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4104 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4105 *lastFrameNumber);
4106 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004107
Jianing Wei90e59c92014-03-12 18:29:36 -07004108 unpauseForNewRequests();
4109
4110 return OK;
4111}
4112
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004113
4114status_t Camera3Device::RequestThread::queueTrigger(
4115 RequestTrigger trigger[],
4116 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004117 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004118 Mutex::Autolock l(mTriggerMutex);
4119 status_t ret;
4120
4121 for (size_t i = 0; i < count; ++i) {
4122 ret = queueTriggerLocked(trigger[i]);
4123
4124 if (ret != OK) {
4125 return ret;
4126 }
4127 }
4128
4129 return OK;
4130}
4131
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004132const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4133 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004134 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004135 if (d != nullptr) return d->mId;
4136 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004137}
4138
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004139status_t Camera3Device::RequestThread::queueTriggerLocked(
4140 RequestTrigger trigger) {
4141
4142 uint32_t tag = trigger.metadataTag;
4143 ssize_t index = mTriggerMap.indexOfKey(tag);
4144
4145 switch (trigger.getTagType()) {
4146 case TYPE_BYTE:
4147 // fall-through
4148 case TYPE_INT32:
4149 break;
4150 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004151 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4152 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004153 return INVALID_OPERATION;
4154 }
4155
4156 /**
4157 * Collect only the latest trigger, since we only have 1 field
4158 * in the request settings per trigger tag, and can't send more than 1
4159 * trigger per request.
4160 */
4161 if (index != NAME_NOT_FOUND) {
4162 mTriggerMap.editValueAt(index) = trigger;
4163 } else {
4164 mTriggerMap.add(tag, trigger);
4165 }
4166
4167 return OK;
4168}
4169
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004170status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004171 const RequestList &requests,
4172 /*out*/
4173 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004174 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004175 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004176 if (lastFrameNumber != NULL) {
4177 *lastFrameNumber = mRepeatingLastFrameNumber;
4178 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004179 mRepeatingRequests.clear();
4180 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4181 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004182
4183 unpauseForNewRequests();
4184
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004185 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004186 return OK;
4187}
4188
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004189bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004190 if (mRepeatingRequests.empty()) {
4191 return false;
4192 }
4193 int32_t requestId = requestIn->mResultExtras.requestId;
4194 const RequestList &repeatRequests = mRepeatingRequests;
4195 // All repeating requests are guaranteed to have same id so only check first quest
4196 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4197 return (firstRequest->mResultExtras.requestId == requestId);
4198}
4199
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004200status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004201 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004202 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004203 return clearRepeatingRequestsLocked(lastFrameNumber);
4204
4205}
4206
4207status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004208 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004209 if (lastFrameNumber != NULL) {
4210 *lastFrameNumber = mRepeatingLastFrameNumber;
4211 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004212 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004213 return OK;
4214}
4215
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004216status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004217 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004218 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004219 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004220 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004221
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004222 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004223
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004224 // Send errors for all requests pending in the request queue, including
4225 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004226 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004227 if (listener != NULL) {
4228 for (RequestList::iterator it = mRequestQueue.begin();
4229 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004230 // Abort the input buffers for reprocess requests.
4231 if ((*it)->mInputStream != NULL) {
4232 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004233 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4234 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004235 if (res != OK) {
4236 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4237 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4238 } else {
4239 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4240 if (res != OK) {
4241 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4242 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4243 }
4244 }
4245 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004246 // Set the frame number this request would have had, if it
4247 // had been submitted; this frame number will not be reused.
4248 // The requestId and burstId fields were set when the request was
4249 // submitted originally (in convertMetadataListToRequestListLocked)
4250 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004251 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004252 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004253 }
4254 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004255 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004256
4257 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004258 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004259 if (lastFrameNumber != NULL) {
4260 *lastFrameNumber = mRepeatingLastFrameNumber;
4261 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004262 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004263 return OK;
4264}
4265
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004266status_t Camera3Device::RequestThread::flush() {
4267 ATRACE_CALL();
4268 Mutex::Autolock l(mFlushLock);
4269
Emilian Peev08dd2452017-04-06 16:55:14 +01004270 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271}
4272
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004273void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004274 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004275 Mutex::Autolock l(mPauseLock);
4276 mDoPause = paused;
4277 mDoPauseSignal.signal();
4278}
4279
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004280status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4281 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004282 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004283 Mutex::Autolock l(mLatestRequestMutex);
4284 status_t res;
4285 while (mLatestRequestId != requestId) {
4286 nsecs_t startTime = systemTime();
4287
4288 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4289 if (res != OK) return res;
4290
4291 timeout -= (systemTime() - startTime);
4292 }
4293
4294 return OK;
4295}
4296
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297void Camera3Device::RequestThread::requestExit() {
4298 // Call parent to set up shutdown
4299 Thread::requestExit();
4300 // The exit from any possible waits
4301 mDoPauseSignal.signal();
4302 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004303
4304 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4305 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004306}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004307
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004308void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004309 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004310 bool surfaceAbandoned = false;
4311 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004312 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004313 {
4314 Mutex::Autolock l(mRequestLock);
4315 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4316 // repeating requests.
4317 for (const auto& request : mRepeatingRequests) {
4318 for (const auto& s : request->mOutputStreams) {
4319 if (s->isAbandoned()) {
4320 surfaceAbandoned = true;
4321 clearRepeatingRequestsLocked(&lastFrameNumber);
4322 break;
4323 }
4324 }
4325 if (surfaceAbandoned) {
4326 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004327 }
4328 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004329 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004330 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004331
4332 if (listener != NULL && surfaceAbandoned) {
4333 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004334 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004335}
4336
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004337bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004338 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004339 status_t res;
4340 size_t batchSize = mNextRequests.size();
4341 std::vector<camera3_capture_request_t*> requests(batchSize);
4342 uint32_t numRequestProcessed = 0;
4343 for (size_t i = 0; i < batchSize; i++) {
4344 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004345 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004346 }
4347
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004348 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4349
4350 bool triggerRemoveFailed = false;
4351 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4352 for (size_t i = 0; i < numRequestProcessed; i++) {
4353 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4354 nextRequest.submitted = true;
4355
4356
4357 // Update the latest request sent to HAL
4358 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4359 Mutex::Autolock al(mLatestRequestMutex);
4360
4361 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4362 mLatestRequest.acquire(cloned);
4363
4364 sp<Camera3Device> parent = mParent.promote();
4365 if (parent != NULL) {
4366 parent->monitorMetadata(TagMonitor::REQUEST,
4367 nextRequest.halRequest.frame_number,
4368 0, mLatestRequest);
4369 }
4370 }
4371
4372 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004373 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4374 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004375 }
4376
Emilian Peevaebbe412018-01-15 13:53:24 +00004377 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4378
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004379 if (!triggerRemoveFailed) {
4380 // Remove any previously queued triggers (after unlock)
4381 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4382 if (removeTriggerRes != OK) {
4383 triggerRemoveFailed = true;
4384 triggerFailedRequest = nextRequest;
4385 }
4386 }
4387 }
4388
4389 if (triggerRemoveFailed) {
4390 SET_ERR("RequestThread: Unable to remove triggers "
4391 "(capture request %d, HAL device: %s (%d)",
4392 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4393 cleanUpFailedRequests(/*sendRequestError*/ false);
4394 return false;
4395 }
4396
4397 if (res != OK) {
4398 // Should only get a failure here for malformed requests or device-level
4399 // errors, so consider all errors fatal. Bad metadata failures should
4400 // come through notify.
4401 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4402 mNextRequests[numRequestProcessed].halRequest.frame_number,
4403 strerror(-res), res);
4404 cleanUpFailedRequests(/*sendRequestError*/ false);
4405 return false;
4406 }
4407 return true;
4408}
4409
4410bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4411 status_t res;
4412
4413 for (auto& nextRequest : mNextRequests) {
4414 // Submit request and block until ready for next one
4415 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4416 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4417
4418 if (res != OK) {
4419 // Should only get a failure here for malformed requests or device-level
4420 // errors, so consider all errors fatal. Bad metadata failures should
4421 // come through notify.
4422 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4423 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4424 res);
4425 cleanUpFailedRequests(/*sendRequestError*/ false);
4426 return false;
4427 }
4428
4429 // Mark that the request has be submitted successfully.
4430 nextRequest.submitted = true;
4431
4432 // Update the latest request sent to HAL
4433 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4434 Mutex::Autolock al(mLatestRequestMutex);
4435
4436 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4437 mLatestRequest.acquire(cloned);
4438
4439 sp<Camera3Device> parent = mParent.promote();
4440 if (parent != NULL) {
4441 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4442 0, mLatestRequest);
4443 }
4444 }
4445
4446 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004447 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4448 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004449 }
4450
Emilian Peevaebbe412018-01-15 13:53:24 +00004451 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4452
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004453 // Remove any previously queued triggers (after unlock)
4454 res = removeTriggers(mPrevRequest);
4455 if (res != OK) {
4456 SET_ERR("RequestThread: Unable to remove triggers "
4457 "(capture request %d, HAL device: %s (%d)",
4458 nextRequest.halRequest.frame_number, strerror(-res), res);
4459 cleanUpFailedRequests(/*sendRequestError*/ false);
4460 return false;
4461 }
4462 }
4463 return true;
4464}
4465
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004466nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4467 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4468 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4469 find_camera_metadata_ro_entry(request,
4470 ANDROID_CONTROL_AE_MODE,
4471 &e);
4472 if (e.count == 0) return maxExpectedDuration;
4473
4474 switch (e.data.u8[0]) {
4475 case ANDROID_CONTROL_AE_MODE_OFF:
4476 find_camera_metadata_ro_entry(request,
4477 ANDROID_SENSOR_EXPOSURE_TIME,
4478 &e);
4479 if (e.count > 0) {
4480 maxExpectedDuration = e.data.i64[0];
4481 }
4482 find_camera_metadata_ro_entry(request,
4483 ANDROID_SENSOR_FRAME_DURATION,
4484 &e);
4485 if (e.count > 0) {
4486 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4487 }
4488 break;
4489 default:
4490 find_camera_metadata_ro_entry(request,
4491 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4492 &e);
4493 if (e.count > 1) {
4494 maxExpectedDuration = 1e9 / e.data.u8[0];
4495 }
4496 break;
4497 }
4498
4499 return maxExpectedDuration;
4500}
4501
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004502bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4503 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4504 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4505 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4506 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4507 return true;
4508 }
4509
4510 return false;
4511}
4512
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004513bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4514 ATRACE_CALL();
4515 bool updatesDetected = false;
4516
4517 for (auto tag : mSessionParamKeys) {
4518 camera_metadata_ro_entry entry = settings.find(tag);
4519 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4520
4521 if (entry.count > 0) {
4522 bool isDifferent = false;
4523 if (lastEntry.count > 0) {
4524 // Have a last value, compare to see if changed
4525 if (lastEntry.type == entry.type &&
4526 lastEntry.count == entry.count) {
4527 // Same type and count, compare values
4528 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4529 size_t entryBytes = bytesPerValue * lastEntry.count;
4530 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4531 if (cmp != 0) {
4532 isDifferent = true;
4533 }
4534 } else {
4535 // Count or type has changed
4536 isDifferent = true;
4537 }
4538 } else {
4539 // No last entry, so always consider to be different
4540 isDifferent = true;
4541 }
4542
4543 if (isDifferent) {
4544 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004545 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4546 updatesDetected = true;
4547 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004548 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004549 }
4550 } else if (lastEntry.count > 0) {
4551 // Value has been removed
4552 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4553 mLatestSessionParams.erase(tag);
4554 updatesDetected = true;
4555 }
4556 }
4557
4558 return updatesDetected;
4559}
4560
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004561bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004562 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004563 status_t res;
4564
4565 // Handle paused state.
4566 if (waitIfPaused()) {
4567 return true;
4568 }
4569
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004570 // Wait for the next batch of requests.
4571 waitForNextRequestBatch();
4572 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004573 return true;
4574 }
4575
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004576 // Get the latest request ID, if any
4577 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004578 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004579 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004580 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004581 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004582 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004583 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4584 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004585 }
4586
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004587 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4588 // or a single request from streaming or burst. In either case the first element
4589 // should contain the latest camera settings that we need to check for any session
4590 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004591 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004592 res = OK;
4593
4594 //Input stream buffers are already acquired at this point so an input stream
4595 //will not be able to move to idle state unless we force it.
4596 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4597 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4598 if (res != OK) {
4599 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4600 cleanUpFailedRequests(/*sendRequestError*/ false);
4601 return false;
4602 }
4603 }
4604
4605 if (res == OK) {
4606 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4607 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004608 sp<Camera3Device> parent = mParent.promote();
4609 if (parent != nullptr) {
4610 parent->pauseStateNotify(true);
4611 }
4612
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004613 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4614
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004615 if (parent != nullptr) {
4616 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4617 }
4618
4619 statusTracker->markComponentActive(mStatusId);
4620 setPaused(false);
4621 }
4622
4623 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4624 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4625 if (res != OK) {
4626 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4627 cleanUpFailedRequests(/*sendRequestError*/ false);
4628 return false;
4629 }
4630 }
4631 }
4632 }
4633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004634 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004635 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004636 if (res == TIMED_OUT) {
4637 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004638 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004639 // Check if any stream is abandoned.
4640 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004641 return true;
4642 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004643 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004644 return false;
4645 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004646
Zhijun Hecc27e112013-10-03 16:12:43 -07004647 // Inform waitUntilRequestProcessed thread of a new request ID
4648 {
4649 Mutex::Autolock al(mLatestRequestMutex);
4650
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004651 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004652 mLatestRequestSignal.signal();
4653 }
4654
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004655 // Submit a batch of requests to HAL.
4656 // Use flush lock only when submitting multilple requests in a batch.
4657 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4658 // which may take a long time to finish so synchronizing flush() and
4659 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4660 // For now, only synchronize for high speed recording and we should figure something out for
4661 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004662 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004663
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004664 if (useFlushLock) {
4665 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004666 }
4667
Zhijun Hef0645c12016-08-02 00:58:11 -07004668 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004669 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004670
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004671 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004672 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004673 if (mInterface->supportBatchRequest()) {
4674 submitRequestSuccess = sendRequestsBatch();
4675 } else {
4676 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004677 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004678 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4679 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004680
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004681 if (useFlushLock) {
4682 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004683 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004684
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004685 // Unset as current request
4686 {
4687 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004688 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004689 }
4690
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004691 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004692}
4693
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004694status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004695 ATRACE_CALL();
4696
Shuzhen Wang4a472662017-02-26 23:29:04 -08004697 for (size_t i = 0; i < mNextRequests.size(); i++) {
4698 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004699 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4700 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4701 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4702
4703 // Prepare a request to HAL
4704 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4705
4706 // Insert any queued triggers (before metadata is locked)
4707 status_t res = insertTriggers(captureRequest);
4708
4709 if (res < 0) {
4710 SET_ERR("RequestThread: Unable to insert triggers "
4711 "(capture request %d, HAL device: %s (%d)",
4712 halRequest->frame_number, strerror(-res), res);
4713 return INVALID_OPERATION;
4714 }
4715 int triggerCount = res;
4716 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4717 mPrevTriggers = triggerCount;
4718
4719 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004720 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4721 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004722 /**
4723 * HAL workaround:
4724 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4725 */
4726 res = addDummyTriggerIds(captureRequest);
4727 if (res != OK) {
4728 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4729 "(capture request %d, HAL device: %s (%d)",
4730 halRequest->frame_number, strerror(-res), res);
4731 return INVALID_OPERATION;
4732 }
4733
4734 /**
4735 * The request should be presorted so accesses in HAL
4736 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4737 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004738 captureRequest->mSettingsList.begin()->metadata.sort();
4739 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004740 mPrevRequest = captureRequest;
4741 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4742
4743 IF_ALOGV() {
4744 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4745 find_camera_metadata_ro_entry(
4746 halRequest->settings,
4747 ANDROID_CONTROL_AF_TRIGGER,
4748 &e
4749 );
4750 if (e.count > 0) {
4751 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4752 __FUNCTION__,
4753 halRequest->frame_number,
4754 e.data.u8[0]);
4755 }
4756 }
4757 } else {
4758 // leave request.settings NULL to indicate 'reuse latest given'
4759 ALOGVV("%s: Request settings are REUSED",
4760 __FUNCTION__);
4761 }
4762
Emilian Peevaebbe412018-01-15 13:53:24 +00004763 if (captureRequest->mSettingsList.size() > 1) {
4764 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4765 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004766 if (newRequest) {
4767 halRequest->physcam_settings =
4768 new const camera_metadata* [halRequest->num_physcam_settings];
4769 } else {
4770 halRequest->physcam_settings = nullptr;
4771 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004772 auto it = ++captureRequest->mSettingsList.begin();
4773 size_t i = 0;
4774 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4775 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004776 if (newRequest) {
4777 it->metadata.sort();
4778 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4779 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004780 }
4781 }
4782
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 uint32_t totalNumBuffers = 0;
4784
4785 // Fill in buffers
4786 if (captureRequest->mInputStream != NULL) {
4787 halRequest->input_buffer = &captureRequest->mInputBuffer;
4788 totalNumBuffers += 1;
4789 } else {
4790 halRequest->input_buffer = NULL;
4791 }
4792
4793 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4794 captureRequest->mOutputStreams.size());
4795 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004796 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004797 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4798 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004799
4800 // Prepare video buffers for high speed recording on the first video request.
4801 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4802 // Only try to prepare video stream on the first video request.
4803 mPrepareVideoStream = false;
4804
4805 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4806 while (res == NOT_ENOUGH_DATA) {
4807 res = outputStream->prepareNextBuffer();
4808 }
4809 if (res != OK) {
4810 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4811 __FUNCTION__, strerror(-res), res);
4812 outputStream->cancelPrepare();
4813 }
4814 }
4815
Shuzhen Wang4a472662017-02-26 23:29:04 -08004816 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4817 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004818 if (res != OK) {
4819 // Can't get output buffer from gralloc queue - this could be due to
4820 // abandoned queue or other consumer misbehavior, so not a fatal
4821 // error
4822 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4823 " %s (%d)", strerror(-res), res);
4824
4825 return TIMED_OUT;
4826 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004827
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004828 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4829
4830 if (!physicalCameraId.isEmpty()) {
4831 // Physical stream isn't supported for input request.
4832 if (halRequest->input_buffer) {
4833 CLOGE("Physical stream is not supported for input request");
4834 return INVALID_OPERATION;
4835 }
4836 requestedPhysicalCameras.insert(physicalCameraId);
4837 }
4838 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004839 }
4840 totalNumBuffers += halRequest->num_output_buffers;
4841
4842 // Log request in the in-flight queue
4843 sp<Camera3Device> parent = mParent.promote();
4844 if (parent == NULL) {
4845 // Should not happen, and nowhere to send errors to, so just log it
4846 CLOGE("RequestThread: Parent is gone");
4847 return INVALID_OPERATION;
4848 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004849
4850 // If this request list is for constrained high speed recording (not
4851 // preview), and the current request is not the last one in the batch,
4852 // do not send callback to the app.
4853 bool hasCallback = true;
4854 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4855 hasCallback = false;
4856 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004857 res = parent->registerInFlight(halRequest->frame_number,
4858 totalNumBuffers, captureRequest->mResultExtras,
4859 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004860 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004861 calculateMaxExpectedDuration(halRequest->settings),
4862 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004863 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4864 ", burstId = %" PRId32 ".",
4865 __FUNCTION__,
4866 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4867 captureRequest->mResultExtras.burstId);
4868 if (res != OK) {
4869 SET_ERR("RequestThread: Unable to register new in-flight request:"
4870 " %s (%d)", strerror(-res), res);
4871 return INVALID_OPERATION;
4872 }
4873 }
4874
4875 return OK;
4876}
4877
Igor Murashkin1e479c02013-09-06 16:55:14 -07004878CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004879 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004880 Mutex::Autolock al(mLatestRequestMutex);
4881
4882 ALOGV("RequestThread::%s", __FUNCTION__);
4883
4884 return mLatestRequest;
4885}
4886
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004887bool Camera3Device::RequestThread::isStreamPending(
4888 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004889 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004890 Mutex::Autolock l(mRequestLock);
4891
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004892 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004893 if (!nextRequest.submitted) {
4894 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4895 if (stream == s) return true;
4896 }
4897 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004898 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004899 }
4900
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004901 for (const auto& request : mRequestQueue) {
4902 for (const auto& s : request->mOutputStreams) {
4903 if (stream == s) return true;
4904 }
4905 if (stream == request->mInputStream) return true;
4906 }
4907
4908 for (const auto& request : mRepeatingRequests) {
4909 for (const auto& s : request->mOutputStreams) {
4910 if (stream == s) return true;
4911 }
4912 if (stream == request->mInputStream) return true;
4913 }
4914
4915 return false;
4916}
Jianing Weicb0652e2014-03-12 18:29:36 -07004917
Emilian Peev40ead602017-09-26 15:46:36 +01004918bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4919 ATRACE_CALL();
4920 Mutex::Autolock l(mRequestLock);
4921
4922 for (const auto& nextRequest : mNextRequests) {
4923 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4924 if (s.first == streamId) {
4925 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4926 if (it != s.second.end()) {
4927 return true;
4928 }
4929 }
4930 }
4931 }
4932
4933 for (const auto& request : mRequestQueue) {
4934 for (const auto& s : request->mOutputSurfaces) {
4935 if (s.first == streamId) {
4936 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4937 if (it != s.second.end()) {
4938 return true;
4939 }
4940 }
4941 }
4942 }
4943
4944 for (const auto& request : mRepeatingRequests) {
4945 for (const auto& s : request->mOutputSurfaces) {
4946 if (s.first == streamId) {
4947 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4948 if (it != s.second.end()) {
4949 return true;
4950 }
4951 }
4952 }
4953 }
4954
4955 return false;
4956}
4957
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004958nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004959 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004960 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004961 return mExpectedInflightDuration > kMinInflightDuration ?
4962 mExpectedInflightDuration : kMinInflightDuration;
4963}
4964
Emilian Peevaebbe412018-01-15 13:53:24 +00004965void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4966 camera3_capture_request_t *halRequest) {
4967 if ((request == nullptr) || (halRequest == nullptr)) {
4968 ALOGE("%s: Invalid request!", __FUNCTION__);
4969 return;
4970 }
4971
4972 if (halRequest->num_physcam_settings > 0) {
4973 if (halRequest->physcam_id != nullptr) {
4974 delete [] halRequest->physcam_id;
4975 halRequest->physcam_id = nullptr;
4976 }
4977 if (halRequest->physcam_settings != nullptr) {
4978 auto it = ++(request->mSettingsList.begin());
4979 size_t i = 0;
4980 for (; it != request->mSettingsList.end(); it++, i++) {
4981 it->metadata.unlock(halRequest->physcam_settings[i]);
4982 }
4983 delete [] halRequest->physcam_settings;
4984 halRequest->physcam_settings = nullptr;
4985 }
4986 }
4987}
4988
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004989void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4990 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004991 return;
4992 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004993
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004994 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004995 // Skip the ones that have been submitted successfully.
4996 if (nextRequest.submitted) {
4997 continue;
4998 }
4999
5000 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5001 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5002 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5003
5004 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005005 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005006 }
5007
Emilian Peevaebbe412018-01-15 13:53:24 +00005008 cleanupPhysicalSettings(captureRequest, halRequest);
5009
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005010 if (captureRequest->mInputStream != NULL) {
5011 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5012 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5013 }
5014
5015 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005016 //Buffers that failed processing could still have
5017 //valid acquire fence.
5018 int acquireFence = (*outputBuffers)[i].acquire_fence;
5019 if (0 <= acquireFence) {
5020 close(acquireFence);
5021 outputBuffers->editItemAt(i).acquire_fence = -1;
5022 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005023 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5024 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5025 }
5026
5027 if (sendRequestError) {
5028 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005029 sp<NotificationListener> listener = mListener.promote();
5030 if (listener != NULL) {
5031 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005032 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005033 captureRequest->mResultExtras);
5034 }
5035 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005036
5037 // Remove yet-to-be submitted inflight request from inflightMap
5038 {
5039 sp<Camera3Device> parent = mParent.promote();
5040 if (parent != NULL) {
5041 Mutex::Autolock l(parent->mInFlightLock);
5042 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5043 if (idx >= 0) {
5044 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5045 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5046 parent->removeInFlightMapEntryLocked(idx);
5047 }
5048 }
5049 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005050 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005051
5052 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005053 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005054}
5055
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005056void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005057 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005058 // Optimized a bit for the simple steady-state case (single repeating
5059 // request), to avoid putting that request in the queue temporarily.
5060 Mutex::Autolock l(mRequestLock);
5061
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005062 assert(mNextRequests.empty());
5063
5064 NextRequest nextRequest;
5065 nextRequest.captureRequest = waitForNextRequestLocked();
5066 if (nextRequest.captureRequest == nullptr) {
5067 return;
5068 }
5069
5070 nextRequest.halRequest = camera3_capture_request_t();
5071 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005072 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005073
5074 // Wait for additional requests
5075 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5076
5077 for (size_t i = 1; i < batchSize; i++) {
5078 NextRequest additionalRequest;
5079 additionalRequest.captureRequest = waitForNextRequestLocked();
5080 if (additionalRequest.captureRequest == nullptr) {
5081 break;
5082 }
5083
5084 additionalRequest.halRequest = camera3_capture_request_t();
5085 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005086 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005087 }
5088
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005089 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005090 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005091 mNextRequests.size(), batchSize);
5092 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005093 }
5094
5095 return;
5096}
5097
5098sp<Camera3Device::CaptureRequest>
5099 Camera3Device::RequestThread::waitForNextRequestLocked() {
5100 status_t res;
5101 sp<CaptureRequest> nextRequest;
5102
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005103 while (mRequestQueue.empty()) {
5104 if (!mRepeatingRequests.empty()) {
5105 // Always atomically enqueue all requests in a repeating request
5106 // list. Guarantees a complete in-sequence set of captures to
5107 // application.
5108 const RequestList &requests = mRepeatingRequests;
5109 RequestList::const_iterator firstRequest =
5110 requests.begin();
5111 nextRequest = *firstRequest;
5112 mRequestQueue.insert(mRequestQueue.end(),
5113 ++firstRequest,
5114 requests.end());
5115 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005116
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005117 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005118
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005119 break;
5120 }
5121
5122 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5123
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005124 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5125 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005126 Mutex::Autolock pl(mPauseLock);
5127 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005128 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005129 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005130 // Let the tracker know
5131 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5132 if (statusTracker != 0) {
5133 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5134 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005135 }
5136 // Stop waiting for now and let thread management happen
5137 return NULL;
5138 }
5139 }
5140
5141 if (nextRequest == NULL) {
5142 // Don't have a repeating request already in hand, so queue
5143 // must have an entry now.
5144 RequestList::iterator firstRequest =
5145 mRequestQueue.begin();
5146 nextRequest = *firstRequest;
5147 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005148 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5149 sp<NotificationListener> listener = mListener.promote();
5150 if (listener != NULL) {
5151 listener->notifyRequestQueueEmpty();
5152 }
5153 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154 }
5155
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005156 // In case we've been unpaused by setPaused clearing mDoPause, need to
5157 // update internal pause state (capture/setRepeatingRequest unpause
5158 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005159 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005160 if (mPaused) {
5161 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5162 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5163 if (statusTracker != 0) {
5164 statusTracker->markComponentActive(mStatusId);
5165 }
5166 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005167 mPaused = false;
5168
5169 // Check if we've reconfigured since last time, and reset the preview
5170 // request if so. Can't use 'NULL request == repeat' across configure calls.
5171 if (mReconfigured) {
5172 mPrevRequest.clear();
5173 mReconfigured = false;
5174 }
5175
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005176 if (nextRequest != NULL) {
5177 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005178 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5179 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005180
5181 // Since RequestThread::clear() removes buffers from the input stream,
5182 // get the right buffer here before unlocking mRequestLock
5183 if (nextRequest->mInputStream != NULL) {
5184 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5185 if (res != OK) {
5186 // Can't get input buffer from gralloc queue - this could be due to
5187 // disconnected queue or other producer misbehavior, so not a fatal
5188 // error
5189 ALOGE("%s: Can't get input buffer, skipping request:"
5190 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005191
5192 sp<NotificationListener> listener = mListener.promote();
5193 if (listener != NULL) {
5194 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005195 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005196 nextRequest->mResultExtras);
5197 }
5198 return NULL;
5199 }
5200 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005201 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005202
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005203 return nextRequest;
5204}
5205
5206bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005207 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005208 status_t res;
5209 Mutex::Autolock l(mPauseLock);
5210 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005211 if (mPaused == false) {
5212 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005213 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5214 // Let the tracker know
5215 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5216 if (statusTracker != 0) {
5217 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5218 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005219 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005220
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005221 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005222 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005223 return true;
5224 }
5225 }
5226 // We don't set mPaused to false here, because waitForNextRequest needs
5227 // to further manage the paused state in case of starvation.
5228 return false;
5229}
5230
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005231void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005232 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005233 // With work to do, mark thread as unpaused.
5234 // If paused by request (setPaused), don't resume, to avoid
5235 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005236 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005237 Mutex::Autolock p(mPauseLock);
5238 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005239 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5240 if (mPaused) {
5241 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5242 if (statusTracker != 0) {
5243 statusTracker->markComponentActive(mStatusId);
5244 }
5245 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005246 mPaused = false;
5247 }
5248}
5249
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005250void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5251 sp<Camera3Device> parent = mParent.promote();
5252 if (parent != NULL) {
5253 va_list args;
5254 va_start(args, fmt);
5255
5256 parent->setErrorStateV(fmt, args);
5257
5258 va_end(args);
5259 }
5260}
5261
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005262status_t Camera3Device::RequestThread::insertTriggers(
5263 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005264 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005265 Mutex::Autolock al(mTriggerMutex);
5266
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005267 sp<Camera3Device> parent = mParent.promote();
5268 if (parent == NULL) {
5269 CLOGE("RequestThread: Parent is gone");
5270 return DEAD_OBJECT;
5271 }
5272
Emilian Peevaebbe412018-01-15 13:53:24 +00005273 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005274 size_t count = mTriggerMap.size();
5275
5276 for (size_t i = 0; i < count; ++i) {
5277 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005278 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005279
5280 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5281 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5282 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005283 if (isAeTrigger) {
5284 request->mResultExtras.precaptureTriggerId = triggerId;
5285 mCurrentPreCaptureTriggerId = triggerId;
5286 } else {
5287 request->mResultExtras.afTriggerId = triggerId;
5288 mCurrentAfTriggerId = triggerId;
5289 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005290 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005291 }
5292
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005293 camera_metadata_entry entry = metadata.find(tag);
5294
5295 if (entry.count > 0) {
5296 /**
5297 * Already has an entry for this trigger in the request.
5298 * Rewrite it with our requested trigger value.
5299 */
5300 RequestTrigger oldTrigger = trigger;
5301
5302 oldTrigger.entryValue = entry.data.u8[0];
5303
5304 mTriggerReplacedMap.add(tag, oldTrigger);
5305 } else {
5306 /**
5307 * More typical, no trigger entry, so we just add it
5308 */
5309 mTriggerRemovedMap.add(tag, trigger);
5310 }
5311
5312 status_t res;
5313
5314 switch (trigger.getTagType()) {
5315 case TYPE_BYTE: {
5316 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5317 res = metadata.update(tag,
5318 &entryValue,
5319 /*count*/1);
5320 break;
5321 }
5322 case TYPE_INT32:
5323 res = metadata.update(tag,
5324 &trigger.entryValue,
5325 /*count*/1);
5326 break;
5327 default:
5328 ALOGE("%s: Type not supported: 0x%x",
5329 __FUNCTION__,
5330 trigger.getTagType());
5331 return INVALID_OPERATION;
5332 }
5333
5334 if (res != OK) {
5335 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5336 ", value %d", __FUNCTION__, trigger.getTagName(),
5337 trigger.entryValue);
5338 return res;
5339 }
5340
5341 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5342 trigger.getTagName(),
5343 trigger.entryValue);
5344 }
5345
5346 mTriggerMap.clear();
5347
5348 return count;
5349}
5350
5351status_t Camera3Device::RequestThread::removeTriggers(
5352 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005353 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005354 Mutex::Autolock al(mTriggerMutex);
5355
Emilian Peevaebbe412018-01-15 13:53:24 +00005356 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005357
5358 /**
5359 * Replace all old entries with their old values.
5360 */
5361 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5362 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5363
5364 status_t res;
5365
5366 uint32_t tag = trigger.metadataTag;
5367 switch (trigger.getTagType()) {
5368 case TYPE_BYTE: {
5369 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5370 res = metadata.update(tag,
5371 &entryValue,
5372 /*count*/1);
5373 break;
5374 }
5375 case TYPE_INT32:
5376 res = metadata.update(tag,
5377 &trigger.entryValue,
5378 /*count*/1);
5379 break;
5380 default:
5381 ALOGE("%s: Type not supported: 0x%x",
5382 __FUNCTION__,
5383 trigger.getTagType());
5384 return INVALID_OPERATION;
5385 }
5386
5387 if (res != OK) {
5388 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5389 ", trigger value %d", __FUNCTION__,
5390 trigger.getTagName(), trigger.entryValue);
5391 return res;
5392 }
5393 }
5394 mTriggerReplacedMap.clear();
5395
5396 /**
5397 * Remove all new entries.
5398 */
5399 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5400 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5401 status_t res = metadata.erase(trigger.metadataTag);
5402
5403 if (res != OK) {
5404 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5405 ", trigger value %d", __FUNCTION__,
5406 trigger.getTagName(), trigger.entryValue);
5407 return res;
5408 }
5409 }
5410 mTriggerRemovedMap.clear();
5411
5412 return OK;
5413}
5414
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005415status_t Camera3Device::RequestThread::addDummyTriggerIds(
5416 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005417 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005418 static const int32_t dummyTriggerId = 1;
5419 status_t res;
5420
Emilian Peevaebbe412018-01-15 13:53:24 +00005421 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005422
5423 // If AF trigger is active, insert a dummy AF trigger ID if none already
5424 // exists
5425 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5426 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5427 if (afTrigger.count > 0 &&
5428 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5429 afId.count == 0) {
5430 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5431 if (res != OK) return res;
5432 }
5433
5434 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5435 // if none already exists
5436 camera_metadata_entry pcTrigger =
5437 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5438 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5439 if (pcTrigger.count > 0 &&
5440 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5441 pcId.count == 0) {
5442 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5443 &dummyTriggerId, 1);
5444 if (res != OK) return res;
5445 }
5446
5447 return OK;
5448}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005449
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005450/**
5451 * PreparerThread inner class methods
5452 */
5453
5454Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005455 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005456 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005457}
5458
5459Camera3Device::PreparerThread::~PreparerThread() {
5460 Thread::requestExitAndWait();
5461 if (mCurrentStream != nullptr) {
5462 mCurrentStream->cancelPrepare();
5463 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5464 mCurrentStream.clear();
5465 }
5466 clear();
5467}
5468
Ruben Brunkc78ac262015-08-13 17:58:46 -07005469status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005470 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005471 status_t res;
5472
5473 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005474 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005475
Ruben Brunkc78ac262015-08-13 17:58:46 -07005476 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005477 if (res == OK) {
5478 // No preparation needed, fire listener right off
5479 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005480 if (listener != NULL) {
5481 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005482 }
5483 return OK;
5484 } else if (res != NOT_ENOUGH_DATA) {
5485 return res;
5486 }
5487
5488 // Need to prepare, start up thread if necessary
5489 if (!mActive) {
5490 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5491 // isn't running
5492 Thread::requestExitAndWait();
5493 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5494 if (res != OK) {
5495 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005496 if (listener != NULL) {
5497 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005498 }
5499 return res;
5500 }
5501 mCancelNow = false;
5502 mActive = true;
5503 ALOGV("%s: Preparer stream started", __FUNCTION__);
5504 }
5505
5506 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005507 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005508 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5509
5510 return OK;
5511}
5512
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005513void Camera3Device::PreparerThread::pause() {
5514 ATRACE_CALL();
5515
5516 Mutex::Autolock l(mLock);
5517
5518 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5519 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5520 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5521 int currentMaxCount = mCurrentMaxCount;
5522 mPendingStreams.clear();
5523 mCancelNow = true;
5524 while (mActive) {
5525 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5526 if (res == TIMED_OUT) {
5527 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5528 return;
5529 } else if (res != OK) {
5530 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5531 return;
5532 }
5533 }
5534
5535 //Check whether the prepare thread was able to complete the current
5536 //stream. In case work is still pending emplace it along with the rest
5537 //of the streams in the pending list.
5538 if (currentStream != nullptr) {
5539 if (!mCurrentPrepareComplete) {
5540 pendingStreams.emplace(currentMaxCount, currentStream);
5541 }
5542 }
5543
5544 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5545 for (const auto& it : mPendingStreams) {
5546 it.second->cancelPrepare();
5547 }
5548}
5549
5550status_t Camera3Device::PreparerThread::resume() {
5551 ATRACE_CALL();
5552 status_t res;
5553
5554 Mutex::Autolock l(mLock);
5555 sp<NotificationListener> listener = mListener.promote();
5556
5557 if (mActive) {
5558 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5559 return NO_INIT;
5560 }
5561
5562 auto it = mPendingStreams.begin();
5563 for (; it != mPendingStreams.end();) {
5564 res = it->second->startPrepare(it->first);
5565 if (res == OK) {
5566 if (listener != NULL) {
5567 listener->notifyPrepared(it->second->getId());
5568 }
5569 it = mPendingStreams.erase(it);
5570 } else if (res != NOT_ENOUGH_DATA) {
5571 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5572 res, strerror(-res));
5573 it = mPendingStreams.erase(it);
5574 } else {
5575 it++;
5576 }
5577 }
5578
5579 if (mPendingStreams.empty()) {
5580 return OK;
5581 }
5582
5583 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5584 if (res != OK) {
5585 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5586 __FUNCTION__, res, strerror(-res));
5587 return res;
5588 }
5589 mCancelNow = false;
5590 mActive = true;
5591 ALOGV("%s: Preparer stream started", __FUNCTION__);
5592
5593 return OK;
5594}
5595
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005597 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005598 Mutex::Autolock l(mLock);
5599
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005600 for (const auto& it : mPendingStreams) {
5601 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005602 }
5603 mPendingStreams.clear();
5604 mCancelNow = true;
5605
5606 return OK;
5607}
5608
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005609void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005610 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005611 Mutex::Autolock l(mLock);
5612 mListener = listener;
5613}
5614
5615bool Camera3Device::PreparerThread::threadLoop() {
5616 status_t res;
5617 {
5618 Mutex::Autolock l(mLock);
5619 if (mCurrentStream == nullptr) {
5620 // End thread if done with work
5621 if (mPendingStreams.empty()) {
5622 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5623 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5624 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5625 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005626 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005627 return false;
5628 }
5629
5630 // Get next stream to prepare
5631 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005632 mCurrentStream = it->second;
5633 mCurrentMaxCount = it->first;
5634 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005635 mPendingStreams.erase(it);
5636 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5637 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5638 } else if (mCancelNow) {
5639 mCurrentStream->cancelPrepare();
5640 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5641 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5642 mCurrentStream.clear();
5643 mCancelNow = false;
5644 return true;
5645 }
5646 }
5647
5648 res = mCurrentStream->prepareNextBuffer();
5649 if (res == NOT_ENOUGH_DATA) return true;
5650 if (res != OK) {
5651 // Something bad happened; try to recover by cancelling prepare and
5652 // signalling listener anyway
5653 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5654 mCurrentStream->getId(), res, strerror(-res));
5655 mCurrentStream->cancelPrepare();
5656 }
5657
5658 // This stream has finished, notify listener
5659 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005660 sp<NotificationListener> listener = mListener.promote();
5661 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005662 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5663 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005664 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005665 }
5666
5667 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5668 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005669 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005670
5671 return true;
5672}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005673
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005674/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005675 * Static callback forwarding methods from HAL to instance
5676 */
5677
5678void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5679 const camera3_capture_result *result) {
5680 Camera3Device *d =
5681 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005682
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005683 d->processCaptureResult(result);
5684}
5685
5686void Camera3Device::sNotify(const camera3_callback_ops *cb,
5687 const camera3_notify_msg *msg) {
5688 Camera3Device *d =
5689 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5690 d->notify(msg);
5691}
5692
5693}; // namespace android