blob: e0a2dd49e8e5f81ab09b20745987d29b2b74c6a2 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000077 mListener(NULL),
78 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080079{
80 ATRACE_CALL();
81 camera3_callback_ops::notify = &sNotify;
82 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080083 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084}
85
86Camera3Device::~Camera3Device()
87{
88 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080089 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080090 disconnect();
91}
92
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080094 return mId;
95}
96
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080097status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
98 ATRACE_CALL();
99 Mutex::Autolock il(mInterfaceLock);
100 Mutex::Autolock l(mLock);
101
102 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
103 if (mStatus != STATUS_UNINITIALIZED) {
104 CLOGE("Already initialized!");
105 return INVALID_OPERATION;
106 }
107 if (manager == nullptr) return INVALID_OPERATION;
108
109 sp<ICameraDeviceSession> session;
110 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800111 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112 /*out*/ &session);
113 ATRACE_END();
114 if (res != OK) {
115 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
116 return res;
117 }
118
Steven Moreland5ff9c912017-03-09 23:13:00 -0800119 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 if (res != OK) {
121 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
122 session->close();
123 return res;
124 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800125
Yifan Hongf79b5542017-04-11 14:44:25 -0700126 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700127 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
128 [&queue](const auto& descriptor) {
129 queue = std::make_shared<RequestMetadataQueue>(descriptor);
130 if (!queue->isValid() || queue->availableToWrite() <= 0) {
131 ALOGE("HAL returns empty request metadata fmq, not use it");
132 queue = nullptr;
133 // don't use the queue onwards.
134 }
135 });
136 if (!requestQueueRet.isOk()) {
137 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
138 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700139 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700140 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700141
142 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700144 [&resQueue](const auto& descriptor) {
145 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
146 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700147 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700148 resQueue = nullptr;
149 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700150 }
151 });
152 if (!resultQueueRet.isOk()) {
153 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
154 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700156 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700157 IF_ALOGV() {
158 session->interfaceChain([](
159 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
160 ALOGV("Session interface chain:");
161 for (auto iface : interfaceChain) {
162 ALOGV(" %s", iface.c_str());
163 }
164 });
165 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700166
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700167 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000168 std::string providerType;
169 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800170
171 return initializeCommonLocked();
172}
173
174status_t Camera3Device::initializeCommonLocked() {
175
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700176 /** Start up status tracker thread */
177 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800178 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700179 if (res != OK) {
180 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
181 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800182 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700183 mStatusTracker.clear();
184 return res;
185 }
186
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700187 /** Register in-flight map to the status tracker */
188 mInFlightStatusId = mStatusTracker->addComponent();
189
Zhijun He125684a2015-12-26 15:07:30 -0800190 /** Create buffer manager */
191 mBufferManager = new Camera3BufferManager();
192
Emilian Peev71c73a22017-03-21 16:35:51 +0000193 mTagMonitor.initialize(mVendorTagId);
194
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700195 /** Start up request queue thread */
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700196 mRequestThread = new RequestThread(this, mStatusTracker, mInterface);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800197 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800198 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700199 SET_ERR_L("Unable to start request queue thread: %s (%d)",
200 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800201 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800202 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800203 return res;
204 }
205
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700206 mPreparerThread = new PreparerThread();
207
Ruben Brunk183f0562015-08-12 12:55:02 -0700208 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800209 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700210 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700211 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700212 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800213
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800214 // Measure the clock domain offset between camera and video/hw_composer
215 camera_metadata_entry timestampSource =
216 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
217 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
218 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
219 mTimestampOffset = getMonoToBoottimeOffset();
220 }
221
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700222 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100223 camera_metadata_entry partialResultsCount =
224 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
225 if (partialResultsCount.count > 0) {
226 mNumPartialResults = partialResultsCount.data.i32[0];
227 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700228 }
229
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700230 camera_metadata_entry configs =
231 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
232 for (uint32_t i = 0; i < configs.count; i += 4) {
233 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
234 configs.data.i32[i + 3] ==
235 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
236 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
237 configs.data.i32[i + 2]));
238 }
239 }
240
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800241 return OK;
242}
243
244status_t Camera3Device::disconnect() {
245 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700246 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800247
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700248 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800249
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700251 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700252 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 {
254 Mutex::Autolock l(mLock);
255 if (mStatus == STATUS_UNINITIALIZED) return res;
256
257 if (mStatus == STATUS_ACTIVE ||
258 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
259 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700260 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700262 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700264 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700266 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
267 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 // Continue to close device even in case of error
269 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700270 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800272
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 if (mStatus == STATUS_ERROR) {
274 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276
277 if (mStatusTracker != NULL) {
278 mStatusTracker->requestExit();
279 }
280
281 if (mRequestThread != NULL) {
282 mRequestThread->requestExit();
283 }
284
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700285 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
286 for (size_t i = 0; i < mOutputStreams.size(); i++) {
287 streams.push_back(mOutputStreams[i]);
288 }
289 if (mInputStream != nullptr) {
290 streams.push_back(mInputStream);
291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292 }
293
294 // Joining done without holding mLock, otherwise deadlocks may ensue
295 // as the threads try to access parent state
296 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
297 // HAL may be in a bad state, so waiting for request thread
298 // (which may be stuck in the HAL processCaptureRequest call)
299 // could be dangerous.
300 mRequestThread->join();
301 }
302
303 if (mStatusTracker != NULL) {
304 mStatusTracker->join();
305 }
306
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800307 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 {
309 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800312 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700313 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800314
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700315 // Call close without internal mutex held, as the HAL close may need to
316 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800317 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700318
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700319 flushInflightRequests();
320
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700321 {
322 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800323 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700324 mOutputStreams.clear();
325 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700326 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700327 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700328 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700329 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800330
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700331 for (auto& weakStream : streams) {
332 sp<Camera3StreamInterface> stream = weakStream.promote();
333 if (stream != nullptr) {
334 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
335 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
336 }
337 }
338
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700339 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341}
342
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343// For dumping/debugging only -
344// try to acquire a lock a few times, eventually give up to proceed with
345// debug/dump operations
346bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
347 bool gotLock = false;
348 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
349 if (lock.tryLock() == NO_ERROR) {
350 gotLock = true;
351 break;
352 } else {
353 usleep(kDumpSleepDuration);
354 }
355 }
356 return gotLock;
357}
358
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700359Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
360 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100361 const int STREAM_CONFIGURATION_SIZE = 4;
362 const int STREAM_FORMAT_OFFSET = 0;
363 const int STREAM_WIDTH_OFFSET = 1;
364 const int STREAM_HEIGHT_OFFSET = 2;
365 const int STREAM_IS_INPUT_OFFSET = 3;
366 camera_metadata_ro_entry_t availableStreamConfigs =
367 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
368 if (availableStreamConfigs.count == 0 ||
369 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
370 return Size(0, 0);
371 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700372
Emilian Peev08dd2452017-04-06 16:55:14 +0100373 // Get max jpeg size (area-wise).
374 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
375 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
376 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
377 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
378 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
379 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
380 && format == HAL_PIXEL_FORMAT_BLOB &&
381 (width * height > maxJpegWidth * maxJpegHeight)) {
382 maxJpegWidth = width;
383 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700384 }
385 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100386
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700387 return Size(maxJpegWidth, maxJpegHeight);
388}
389
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800390nsecs_t Camera3Device::getMonoToBoottimeOffset() {
391 // try three times to get the clock offset, choose the one
392 // with the minimum gap in measurements.
393 const int tries = 3;
394 nsecs_t bestGap, measured;
395 for (int i = 0; i < tries; ++i) {
396 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
397 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
398 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
399 const nsecs_t gap = tmono2 - tmono;
400 if (i == 0 || gap < bestGap) {
401 bestGap = gap;
402 measured = tbase - ((tmono + tmono2) >> 1);
403 }
404 }
405 return measured;
406}
407
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800408hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
409 int frameworkFormat) {
410 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
411}
412
413DataspaceFlags Camera3Device::mapToHidlDataspace(
414 android_dataspace dataSpace) {
415 return dataSpace;
416}
417
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700418BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100419 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700420 return usage;
421}
422
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800423StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
424 switch (rotation) {
425 case CAMERA3_STREAM_ROTATION_0:
426 return StreamRotation::ROTATION_0;
427 case CAMERA3_STREAM_ROTATION_90:
428 return StreamRotation::ROTATION_90;
429 case CAMERA3_STREAM_ROTATION_180:
430 return StreamRotation::ROTATION_180;
431 case CAMERA3_STREAM_ROTATION_270:
432 return StreamRotation::ROTATION_270;
433 }
434 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
435 return StreamRotation::ROTATION_0;
436}
437
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800438status_t Camera3Device::mapToStreamConfigurationMode(
439 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
440 if (mode == nullptr) return BAD_VALUE;
441 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
442 switch(operationMode) {
443 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
444 *mode = StreamConfigurationMode::NORMAL_MODE;
445 break;
446 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
447 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
448 break;
449 default:
450 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
451 return BAD_VALUE;
452 }
453 } else {
454 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800455 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800456 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800457}
458
459camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
460 switch (status) {
461 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
462 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
463 }
464 return CAMERA3_BUFFER_STATUS_ERROR;
465}
466
467int Camera3Device::mapToFrameworkFormat(
468 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
469 return static_cast<uint32_t>(pixelFormat);
470}
471
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700472android_dataspace Camera3Device::mapToFrameworkDataspace(
473 DataspaceFlags dataSpace) {
474 return static_cast<android_dataspace>(dataSpace);
475}
476
Emilian Peev050f5dc2017-05-18 14:43:56 +0100477uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700478 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700479 return usage;
480}
481
Emilian Peev050f5dc2017-05-18 14:43:56 +0100482uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700483 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700484 return usage;
485}
486
Zhijun Hef7da0962014-04-24 13:27:56 -0700487ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700488 // Get max jpeg size (area-wise).
489 Size maxJpegResolution = getMaxJpegResolution();
490 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800491 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
492 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700493 return BAD_VALUE;
494 }
495
Zhijun Hef7da0962014-04-24 13:27:56 -0700496 // Get max jpeg buffer size
497 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700498 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
499 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
501 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700502 return BAD_VALUE;
503 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700504 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800505 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700506
507 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700508 float scaleFactor = ((float) (width * height)) /
509 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800510 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
511 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700512 if (jpegBufferSize > maxJpegBufferSize) {
513 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700514 }
515
516 return jpegBufferSize;
517}
518
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700519ssize_t Camera3Device::getPointCloudBufferSize() const {
520 const int FLOATS_PER_POINT=4;
521 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
522 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800523 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
524 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700525 return BAD_VALUE;
526 }
527 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
528 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
529 return maxBytesForPointCloud;
530}
531
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800532ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800533 const int PER_CONFIGURATION_SIZE = 3;
534 const int WIDTH_OFFSET = 0;
535 const int HEIGHT_OFFSET = 1;
536 const int SIZE_OFFSET = 2;
537 camera_metadata_ro_entry rawOpaqueSizes =
538 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800539 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800540 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800541 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
542 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800543 return BAD_VALUE;
544 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700545
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800546 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
547 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
548 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
549 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
550 }
551 }
552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
554 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800555 return BAD_VALUE;
556}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700557
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800558status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
559 ATRACE_CALL();
560 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700561
562 // Try to lock, but continue in case of failure (to avoid blocking in
563 // deadlocks)
564 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
565 bool gotLock = tryLockSpinRightRound(mLock);
566
567 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
569 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700570 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800571 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
572 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700573
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800574 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700575
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800576 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700577 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800578 int n = args.size();
579 for (int i = 0; i < n; i++) {
580 if (args[i] == templatesOption) {
581 dumpTemplates = true;
582 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700583 if (args[i] == monitorOption) {
584 if (i + 1 < n) {
585 String8 monitorTags = String8(args[i + 1]);
586 if (monitorTags == "off") {
587 mTagMonitor.disableMonitoring();
588 } else {
589 mTagMonitor.parseTagsToMonitor(monitorTags);
590 }
591 } else {
592 mTagMonitor.disableMonitoring();
593 }
594 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800595 }
596
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800597 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800598
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800599 const char *status =
600 mStatus == STATUS_ERROR ? "ERROR" :
601 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700602 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
603 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800604 mStatus == STATUS_ACTIVE ? "ACTIVE" :
605 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800607 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700608 if (mStatus == STATUS_ERROR) {
609 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
610 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800611 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800612 const char *mode =
613 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
614 mOperatingMode == static_cast<int>(
615 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
616 "CUSTOM";
617 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800618
619 if (mInputStream != NULL) {
620 write(fd, lines.string(), lines.size());
621 mInputStream->dump(fd, args);
622 } else {
623 lines.appendFormat(" No input stream.\n");
624 write(fd, lines.string(), lines.size());
625 }
626 for (size_t i = 0; i < mOutputStreams.size(); i++) {
627 mOutputStreams[i]->dump(fd,args);
628 }
629
Zhijun He431503c2016-03-07 17:30:16 -0800630 if (mBufferManager != NULL) {
631 lines = String8(" Camera3 Buffer Manager:\n");
632 write(fd, lines.string(), lines.size());
633 mBufferManager->dump(fd, args);
634 }
Zhijun He125684a2015-12-26 15:07:30 -0800635
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700636 lines = String8(" In-flight requests:\n");
637 if (mInFlightMap.size() == 0) {
638 lines.append(" None\n");
639 } else {
640 for (size_t i = 0; i < mInFlightMap.size(); i++) {
641 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700642 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700643 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800644 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700645 r.numBuffersLeft);
646 }
647 }
648 write(fd, lines.string(), lines.size());
649
Shuzhen Wang686f6442017-06-20 16:16:04 -0700650 if (mRequestThread != NULL) {
651 mRequestThread->dumpCaptureRequestLatency(fd,
652 " ProcessCaptureRequest latency histogram:");
653 }
654
Igor Murashkin1e479c02013-09-06 16:55:14 -0700655 {
656 lines = String8(" Last request sent:\n");
657 write(fd, lines.string(), lines.size());
658
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700659 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700660 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
661 }
662
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800663 if (dumpTemplates) {
664 const char *templateNames[] = {
665 "TEMPLATE_PREVIEW",
666 "TEMPLATE_STILL_CAPTURE",
667 "TEMPLATE_VIDEO_RECORD",
668 "TEMPLATE_VIDEO_SNAPSHOT",
669 "TEMPLATE_ZERO_SHUTTER_LAG",
670 "TEMPLATE_MANUAL"
671 };
672
673 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800674 camera_metadata_t *templateRequest = nullptr;
675 mInterface->constructDefaultRequestSettings(
676 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800677 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800678 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800679 lines.append(" Not supported\n");
680 write(fd, lines.string(), lines.size());
681 } else {
682 write(fd, lines.string(), lines.size());
683 dump_indented_camera_metadata(templateRequest,
684 fd, /*verbosity*/2, /*indentation*/8);
685 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800687 }
688 }
689
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700690 mTagMonitor.dumpMonitoredMetadata(fd);
691
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800692 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800693 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800694 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800695 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800697
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 if (gotLock) mLock.unlock();
699 if (gotInterfaceLock) mInterfaceLock.unlock();
700
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800701 return OK;
702}
703
704const CameraMetadata& Camera3Device::info() const {
705 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800706 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
707 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700708 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800709 mStatus == STATUS_ERROR ?
710 "when in error state" : "before init");
711 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800712 return mDeviceInfo;
713}
714
Jianing Wei90e59c92014-03-12 18:29:36 -0700715status_t Camera3Device::checkStatusOkToCaptureLocked() {
716 switch (mStatus) {
717 case STATUS_ERROR:
718 CLOGE("Device has encountered a serious error");
719 return INVALID_OPERATION;
720 case STATUS_UNINITIALIZED:
721 CLOGE("Device not initialized");
722 return INVALID_OPERATION;
723 case STATUS_UNCONFIGURED:
724 case STATUS_CONFIGURED:
725 case STATUS_ACTIVE:
726 // OK
727 break;
728 default:
729 SET_ERR_L("Unexpected status: %d", mStatus);
730 return INVALID_OPERATION;
731 }
732 return OK;
733}
734
735status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700736 const List<const CameraMetadata> &metadataList,
737 const std::list<const SurfaceMap> &surfaceMaps,
738 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700739 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700740 if (requestList == NULL) {
741 CLOGE("requestList cannot be NULL.");
742 return BAD_VALUE;
743 }
744
Jianing Weicb0652e2014-03-12 18:29:36 -0700745 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
747 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
748 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
749 ++metadataIt, ++surfaceMapIt) {
750 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700751 if (newRequest == 0) {
752 CLOGE("Can't create capture request");
753 return BAD_VALUE;
754 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700755
Shuzhen Wang9d066012016-09-30 11:30:20 -0700756 newRequest->mRepeating = repeating;
757
Jianing Weicb0652e2014-03-12 18:29:36 -0700758 // Setup burst Id and request Id
759 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700760 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
761 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700762 CLOGE("RequestID entry exists; but must not be empty in metadata");
763 return BAD_VALUE;
764 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700765 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700766 } else {
767 CLOGE("RequestID does not exist in metadata");
768 return BAD_VALUE;
769 }
770
Jianing Wei90e59c92014-03-12 18:29:36 -0700771 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700772
773 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700774 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700775 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
776 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
777 return BAD_VALUE;
778 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700779
780 // Setup batch size if this is a high speed video recording request.
781 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
782 auto firstRequest = requestList->begin();
783 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
784 if (outputStream->isVideoStream()) {
785 (*firstRequest)->mBatchSize = requestList->size();
786 break;
787 }
788 }
789 }
790
Jianing Wei90e59c92014-03-12 18:29:36 -0700791 return OK;
792}
793
Jianing Weicb0652e2014-03-12 18:29:36 -0700794status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800795 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800796
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700797 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 std::list<const SurfaceMap> surfaceMaps;
799 convertToRequestList(requests, surfaceMaps, request);
800
801 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
802}
803
804void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
805 std::list<const SurfaceMap>& surfaceMaps,
806 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700807 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700808
809 SurfaceMap surfaceMap;
810 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
811 // With no surface list passed in, stream and surface will have 1-to-1
812 // mapping. So the surface index is 0 for each stream in the surfaceMap.
813 for (size_t i = 0; i < streams.count; i++) {
814 surfaceMap[streams.data.i32[i]].push_back(0);
815 }
816 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800817}
818
Jianing Wei90e59c92014-03-12 18:29:36 -0700819status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 const List<const CameraMetadata> &requests,
821 const std::list<const SurfaceMap> &surfaceMaps,
822 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700823 /*out*/
824 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 ATRACE_CALL();
826 Mutex::Autolock il(mInterfaceLock);
827 Mutex::Autolock l(mLock);
828
829 status_t res = checkStatusOkToCaptureLocked();
830 if (res != OK) {
831 // error logged by previous call
832 return res;
833 }
834
835 RequestList requestList;
836
Shuzhen Wang0129d522016-10-30 22:43:41 -0700837 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
838 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700839 if (res != OK) {
840 // error logged by previous call
841 return res;
842 }
843
844 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700845 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700846 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700847 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 }
849
850 if (res == OK) {
851 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
852 if (res != OK) {
853 SET_ERR_L("Can't transition to active in %f seconds!",
854 kActiveTimeout/1e9);
855 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800856 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700857 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700858 } else {
859 CLOGE("Cannot queue request. Impossible.");
860 return BAD_VALUE;
861 }
862
863 return res;
864}
865
Yifan Honga640c5a2017-04-12 16:30:31 -0700866// Only one processCaptureResult should be called at a time, so
867// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800868hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800869 const hardware::hidl_vec<
870 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700871 // Ideally we should grab mLock, but that can lead to deadlock, and
872 // it's not super important to get up to date value of mStatus for this
873 // warning print, hence skipping the lock here
874 if (mStatus == STATUS_ERROR) {
875 // Per API contract, HAL should act as closed after device error
876 // But mStatus can be set to error by framework as well, so just log
877 // a warning here.
878 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700879 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700880
881 if (mProcessCaptureResultLock.tryLock() != OK) {
882 // This should never happen; it indicates a wrong client implementation
883 // that doesn't follow the contract. But, we can be tolerant here.
884 ALOGE("%s: callback overlapped! waiting 1s...",
885 __FUNCTION__);
886 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
887 ALOGE("%s: cannot acquire lock in 1s, dropping results",
888 __FUNCTION__);
889 // really don't know what to do, so bail out.
890 return hardware::Void();
891 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800892 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700893 for (const auto& result : results) {
894 processOneCaptureResultLocked(result);
895 }
896 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800897 return hardware::Void();
898}
899
Yifan Honga640c5a2017-04-12 16:30:31 -0700900void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800901 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800902 camera3_capture_result r;
903 status_t res;
904 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700905
906 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
907 if (result.fmqResultSize > 0) {
908 resultMetadata.resize(result.fmqResultSize);
909 if (mResultMetadataQueue == nullptr) {
910 return; // logged in initialize()
911 }
912 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
913 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
914 __FUNCTION__, result.frameNumber, result.fmqResultSize);
915 return;
916 }
917 } else {
918 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
919 result.result.size());
920 }
921
922 if (resultMetadata.size() != 0) {
923 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
924 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800925 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
926 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
927 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800928 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800929 }
930 } else {
931 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800932 }
933
934 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
935 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
936 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
937 auto& bDst = outputBuffers[i];
938 const StreamBuffer &bSrc = result.outputBuffers[i];
939
940 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100941 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800942 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
943 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800944 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800945 }
946 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
947
948 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800949 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800950 if (res != OK) {
951 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
952 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800953 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800954 }
955 bDst.buffer = buffer;
956 bDst.status = mapHidlBufferStatus(bSrc.status);
957 bDst.acquire_fence = -1;
958 if (bSrc.releaseFence == nullptr) {
959 bDst.release_fence = -1;
960 } else if (bSrc.releaseFence->numFds == 1) {
961 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
962 } else {
963 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
964 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800965 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800966 }
967 }
968 r.num_output_buffers = outputBuffers.size();
969 r.output_buffers = outputBuffers.data();
970
971 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800972 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800973 r.input_buffer = nullptr;
974 } else {
975 if (mInputStream->getId() != result.inputBuffer.streamId) {
976 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
977 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800978 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800979 }
980 inputBuffer.stream = mInputStream->asHalStream();
981 buffer_handle_t *buffer;
982 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
983 &buffer);
984 if (res != OK) {
985 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
986 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800987 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800988 }
989 inputBuffer.buffer = buffer;
990 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
991 inputBuffer.acquire_fence = -1;
992 if (result.inputBuffer.releaseFence == nullptr) {
993 inputBuffer.release_fence = -1;
994 } else if (result.inputBuffer.releaseFence->numFds == 1) {
995 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
996 } else {
997 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
998 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800999 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 }
1001 r.input_buffer = &inputBuffer;
1002 }
1003
1004 r.partial_result = result.partialResult;
1005
1006 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001007}
1008
1009hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001010 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001011 // Ideally we should grab mLock, but that can lead to deadlock, and
1012 // it's not super important to get up to date value of mStatus for this
1013 // warning print, hence skipping the lock here
1014 if (mStatus == STATUS_ERROR) {
1015 // Per API contract, HAL should act as closed after device error
1016 // But mStatus can be set to error by framework as well, so just log
1017 // a warning here.
1018 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001019 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001020
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001021 for (const auto& msg : msgs) {
1022 notify(msg);
1023 }
1024 return hardware::Void();
1025}
1026
1027void Camera3Device::notify(
1028 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1029
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001030 camera3_notify_msg m;
1031 switch (msg.type) {
1032 case MsgType::ERROR:
1033 m.type = CAMERA3_MSG_ERROR;
1034 m.message.error.frame_number = msg.msg.error.frameNumber;
1035 if (msg.msg.error.errorStreamId >= 0) {
1036 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001037 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001038 ALOGE("%s: Frame %d: Invalid error stream id %d",
1039 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001040 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001041 }
1042 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1043 } else {
1044 m.message.error.error_stream = nullptr;
1045 }
1046 switch (msg.msg.error.errorCode) {
1047 case ErrorCode::ERROR_DEVICE:
1048 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1049 break;
1050 case ErrorCode::ERROR_REQUEST:
1051 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1052 break;
1053 case ErrorCode::ERROR_RESULT:
1054 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1055 break;
1056 case ErrorCode::ERROR_BUFFER:
1057 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1058 break;
1059 }
1060 break;
1061 case MsgType::SHUTTER:
1062 m.type = CAMERA3_MSG_SHUTTER;
1063 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1064 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1065 break;
1066 }
1067 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001068}
1069
Jianing Weicb0652e2014-03-12 18:29:36 -07001070status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001071 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001072 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001073 ATRACE_CALL();
1074
Shuzhen Wang0129d522016-10-30 22:43:41 -07001075 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001076}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001077
Jianing Weicb0652e2014-03-12 18:29:36 -07001078status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1079 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001080 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001081
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001082 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001083 std::list<const SurfaceMap> surfaceMaps;
1084 convertToRequestList(requests, surfaceMaps, request);
1085
1086 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1087 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088}
1089
Jianing Weicb0652e2014-03-12 18:29:36 -07001090status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001092 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001093 ATRACE_CALL();
1094
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001096}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001097
1098sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001099 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100 status_t res;
1101
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001102 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001103 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1104 // so unilaterally select normal operating mode.
1105 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001106 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001108 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001109 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001110 } else if (mStatus == STATUS_UNCONFIGURED) {
1111 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001112 CLOGE("No streams configured");
1113 return NULL;
1114 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 }
1116
Shuzhen Wang0129d522016-10-30 22:43:41 -07001117 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001119}
1120
Jianing Weicb0652e2014-03-12 18:29:36 -07001121status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001122 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001123 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001124 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001125
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 switch (mStatus) {
1127 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001128 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001129 return INVALID_OPERATION;
1130 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001131 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001133 case STATUS_UNCONFIGURED:
1134 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001135 case STATUS_ACTIVE:
1136 // OK
1137 break;
1138 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001139 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001140 return INVALID_OPERATION;
1141 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001142 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001143
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001144 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001145}
1146
1147status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1148 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001149 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001150
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001151 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001152}
1153
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001154status_t Camera3Device::createInputStream(
1155 uint32_t width, uint32_t height, int format, int *id) {
1156 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001157 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001158 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001159 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001160 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1161 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162
1163 status_t res;
1164 bool wasActive = false;
1165
1166 switch (mStatus) {
1167 case STATUS_ERROR:
1168 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1169 return INVALID_OPERATION;
1170 case STATUS_UNINITIALIZED:
1171 ALOGE("%s: Device not initialized", __FUNCTION__);
1172 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 case STATUS_UNCONFIGURED:
1174 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001175 // OK
1176 break;
1177 case STATUS_ACTIVE:
1178 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001179 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001181 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001182 return res;
1183 }
1184 wasActive = true;
1185 break;
1186 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001187 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001188 return INVALID_OPERATION;
1189 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001190 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001191
1192 if (mInputStream != 0) {
1193 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1194 return INVALID_OPERATION;
1195 }
1196
1197 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1198 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001200
1201 mInputStream = newStream;
1202
1203 *id = mNextStreamId++;
1204
1205 // Continue captures if active at start
1206 if (wasActive) {
1207 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001208 // Reuse current operating mode for new stream config
1209 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001210 if (res != OK) {
1211 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1212 __FUNCTION__, mNextStreamId, strerror(-res), res);
1213 return res;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001216 }
1217
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001218 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001219 return OK;
1220}
1221
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001222status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001223 uint32_t width, uint32_t height, int format,
1224 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001225 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001226 ATRACE_CALL();
1227
1228 if (consumer == nullptr) {
1229 ALOGE("%s: consumer must not be null", __FUNCTION__);
1230 return BAD_VALUE;
1231 }
1232
1233 std::vector<sp<Surface>> consumers;
1234 consumers.push_back(consumer);
1235
1236 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Emilian Peev40ead602017-09-26 15:46:36 +01001237 format, dataSpace, rotation, id, surfaceIds, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001238}
1239
1240status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1241 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1242 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001243 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001245
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001247 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001249 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Emilian Peev050f5dc2017-05-18 14:43:56 +01001250 " consumer usage %" PRIu64 ", isShared %d", mId.string(), mNextStreamId, width, height, format,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001251 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 status_t res;
1254 bool wasActive = false;
1255
1256 switch (mStatus) {
1257 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 // OK
1266 break;
1267 case STATUS_ACTIVE:
1268 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001269 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 return res;
1273 }
1274 wasActive = true;
1275 break;
1276 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001277 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 return INVALID_OPERATION;
1279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281
1282 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001283
Shuzhen Wang0129d522016-10-30 22:43:41 -07001284 if (consumers.size() == 0 && !hasDeferredConsumer) {
1285 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1286 return BAD_VALUE;
1287 }
Zhijun He5d677d12016-05-29 16:52:39 -07001288
Shuzhen Wang0129d522016-10-30 22:43:41 -07001289 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001290 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1291 return BAD_VALUE;
1292 }
1293
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001295 ssize_t blobBufferSize;
1296 if (dataSpace != HAL_DATASPACE_DEPTH) {
1297 blobBufferSize = getJpegBufferSize(width, height);
1298 if (blobBufferSize <= 0) {
1299 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1300 return BAD_VALUE;
1301 }
1302 } else {
1303 blobBufferSize = getPointCloudBufferSize();
1304 if (blobBufferSize <= 0) {
1305 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1306 return BAD_VALUE;
1307 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001308 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001309 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001310 width, height, blobBufferSize, format, dataSpace, rotation,
1311 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001312 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1313 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1314 if (rawOpaqueBufferSize <= 0) {
1315 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1316 return BAD_VALUE;
1317 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001318 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001319 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1320 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001321 } else if (isShared) {
1322 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1323 width, height, format, consumerUsage, dataSpace, rotation,
1324 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001326 newStream = new Camera3OutputStream(mNextStreamId,
1327 width, height, format, consumerUsage, dataSpace, rotation,
1328 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001330 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001331 width, height, format, dataSpace, rotation,
1332 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333 }
Emilian Peev40ead602017-09-26 15:46:36 +01001334
1335 size_t consumerCount = consumers.size();
1336 for (size_t i = 0; i < consumerCount; i++) {
1337 int id = newStream->getSurfaceId(consumers[i]);
1338 if (id < 0) {
1339 SET_ERR_L("Invalid surface id");
1340 return BAD_VALUE;
1341 }
1342 if (surfaceIds != nullptr) {
1343 surfaceIds->push_back(id);
1344 }
1345 }
1346
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348
Emilian Peev08dd2452017-04-06 16:55:14 +01001349 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001350
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 res = mOutputStreams.add(mNextStreamId, newStream);
1352 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001353 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 return res;
1355 }
1356
1357 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001358 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359
1360 // Continue captures if active at start
1361 if (wasActive) {
1362 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001363 // Reuse current operating mode for new stream config
1364 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1367 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return res;
1369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001370 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001372 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001374}
1375
Emilian Peev710c1422017-08-30 11:19:38 +01001376status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001378 if (nullptr == streamInfo) {
1379 return BAD_VALUE;
1380 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001381 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 switch (mStatus) {
1385 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001386 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 return INVALID_OPERATION;
1388 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001389 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001391 case STATUS_UNCONFIGURED:
1392 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 case STATUS_ACTIVE:
1394 // OK
1395 break;
1396 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001397 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 return INVALID_OPERATION;
1399 }
1400
1401 ssize_t idx = mOutputStreams.indexOfKey(id);
1402 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001403 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 return idx;
1405 }
1406
Emilian Peev710c1422017-08-30 11:19:38 +01001407 streamInfo->width = mOutputStreams[idx]->getWidth();
1408 streamInfo->height = mOutputStreams[idx]->getHeight();
1409 streamInfo->format = mOutputStreams[idx]->getFormat();
1410 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1411 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1412 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001413 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1414 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001416}
1417
1418status_t Camera3Device::setStreamTransform(int id,
1419 int transform) {
1420 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 switch (mStatus) {
1425 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001426 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001427 return INVALID_OPERATION;
1428 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001429 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001431 case STATUS_UNCONFIGURED:
1432 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 case STATUS_ACTIVE:
1434 // OK
1435 break;
1436 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001437 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 return INVALID_OPERATION;
1439 }
1440
1441 ssize_t idx = mOutputStreams.indexOfKey(id);
1442 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 CLOGE("Stream %d does not exist",
1444 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 return BAD_VALUE;
1446 }
1447
1448 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001449}
1450
1451status_t Camera3Device::deleteStream(int id) {
1452 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001453 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 Mutex::Autolock l(mLock);
1455 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001456
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001457 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 // CameraDevice semantics require device to already be idle before
1460 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001462 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001463 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 }
1465
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001466 if (mStatus == STATUS_ERROR) {
1467 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1468 __FUNCTION__, mId.string());
1469 return -EBUSY;
1470 }
1471
Igor Murashkin2fba5842013-04-22 14:03:54 -07001472 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001473 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 if (mInputStream != NULL && id == mInputStream->getId()) {
1475 deletedStream = mInputStream;
1476 mInputStream.clear();
1477 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001478 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return BAD_VALUE;
1481 }
Zhijun He5f446352014-01-22 09:49:33 -08001482 }
1483
1484 // Delete output stream or the output part of a bi-directional stream.
1485 if (outputStreamIdx != NAME_NOT_FOUND) {
1486 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 mOutputStreams.removeItem(id);
1488 }
1489
1490 // Free up the stream endpoint so that it can be used by some other stream
1491 res = deletedStream->disconnect();
1492 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001493 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 // fall through since we want to still list the stream as deleted.
1495 }
1496 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001497 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498
1499 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001500}
1501
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001502status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001503 ATRACE_CALL();
1504 ALOGV("%s: E", __FUNCTION__);
1505
1506 Mutex::Autolock il(mInterfaceLock);
1507 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001508
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001509 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001510}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001512status_t Camera3Device::getInputBufferProducer(
1513 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001514 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001515 Mutex::Autolock il(mInterfaceLock);
1516 Mutex::Autolock l(mLock);
1517
1518 if (producer == NULL) {
1519 return BAD_VALUE;
1520 } else if (mInputStream == NULL) {
1521 return INVALID_OPERATION;
1522 }
1523
1524 return mInputStream->getInputBufferProducer(producer);
1525}
1526
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527status_t Camera3Device::createDefaultRequest(int templateId,
1528 CameraMetadata *request) {
1529 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001530 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001531
1532 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1533 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1534 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1535 return BAD_VALUE;
1536 }
1537
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001538 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001540 {
1541 Mutex::Autolock l(mLock);
1542 switch (mStatus) {
1543 case STATUS_ERROR:
1544 CLOGE("Device has encountered a serious error");
1545 return INVALID_OPERATION;
1546 case STATUS_UNINITIALIZED:
1547 CLOGE("Device is not initialized!");
1548 return INVALID_OPERATION;
1549 case STATUS_UNCONFIGURED:
1550 case STATUS_CONFIGURED:
1551 case STATUS_ACTIVE:
1552 // OK
1553 break;
1554 default:
1555 SET_ERR_L("Unexpected status: %d", mStatus);
1556 return INVALID_OPERATION;
1557 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001559 if (!mRequestTemplateCache[templateId].isEmpty()) {
1560 *request = mRequestTemplateCache[templateId];
1561 return OK;
1562 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001563 }
1564
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001565 camera_metadata_t *rawRequest;
1566 status_t res = mInterface->constructDefaultRequestSettings(
1567 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001568
1569 {
1570 Mutex::Autolock l(mLock);
1571 if (res == BAD_VALUE) {
1572 ALOGI("%s: template %d is not supported on this camera device",
1573 __FUNCTION__, templateId);
1574 return res;
1575 } else if (res != OK) {
1576 CLOGE("Unable to construct request template %d: %s (%d)",
1577 templateId, strerror(-res), res);
1578 return res;
1579 }
1580
1581 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1582 mRequestTemplateCache[templateId].acquire(rawRequest);
1583
1584 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001585 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586 return OK;
1587}
1588
1589status_t Camera3Device::waitUntilDrained() {
1590 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001592 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001595 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001596}
1597
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001598status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 switch (mStatus) {
1600 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001601 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 ALOGV("%s: Already idle", __FUNCTION__);
1603 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 case STATUS_CONFIGURED:
1605 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 case STATUS_ERROR:
1607 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 break;
1610 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001611 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 return INVALID_OPERATION;
1613 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001614 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1615 maxExpectedDuration);
1616 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001617 if (res != OK) {
1618 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1619 res);
1620 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 return res;
1622}
1623
Ruben Brunk183f0562015-08-12 12:55:02 -07001624
1625void Camera3Device::internalUpdateStatusLocked(Status status) {
1626 mStatus = status;
1627 mRecentStatusUpdates.add(mStatus);
1628 mStatusChanged.broadcast();
1629}
1630
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001632status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 mRequestThread->setPaused(true);
1634 mPauseStateNotify = true;
1635
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001636 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1637 maxExpectedDuration);
1638 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 if (res != OK) {
1640 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001641 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001642 }
1643
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 return res;
1645}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001647// Resume after internalPauseAndWaitLocked
1648status_t Camera3Device::internalResumeLocked() {
1649 status_t res;
1650
1651 mRequestThread->setPaused(false);
1652
1653 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1654 if (res != OK) {
1655 SET_ERR_L("Can't transition to active in %f seconds!",
1656 kActiveTimeout/1e9);
1657 }
1658 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660}
1661
Ruben Brunk183f0562015-08-12 12:55:02 -07001662status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001664
1665 size_t startIndex = 0;
1666 if (mStatusWaiters == 0) {
1667 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1668 // this status list
1669 mRecentStatusUpdates.clear();
1670 } else {
1671 // If other threads are waiting on updates to this status list, set the position of the
1672 // first element that this list will check rather than clearing the list.
1673 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001674 }
1675
Ruben Brunk183f0562015-08-12 12:55:02 -07001676 mStatusWaiters++;
1677
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001678 bool stateSeen = false;
1679 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001680 if (active == (mStatus == STATUS_ACTIVE)) {
1681 // Desired state is current
1682 break;
1683 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684
1685 res = mStatusChanged.waitRelative(mLock, timeout);
1686 if (res != OK) break;
1687
Ruben Brunk183f0562015-08-12 12:55:02 -07001688 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1689 // transitions.
1690 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1691 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1692 __FUNCTION__);
1693
1694 // Encountered desired state since we began waiting
1695 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001696 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1697 stateSeen = true;
1698 break;
1699 }
1700 }
1701 } while (!stateSeen);
1702
Ruben Brunk183f0562015-08-12 12:55:02 -07001703 mStatusWaiters--;
1704
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 return res;
1706}
1707
1708
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001709status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001711 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001712
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001713 if (listener != NULL && mListener != NULL) {
1714 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1715 }
1716 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001717 mRequestThread->setNotificationListener(listener);
1718 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001719
1720 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001721}
1722
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001723bool Camera3Device::willNotify3A() {
1724 return false;
1725}
1726
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001728 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001729 status_t res;
1730 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001732 while (mResultQueue.empty()) {
1733 res = mResultSignal.waitRelative(mOutputLock, timeout);
1734 if (res == TIMED_OUT) {
1735 return res;
1736 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001737 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1738 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001739 return res;
1740 }
1741 }
1742 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
Jianing Weicb0652e2014-03-12 18:29:36 -07001745status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001747 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001749 if (mResultQueue.empty()) {
1750 return NOT_ENOUGH_DATA;
1751 }
1752
Jianing Weicb0652e2014-03-12 18:29:36 -07001753 if (frame == NULL) {
1754 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1755 return BAD_VALUE;
1756 }
1757
1758 CaptureResult &result = *(mResultQueue.begin());
1759 frame->mResultExtras = result.mResultExtras;
1760 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001761 mResultQueue.erase(mResultQueue.begin());
1762
1763 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764}
1765
1766status_t Camera3Device::triggerAutofocus(uint32_t id) {
1767 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001770 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1771 // Mix-in this trigger into the next request and only the next request.
1772 RequestTrigger trigger[] = {
1773 {
1774 ANDROID_CONTROL_AF_TRIGGER,
1775 ANDROID_CONTROL_AF_TRIGGER_START
1776 },
1777 {
1778 ANDROID_CONTROL_AF_TRIGGER_ID,
1779 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001780 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001781 };
1782
1783 return mRequestThread->queueTrigger(trigger,
1784 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785}
1786
1787status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1788 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001791 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1792 // Mix-in this trigger into the next request and only the next request.
1793 RequestTrigger trigger[] = {
1794 {
1795 ANDROID_CONTROL_AF_TRIGGER,
1796 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1797 },
1798 {
1799 ANDROID_CONTROL_AF_TRIGGER_ID,
1800 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001801 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001802 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001803
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001804 return mRequestThread->queueTrigger(trigger,
1805 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806}
1807
1808status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1809 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001812 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1813 // Mix-in this trigger into the next request and only the next request.
1814 RequestTrigger trigger[] = {
1815 {
1816 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1817 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1818 },
1819 {
1820 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1821 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001822 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001824
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001825 return mRequestThread->queueTrigger(trigger,
1826 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001827}
1828
Jianing Weicb0652e2014-03-12 18:29:36 -07001829status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001830 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001831 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001833
Zhijun He7ef20392014-04-21 16:04:17 -07001834 {
1835 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001836 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001837 }
1838
Emilian Peev08dd2452017-04-06 16:55:14 +01001839 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001840}
1841
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001842status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001843 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1844}
1845
1846status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001847 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001848 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001849 Mutex::Autolock il(mInterfaceLock);
1850 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001851
1852 sp<Camera3StreamInterface> stream;
1853 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1854 if (outputStreamIdx == NAME_NOT_FOUND) {
1855 CLOGE("Stream %d does not exist", streamId);
1856 return BAD_VALUE;
1857 }
1858
1859 stream = mOutputStreams.editValueAt(outputStreamIdx);
1860
1861 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001862 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001863 return BAD_VALUE;
1864 }
1865
1866 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001867 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001868 return BAD_VALUE;
1869 }
1870
Ruben Brunkc78ac262015-08-13 17:58:46 -07001871 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001872}
1873
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001874status_t Camera3Device::tearDown(int streamId) {
1875 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001876 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001877 Mutex::Autolock il(mInterfaceLock);
1878 Mutex::Autolock l(mLock);
1879
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001880 sp<Camera3StreamInterface> stream;
1881 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1882 if (outputStreamIdx == NAME_NOT_FOUND) {
1883 CLOGE("Stream %d does not exist", streamId);
1884 return BAD_VALUE;
1885 }
1886
1887 stream = mOutputStreams.editValueAt(outputStreamIdx);
1888
1889 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1890 CLOGE("Stream %d is a target of a in-progress request", streamId);
1891 return BAD_VALUE;
1892 }
1893
1894 return stream->tearDown();
1895}
1896
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001897status_t Camera3Device::addBufferListenerForStream(int streamId,
1898 wp<Camera3StreamBufferListener> listener) {
1899 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001900 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001901 Mutex::Autolock il(mInterfaceLock);
1902 Mutex::Autolock l(mLock);
1903
1904 sp<Camera3StreamInterface> stream;
1905 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1906 if (outputStreamIdx == NAME_NOT_FOUND) {
1907 CLOGE("Stream %d does not exist", streamId);
1908 return BAD_VALUE;
1909 }
1910
1911 stream = mOutputStreams.editValueAt(outputStreamIdx);
1912 stream->addBufferListener(listener);
1913
1914 return OK;
1915}
1916
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001917/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 * Methods called by subclasses
1919 */
1920
1921void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001922 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001923 {
1924 // Need mLock to safely update state and synchronize to current
1925 // state of methods in flight.
1926 Mutex::Autolock l(mLock);
1927 // We can get various system-idle notices from the status tracker
1928 // while starting up. Only care about them if we've actually sent
1929 // in some requests recently.
1930 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1931 return;
1932 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001933 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001934 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001935 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001936
1937 // Skip notifying listener if we're doing some user-transparent
1938 // state changes
1939 if (mPauseStateNotify) return;
1940 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001941
1942 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001943 {
1944 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001945 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001946 }
1947 if (idle && listener != NULL) {
1948 listener->notifyIdle();
1949 }
1950}
1951
Shuzhen Wang758c2152017-01-10 18:26:18 -08001952status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001953 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001954 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001955 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1956 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001957
1958 if (surfaceIds == nullptr) {
1959 return BAD_VALUE;
1960 }
1961
Zhijun He5d677d12016-05-29 16:52:39 -07001962 Mutex::Autolock il(mInterfaceLock);
1963 Mutex::Autolock l(mLock);
1964
Shuzhen Wang758c2152017-01-10 18:26:18 -08001965 if (consumers.size() == 0) {
1966 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001967 return BAD_VALUE;
1968 }
1969
1970 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1971 if (idx == NAME_NOT_FOUND) {
1972 CLOGE("Stream %d is unknown", streamId);
1973 return idx;
1974 }
1975 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001976 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001977 if (res != OK) {
1978 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1979 return res;
1980 }
1981
Emilian Peev40ead602017-09-26 15:46:36 +01001982 for (auto &consumer : consumers) {
1983 int id = stream->getSurfaceId(consumer);
1984 if (id < 0) {
1985 CLOGE("Invalid surface id!");
1986 return BAD_VALUE;
1987 }
1988 surfaceIds->push_back(id);
1989 }
1990
Shuzhen Wang0129d522016-10-30 22:43:41 -07001991 if (stream->isConsumerConfigurationDeferred()) {
1992 if (!stream->isConfiguring()) {
1993 CLOGE("Stream %d was already fully configured.", streamId);
1994 return INVALID_OPERATION;
1995 }
Zhijun He5d677d12016-05-29 16:52:39 -07001996
Shuzhen Wang0129d522016-10-30 22:43:41 -07001997 res = stream->finishConfiguration();
1998 if (res != OK) {
1999 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2000 stream->getId(), strerror(-res), res);
2001 return res;
2002 }
Zhijun He5d677d12016-05-29 16:52:39 -07002003 }
2004
2005 return OK;
2006}
2007
Emilian Peev40ead602017-09-26 15:46:36 +01002008status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2009 const std::vector<OutputStreamInfo> &outputInfo,
2010 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2011 Mutex::Autolock il(mInterfaceLock);
2012 Mutex::Autolock l(mLock);
2013
2014 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2015 if (idx == NAME_NOT_FOUND) {
2016 CLOGE("Stream %d is unknown", streamId);
2017 return idx;
2018 }
2019
2020 for (const auto &it : removedSurfaceIds) {
2021 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2022 CLOGE("Shared surface still part of a pending request!");
2023 return -EBUSY;
2024 }
2025 }
2026
2027 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2028 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2029 if (res != OK) {
2030 CLOGE("Stream %d failed to update stream (error %d %s) ",
2031 streamId, res, strerror(-res));
2032 if (res == UNKNOWN_ERROR) {
2033 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2034 __FUNCTION__);
2035 }
2036 return res;
2037 }
2038
2039 return res;
2040}
2041
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002042/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002043 * Camera3Device private methods
2044 */
2045
2046sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002047 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 ATRACE_CALL();
2049 status_t res;
2050
2051 sp<CaptureRequest> newRequest = new CaptureRequest;
2052 newRequest->mSettings = request;
2053
2054 camera_metadata_entry_t inputStreams =
2055 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2056 if (inputStreams.count > 0) {
2057 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002058 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002059 CLOGE("Request references unknown input stream %d",
2060 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 return NULL;
2062 }
2063 // Lazy completion of stream configuration (allocation/registration)
2064 // on first use
2065 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002066 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002068 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002070 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return NULL;
2072 }
2073 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002074 // Check if stream is being prepared
2075 if (mInputStream->isPreparing()) {
2076 CLOGE("Request references an input stream that's being prepared!");
2077 return NULL;
2078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079
2080 newRequest->mInputStream = mInputStream;
2081 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2082 }
2083
2084 camera_metadata_entry_t streams =
2085 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2086 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002087 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 return NULL;
2089 }
2090
2091 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002092 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002094 CLOGE("Request references unknown stream %d",
2095 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096 return NULL;
2097 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002098 sp<Camera3OutputStreamInterface> stream =
2099 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100
Zhijun He5d677d12016-05-29 16:52:39 -07002101 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002102 auto iter = surfaceMap.find(streams.data.i32[i]);
2103 if (iter != surfaceMap.end()) {
2104 const std::vector<size_t>& surfaces = iter->second;
2105 for (const auto& surface : surfaces) {
2106 if (stream->isConsumerConfigurationDeferred(surface)) {
2107 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2108 "due to deferred consumer", stream->getId(), surface);
2109 return NULL;
2110 }
2111 }
2112 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002113 }
2114
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 // Lazy completion of stream configuration (allocation/registration)
2116 // on first use
2117 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002118 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002120 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2121 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122 return NULL;
2123 }
2124 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002125 // Check if stream is being prepared
2126 if (stream->isPreparing()) {
2127 CLOGE("Request references an output stream that's being prepared!");
2128 return NULL;
2129 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130
2131 newRequest->mOutputStreams.push(stream);
2132 }
2133 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002134 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135
2136 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002137}
2138
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002139bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2140 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2141 Size size = mSupportedOpaqueInputSizes[i];
2142 if (size.width == width && size.height == height) {
2143 return true;
2144 }
2145 }
2146
2147 return false;
2148}
2149
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002150void Camera3Device::cancelStreamsConfigurationLocked() {
2151 int res = OK;
2152 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2153 res = mInputStream->cancelConfiguration();
2154 if (res != OK) {
2155 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2156 mInputStream->getId(), strerror(-res), res);
2157 }
2158 }
2159
2160 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2161 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2162 if (outputStream->isConfiguring()) {
2163 res = outputStream->cancelConfiguration();
2164 if (res != OK) {
2165 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2166 outputStream->getId(), strerror(-res), res);
2167 }
2168 }
2169 }
2170
2171 // Return state to that at start of call, so that future configures
2172 // properly clean things up
2173 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2174 mNeedConfig = true;
2175}
2176
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002177status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002178 ATRACE_CALL();
2179 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002180
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002182 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002183 return INVALID_OPERATION;
2184 }
2185
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002186 if (operatingMode < 0) {
2187 CLOGE("Invalid operating mode: %d", operatingMode);
2188 return BAD_VALUE;
2189 }
2190
2191 bool isConstrainedHighSpeed =
2192 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2193 operatingMode;
2194
2195 if (mOperatingMode != operatingMode) {
2196 mNeedConfig = true;
2197 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2198 mOperatingMode = operatingMode;
2199 }
2200
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002201 if (!mNeedConfig) {
2202 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2203 return OK;
2204 }
2205
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002206 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2207 // adding a dummy stream instead.
2208 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2209 if (mOutputStreams.size() == 0) {
2210 addDummyStreamLocked();
2211 } else {
2212 tryRemoveDummyStreamLocked();
2213 }
2214
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002215 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002216 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002217
2218 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002219 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2221
2222 Vector<camera3_stream_t*> streams;
2223 streams.setCapacity(config.num_streams);
2224
2225 if (mInputStream != NULL) {
2226 camera3_stream_t *inputStream;
2227 inputStream = mInputStream->startConfiguration();
2228 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002229 CLOGE("Can't start input stream configuration");
2230 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 return INVALID_OPERATION;
2232 }
2233 streams.add(inputStream);
2234 }
2235
2236 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002237
2238 // Don't configure bidi streams twice, nor add them twice to the list
2239 if (mOutputStreams[i].get() ==
2240 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2241
2242 config.num_streams--;
2243 continue;
2244 }
2245
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246 camera3_stream_t *outputStream;
2247 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2248 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002249 CLOGE("Can't start output stream configuration");
2250 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002251 return INVALID_OPERATION;
2252 }
2253 streams.add(outputStream);
2254 }
2255
2256 config.streams = streams.editArray();
2257
2258 // Do the HAL configuration; will potentially touch stream
2259 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002260
2261 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002263 if (res == BAD_VALUE) {
2264 // HAL rejected this set of streams as unsupported, clean up config
2265 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002266 CLOGE("Set of requested inputs/outputs not supported by HAL");
2267 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002268 return BAD_VALUE;
2269 } else if (res != OK) {
2270 // Some other kind of error from configure_streams - this is not
2271 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002272 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2273 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002274 return res;
2275 }
2276
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002277 // Finish all stream configuration immediately.
2278 // TODO: Try to relax this later back to lazy completion, which should be
2279 // faster
2280
Igor Murashkin073f8572013-05-02 14:59:28 -07002281 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002282 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002283 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002284 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002285 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002286 cancelStreamsConfigurationLocked();
2287 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002288 }
2289 }
2290
2291 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002292 sp<Camera3OutputStreamInterface> outputStream =
2293 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002294 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002295 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002296 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002297 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002298 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002299 cancelStreamsConfigurationLocked();
2300 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002301 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002302 }
2303 }
2304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305 // Request thread needs to know to avoid using repeat-last-settings protocol
2306 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002307 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308
Zhijun He90f7c372016-08-16 16:19:43 -07002309 char value[PROPERTY_VALUE_MAX];
2310 property_get("camera.fifo.disable", value, "0");
2311 int32_t disableFifo = atoi(value);
2312 if (disableFifo != 1) {
2313 // Boost priority of request thread to SCHED_FIFO.
2314 pid_t requestThreadTid = mRequestThread->getTid();
2315 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002316 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002317 if (res != OK) {
2318 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2319 strerror(-res), res);
2320 } else {
2321 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2322 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002323 }
2324
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002325 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002327 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002328
Ruben Brunk183f0562015-08-12 12:55:02 -07002329 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2330 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002331
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002332 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002333
Zhijun He0a210512014-07-24 13:45:15 -07002334 // tear down the deleted streams after configure streams.
2335 mDeletedStreams.clear();
2336
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002337 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002338}
2339
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002340status_t Camera3Device::addDummyStreamLocked() {
2341 ATRACE_CALL();
2342 status_t res;
2343
2344 if (mDummyStreamId != NO_STREAM) {
2345 // Should never be adding a second dummy stream when one is already
2346 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002347 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2348 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002349 return INVALID_OPERATION;
2350 }
2351
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002352 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002353
2354 sp<Camera3OutputStreamInterface> dummyStream =
2355 new Camera3DummyStream(mNextStreamId);
2356
2357 res = mOutputStreams.add(mNextStreamId, dummyStream);
2358 if (res < 0) {
2359 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2360 return res;
2361 }
2362
2363 mDummyStreamId = mNextStreamId;
2364 mNextStreamId++;
2365
2366 return OK;
2367}
2368
2369status_t Camera3Device::tryRemoveDummyStreamLocked() {
2370 ATRACE_CALL();
2371 status_t res;
2372
2373 if (mDummyStreamId == NO_STREAM) return OK;
2374 if (mOutputStreams.size() == 1) return OK;
2375
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002376 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002377
2378 // Ok, have a dummy stream and there's at least one other output stream,
2379 // so remove the dummy
2380
2381 sp<Camera3StreamInterface> deletedStream;
2382 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2383 if (outputStreamIdx == NAME_NOT_FOUND) {
2384 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2385 return INVALID_OPERATION;
2386 }
2387
2388 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2389 mOutputStreams.removeItemsAt(outputStreamIdx);
2390
2391 // Free up the stream endpoint so that it can be used by some other stream
2392 res = deletedStream->disconnect();
2393 if (res != OK) {
2394 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2395 // fall through since we want to still list the stream as deleted.
2396 }
2397 mDeletedStreams.add(deletedStream);
2398 mDummyStreamId = NO_STREAM;
2399
2400 return res;
2401}
2402
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002403void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002404 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002405 Mutex::Autolock l(mLock);
2406 va_list args;
2407 va_start(args, fmt);
2408
2409 setErrorStateLockedV(fmt, args);
2410
2411 va_end(args);
2412}
2413
2414void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002415 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002416 Mutex::Autolock l(mLock);
2417 setErrorStateLockedV(fmt, args);
2418}
2419
2420void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2421 va_list args;
2422 va_start(args, fmt);
2423
2424 setErrorStateLockedV(fmt, args);
2425
2426 va_end(args);
2427}
2428
2429void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002430 // Print out all error messages to log
2431 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002432 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002433
2434 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002435 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002436
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002437 mErrorCause = errorCause;
2438
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002439 if (mRequestThread != nullptr) {
2440 mRequestThread->setPaused(true);
2441 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002442 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002443
2444 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002445 sp<NotificationListener> listener = mListener.promote();
2446 if (listener != NULL) {
2447 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002448 CaptureResultExtras());
2449 }
2450
2451 // Save stack trace. View by dumping it later.
2452 CameraTraces::saveTrace();
2453 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002454}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455
2456/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002457 * In-flight request management
2458 */
2459
Jianing Weicb0652e2014-03-12 18:29:36 -07002460status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002461 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002462 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002463 ATRACE_CALL();
2464 Mutex::Autolock l(mInFlightLock);
2465
2466 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002467 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002468 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002469 if (res < 0) return res;
2470
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002471 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002472 // hold mLock to prevent race with disconnect
2473 Mutex::Autolock l(mLock);
2474 if (mStatusTracker != nullptr) {
2475 mStatusTracker->markComponentActive(mInFlightStatusId);
2476 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002477 }
2478
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002479 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002480 return OK;
2481}
2482
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002483void Camera3Device::returnOutputBuffers(
2484 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2485 nsecs_t timestamp) {
2486 for (size_t i = 0; i < numBuffers; i++)
2487 {
2488 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2489 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2490 // Note: stream may be deallocated at this point, if this buffer was
2491 // the last reference to it.
2492 if (res != OK) {
2493 ALOGE("Can't return buffer to its stream: %s (%d)",
2494 strerror(-res), res);
2495 }
2496 }
2497}
2498
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002499void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002500 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002501 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002502 mInFlightMap.removeItemsAt(idx, 1);
2503
2504 // Indicate idle inFlightMap to the status tracker
2505 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002506 // hold mLock to prevent race with disconnect
2507 Mutex::Autolock l(mLock);
2508 if (mStatusTracker != nullptr) {
2509 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2510 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002511 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002512 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002513}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002514
2515void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2516
2517 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2518 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2519
2520 nsecs_t sensorTimestamp = request.sensorTimestamp;
2521 nsecs_t shutterTimestamp = request.shutterTimestamp;
2522
2523 // Check if it's okay to remove the request from InFlightMap:
2524 // In the case of a successful request:
2525 // all input and output buffers, all result metadata, shutter callback
2526 // arrived.
2527 // In the case of a unsuccessful request:
2528 // all input and output buffers arrived.
2529 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002530 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002531 (request.haveResultMetadata && shutterTimestamp != 0))) {
2532 ATRACE_ASYNC_END("frame capture", frameNumber);
2533
Shuzhen Wang403044a2017-02-26 23:29:04 -08002534 // Sanity check - if sensor timestamp matches shutter timestamp in the
2535 // case of request having callback.
2536 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002537 sensorTimestamp != shutterTimestamp) {
2538 SET_ERR("sensor timestamp (%" PRId64
2539 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2540 sensorTimestamp, frameNumber, shutterTimestamp);
2541 }
2542
2543 // for an unsuccessful request, it may have pending output buffers to
2544 // return.
2545 assert(request.requestStatus != OK ||
2546 request.pendingOutputBuffers.size() == 0);
2547 returnOutputBuffers(request.pendingOutputBuffers.array(),
2548 request.pendingOutputBuffers.size(), 0);
2549
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002550 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002551 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2552 }
2553
2554 // Sanity check - if we have too many in-flight frames, something has
2555 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002556 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002557 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002558 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2559 kInFlightWarnLimitHighSpeed) {
2560 CLOGE("In-flight list too large for high speed configuration: %zu",
2561 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002562 }
2563}
2564
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002565void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002566 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002567 { // First return buffers cached in mInFlightMap
2568 Mutex::Autolock l(mInFlightLock);
2569 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2570 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2571 returnOutputBuffers(request.pendingOutputBuffers.array(),
2572 request.pendingOutputBuffers.size(), 0);
2573 }
2574 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002575 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002576 }
2577
2578 // Then return all inflight buffers not returned by HAL
2579 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2580 mInterface->getInflightBufferKeys(&inflightKeys);
2581
2582 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2583 for (auto& pair : inflightKeys) {
2584 int32_t frameNumber = pair.first;
2585 int32_t streamId = pair.second;
2586 buffer_handle_t* buffer;
2587 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2588 if (res != OK) {
2589 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2590 __FUNCTION__, frameNumber, streamId);
2591 continue;
2592 }
2593
2594 camera3_stream_buffer_t streamBuffer;
2595 streamBuffer.buffer = buffer;
2596 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2597 streamBuffer.acquire_fence = -1;
2598 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002599
2600 // First check if the buffer belongs to deleted stream
2601 bool streamDeleted = false;
2602 for (auto& stream : mDeletedStreams) {
2603 if (streamId == stream->getId()) {
2604 streamDeleted = true;
2605 // Return buffer to deleted stream
2606 camera3_stream* halStream = stream->asHalStream();
2607 streamBuffer.stream = halStream;
2608 switch (halStream->stream_type) {
2609 case CAMERA3_STREAM_OUTPUT:
2610 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2611 if (res != OK) {
2612 ALOGE("%s: Can't return output buffer for frame %d to"
2613 " stream %d: %s (%d)", __FUNCTION__,
2614 frameNumber, streamId, strerror(-res), res);
2615 }
2616 break;
2617 case CAMERA3_STREAM_INPUT:
2618 res = stream->returnInputBuffer(streamBuffer);
2619 if (res != OK) {
2620 ALOGE("%s: Can't return input buffer for frame %d to"
2621 " stream %d: %s (%d)", __FUNCTION__,
2622 frameNumber, streamId, strerror(-res), res);
2623 }
2624 break;
2625 default: // Bi-direcitonal stream is deprecated
2626 ALOGE("%s: stream %d has unknown stream type %d",
2627 __FUNCTION__, streamId, halStream->stream_type);
2628 break;
2629 }
2630 break;
2631 }
2632 }
2633 if (streamDeleted) {
2634 continue;
2635 }
2636
2637 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002638 if (streamId == inputStreamId) {
2639 streamBuffer.stream = mInputStream->asHalStream();
2640 res = mInputStream->returnInputBuffer(streamBuffer);
2641 if (res != OK) {
2642 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002643 " stream %d: %s (%d)", __FUNCTION__,
2644 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002645 }
2646 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002647 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2648 if (idx == NAME_NOT_FOUND) {
2649 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2650 continue;
2651 }
2652 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002653 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2654 }
2655 }
2656}
2657
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002658void Camera3Device::insertResultLocked(CaptureResult *result,
2659 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002660 if (result == nullptr) return;
2661
Emilian Peev71c73a22017-03-21 16:35:51 +00002662 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2663 result->mMetadata.getAndLock());
2664 set_camera_metadata_vendor_id(meta, mVendorTagId);
2665 result->mMetadata.unlock(meta);
2666
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002667 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2668 (int32_t*)&frameNumber, 1) != OK) {
2669 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2670 return;
2671 }
2672
2673 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2674 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2675 return;
2676 }
2677
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002678 // Valid result, insert into queue
2679 List<CaptureResult>::iterator queuedResult =
2680 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2681 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2682 ", burstId = %" PRId32, __FUNCTION__,
2683 queuedResult->mResultExtras.requestId,
2684 queuedResult->mResultExtras.frameNumber,
2685 queuedResult->mResultExtras.burstId);
2686
2687 mResultSignal.signal();
2688}
2689
2690
2691void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002692 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002693 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002694 Mutex::Autolock l(mOutputLock);
2695
2696 CaptureResult captureResult;
2697 captureResult.mResultExtras = resultExtras;
2698 captureResult.mMetadata = partialResult;
2699
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002700 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002701}
2702
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002703
2704void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2705 CaptureResultExtras &resultExtras,
2706 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002707 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002708 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002709 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002710 if (pendingMetadata.isEmpty())
2711 return;
2712
2713 Mutex::Autolock l(mOutputLock);
2714
2715 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002716 if (reprocess) {
2717 if (frameNumber < mNextReprocessResultFrameNumber) {
2718 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002719 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002720 frameNumber, mNextReprocessResultFrameNumber);
2721 return;
2722 }
2723 mNextReprocessResultFrameNumber = frameNumber + 1;
2724 } else {
2725 if (frameNumber < mNextResultFrameNumber) {
2726 SET_ERR("Out-of-order capture result metadata submitted! "
2727 "(got frame number %d, expecting %d)",
2728 frameNumber, mNextResultFrameNumber);
2729 return;
2730 }
2731 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002732 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002733
2734 CaptureResult captureResult;
2735 captureResult.mResultExtras = resultExtras;
2736 captureResult.mMetadata = pendingMetadata;
2737
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002738 // Append any previous partials to form a complete result
2739 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2740 captureResult.mMetadata.append(collectedPartialResult);
2741 }
2742
2743 captureResult.mMetadata.sort();
2744
2745 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002746 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2747 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002748 SET_ERR("No timestamp provided by HAL for frame %d!",
2749 frameNumber);
2750 return;
2751 }
2752
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002753 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2754 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2755
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002756 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757}
2758
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002759/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002760 * Camera HAL device callback methods
2761 */
2762
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002763void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002764 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002765
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002766 status_t res;
2767
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002768 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002769 if (result->result == NULL && result->num_output_buffers == 0 &&
2770 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002771 SET_ERR("No result data provided by HAL for frame %d",
2772 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002773 return;
2774 }
Zhijun He204e3292014-07-14 17:09:23 -07002775
Zhijun He204e3292014-07-14 17:09:23 -07002776 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002777 result->result != NULL &&
2778 result->partial_result != 1) {
2779 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2780 " if partial result is not supported",
2781 frameNumber, result->partial_result);
2782 return;
2783 }
2784
2785 bool isPartialResult = false;
2786 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002787 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002788 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002789
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790 // Get shutter timestamp and resultExtras from list of in-flight requests,
2791 // where it was added by the shutter notification for this frame. If the
2792 // shutter timestamp isn't received yet, append the output buffers to the
2793 // in-flight request and they will be returned when the shutter timestamp
2794 // arrives. Update the in-flight status and remove the in-flight entry if
2795 // all result data and shutter timestamp have been received.
2796 nsecs_t shutterTimestamp = 0;
2797
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002798 {
2799 Mutex::Autolock l(mInFlightLock);
2800 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2801 if (idx == NAME_NOT_FOUND) {
2802 SET_ERR("Unknown frame number for capture result: %d",
2803 frameNumber);
2804 return;
2805 }
2806 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002807 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2808 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002809 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002810 __FUNCTION__, request.resultExtras.requestId,
2811 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002812 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002813 // Always update the partial count to the latest one if it's not 0
2814 // (buffers only). When framework aggregates adjacent partial results
2815 // into one, the latest partial count will be used.
2816 if (result->partial_result != 0)
2817 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002818
2819 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002820 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002821 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2822 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2823 " the range of [1, %d] when metadata is included in the result",
2824 frameNumber, result->partial_result, mNumPartialResults);
2825 return;
2826 }
2827 isPartialResult = (result->partial_result < mNumPartialResults);
2828 if (isPartialResult) {
2829 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002830 }
2831
Shuzhen Wang4a472662017-02-26 23:29:04 -08002832 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002833 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002834 sendPartialCaptureResult(result->result, request.resultExtras,
2835 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002836 }
2837 }
2838
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002839 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002840 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002841
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002842 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002843 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002844 if (request.haveResultMetadata) {
2845 SET_ERR("Called multiple times with metadata for frame %d",
2846 frameNumber);
2847 return;
2848 }
Zhijun He204e3292014-07-14 17:09:23 -07002849 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002850 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002851 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002852 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002853 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002854 request.haveResultMetadata = true;
2855 }
2856
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002857 uint32_t numBuffersReturned = result->num_output_buffers;
2858 if (result->input_buffer != NULL) {
2859 if (hasInputBufferInRequest) {
2860 numBuffersReturned += 1;
2861 } else {
2862 ALOGW("%s: Input buffer should be NULL if there is no input"
2863 " buffer sent in the request",
2864 __FUNCTION__);
2865 }
2866 }
2867 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002868 if (request.numBuffersLeft < 0) {
2869 SET_ERR("Too many buffers returned for frame %d",
2870 frameNumber);
2871 return;
2872 }
2873
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002874 camera_metadata_ro_entry_t entry;
2875 res = find_camera_metadata_ro_entry(result->result,
2876 ANDROID_SENSOR_TIMESTAMP, &entry);
2877 if (res == OK && entry.count == 1) {
2878 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002879 }
2880
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002881 // If shutter event isn't received yet, append the output buffers to
2882 // the in-flight request. Otherwise, return the output buffers to
2883 // streams.
2884 if (shutterTimestamp == 0) {
2885 request.pendingOutputBuffers.appendArray(result->output_buffers,
2886 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002887 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002888 returnOutputBuffers(result->output_buffers,
2889 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002890 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002891
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002892 if (result->result != NULL && !isPartialResult) {
2893 if (shutterTimestamp == 0) {
2894 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002895 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002896 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002897 CameraMetadata metadata;
2898 metadata = result->result;
2899 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002900 collectedPartialResult, frameNumber,
2901 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002902 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002903 }
2904
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002905 removeInFlightRequestIfReadyLocked(idx);
2906 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002907
Zhijun Hef0d962a2014-06-30 10:24:11 -07002908 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002909 if (hasInputBufferInRequest) {
2910 Camera3Stream *stream =
2911 Camera3Stream::cast(result->input_buffer->stream);
2912 res = stream->returnInputBuffer(*(result->input_buffer));
2913 // Note: stream may be deallocated at this point, if this buffer was the
2914 // last reference to it.
2915 if (res != OK) {
2916 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2917 " its stream:%s (%d)", __FUNCTION__,
2918 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002919 }
2920 } else {
2921 ALOGW("%s: Input buffer should be NULL if there is no input"
2922 " buffer sent in the request, skipping input buffer return.",
2923 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002924 }
2925 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002926}
2927
2928void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002929 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002930 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002931 {
2932 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002933 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002934 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002935
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002936 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002937 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002938 return;
2939 }
2940
2941 switch (msg->type) {
2942 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002943 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002944 break;
2945 }
2946 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002947 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002948 break;
2949 }
2950 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002951 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002952 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002953 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002954}
2955
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002956void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002957 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002958 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959 // Map camera HAL error codes to ICameraDeviceCallback error codes
2960 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002961 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002963 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002964 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002965 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002966 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002967 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002968 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002971 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972 };
2973
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002974 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002975 ((msg.error_code >= 0) &&
2976 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2977 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002979
2980 int streamId = 0;
2981 if (msg.error_stream != NULL) {
2982 Camera3Stream *stream =
2983 Camera3Stream::cast(msg.error_stream);
2984 streamId = stream->getId();
2985 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002986 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2987 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002988 streamId, msg.error_code);
2989
2990 CaptureResultExtras resultExtras;
2991 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002992 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002993 // SET_ERR calls notifyError
2994 SET_ERR("Camera HAL reported serious device error");
2995 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2997 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2998 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002999 {
3000 Mutex::Autolock l(mInFlightLock);
3001 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3002 if (idx >= 0) {
3003 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3004 r.requestStatus = msg.error_code;
3005 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003006 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3007 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3008 errorCode) {
3009 r.skipResultMetadata = true;
3010 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003011 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3012 errorCode) {
3013 // In case of missing result check whether the buffers
3014 // returned. If they returned, then remove inflight
3015 // request.
3016 removeInFlightRequestIfReadyLocked(idx);
3017 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003018 } else {
3019 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003020 ALOGE("Camera %s: %s: cannot find in-flight request on "
3021 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003022 resultExtras.frameNumber);
3023 }
3024 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003025 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003026 if (listener != NULL) {
3027 listener->notifyError(errorCode, resultExtras);
3028 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003029 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003030 }
3031 break;
3032 default:
3033 // SET_ERR calls notifyError
3034 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3035 break;
3036 }
3037}
3038
3039void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003040 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003041 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003042 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003043
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003044 // Set timestamp for the request in the in-flight tracking
3045 // and get the request ID to send upstream
3046 {
3047 Mutex::Autolock l(mInFlightLock);
3048 idx = mInFlightMap.indexOfKey(msg.frame_number);
3049 if (idx >= 0) {
3050 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003051
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003052 // Verify ordering of shutter notifications
3053 {
3054 Mutex::Autolock l(mOutputLock);
3055 // TODO: need to track errors for tighter bounds on expected frame number.
3056 if (r.hasInputBuffer) {
3057 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3058 SET_ERR("Shutter notification out-of-order. Expected "
3059 "notification for frame %d, got frame %d",
3060 mNextReprocessShutterFrameNumber, msg.frame_number);
3061 return;
3062 }
3063 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3064 } else {
3065 if (msg.frame_number < mNextShutterFrameNumber) {
3066 SET_ERR("Shutter notification out-of-order. Expected "
3067 "notification for frame %d, got frame %d",
3068 mNextShutterFrameNumber, msg.frame_number);
3069 return;
3070 }
3071 mNextShutterFrameNumber = msg.frame_number + 1;
3072 }
3073 }
3074
Shuzhen Wang4a472662017-02-26 23:29:04 -08003075 r.shutterTimestamp = msg.timestamp;
3076 if (r.hasCallback) {
3077 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003078 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003079 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003080 // Call listener, if any
3081 if (listener != NULL) {
3082 listener->notifyShutter(r.resultExtras, msg.timestamp);
3083 }
3084 // send pending result and buffers
3085 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3086 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003087 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003088 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003089 returnOutputBuffers(r.pendingOutputBuffers.array(),
3090 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3091 r.pendingOutputBuffers.clear();
3092
3093 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003094 }
3095 }
3096 if (idx < 0) {
3097 SET_ERR("Shutter notification for non-existent frame number %d",
3098 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003099 }
3100}
3101
3102
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003103CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003104 ALOGV("%s", __FUNCTION__);
3105
Igor Murashkin1e479c02013-09-06 16:55:14 -07003106 CameraMetadata retVal;
3107
3108 if (mRequestThread != NULL) {
3109 retVal = mRequestThread->getLatestRequest();
3110 }
3111
Igor Murashkin1e479c02013-09-06 16:55:14 -07003112 return retVal;
3113}
3114
Jianing Weicb0652e2014-03-12 18:29:36 -07003115
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003116void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3117 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3118 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3119}
3120
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003121/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003122 * HalInterface inner class methods
3123 */
3124
Yifan Hongf79b5542017-04-11 14:44:25 -07003125Camera3Device::HalInterface::HalInterface(
3126 sp<ICameraDeviceSession> &session,
3127 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003128 mHidlSession(session),
3129 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130
Emilian Peev31abd0a2017-05-11 18:37:46 +01003131Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003132
3133Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003134 mHidlSession(other.mHidlSession),
3135 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003136
3137bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003138 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003139}
3140
3141void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003142 mHidlSession.clear();
3143}
3144
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003145bool Camera3Device::HalInterface::supportBatchRequest() {
3146 return mHidlSession != nullptr;
3147}
3148
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003149status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3150 camera3_request_template_t templateId,
3151 /*out*/ camera_metadata_t **requestTemplate) {
3152 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3153 if (!valid()) return INVALID_OPERATION;
3154 status_t res = OK;
3155
Emilian Peev31abd0a2017-05-11 18:37:46 +01003156 common::V1_0::Status status;
3157 RequestTemplate id;
3158 switch (templateId) {
3159 case CAMERA3_TEMPLATE_PREVIEW:
3160 id = RequestTemplate::PREVIEW;
3161 break;
3162 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3163 id = RequestTemplate::STILL_CAPTURE;
3164 break;
3165 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3166 id = RequestTemplate::VIDEO_RECORD;
3167 break;
3168 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3169 id = RequestTemplate::VIDEO_SNAPSHOT;
3170 break;
3171 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3172 id = RequestTemplate::ZERO_SHUTTER_LAG;
3173 break;
3174 case CAMERA3_TEMPLATE_MANUAL:
3175 id = RequestTemplate::MANUAL;
3176 break;
3177 default:
3178 // Unknown template ID
3179 return BAD_VALUE;
3180 }
3181 auto err = mHidlSession->constructDefaultRequestSettings(id,
3182 [&status, &requestTemplate]
3183 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3184 status = s;
3185 if (status == common::V1_0::Status::OK) {
3186 const camera_metadata *r =
3187 reinterpret_cast<const camera_metadata_t*>(request.data());
3188 size_t expectedSize = request.size();
3189 int ret = validate_camera_metadata_structure(r, &expectedSize);
3190 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3191 *requestTemplate = clone_camera_metadata(r);
3192 if (*requestTemplate == nullptr) {
3193 ALOGE("%s: Unable to clone camera metadata received from HAL",
3194 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003195 status = common::V1_0::Status::INTERNAL_ERROR;
3196 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003197 } else {
3198 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3199 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003200 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 }
3202 });
3203 if (!err.isOk()) {
3204 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3205 res = DEAD_OBJECT;
3206 } else {
3207 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003208 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003209
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003210 return res;
3211}
3212
3213status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3214 ATRACE_NAME("CameraHal::configureStreams");
3215 if (!valid()) return INVALID_OPERATION;
3216 status_t res = OK;
3217
Emilian Peev31abd0a2017-05-11 18:37:46 +01003218 // Convert stream config to HIDL
3219 std::set<int> activeStreams;
3220 StreamConfiguration requestedConfiguration;
3221 requestedConfiguration.streams.resize(config->num_streams);
3222 for (size_t i = 0; i < config->num_streams; i++) {
3223 Stream &dst = requestedConfiguration.streams[i];
3224 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003225
Emilian Peev31abd0a2017-05-11 18:37:46 +01003226 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3227 cam3stream->setBufferFreedListener(this);
3228 int streamId = cam3stream->getId();
3229 StreamType streamType;
3230 switch (src->stream_type) {
3231 case CAMERA3_STREAM_OUTPUT:
3232 streamType = StreamType::OUTPUT;
3233 break;
3234 case CAMERA3_STREAM_INPUT:
3235 streamType = StreamType::INPUT;
3236 break;
3237 default:
3238 ALOGE("%s: Stream %d: Unsupported stream type %d",
3239 __FUNCTION__, streamId, config->streams[i]->stream_type);
3240 return BAD_VALUE;
3241 }
3242 dst.id = streamId;
3243 dst.streamType = streamType;
3244 dst.width = src->width;
3245 dst.height = src->height;
3246 dst.format = mapToPixelFormat(src->format);
Emilian Peev050f5dc2017-05-18 14:43:56 +01003247 dst.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peev31abd0a2017-05-11 18:37:46 +01003248 dst.dataSpace = mapToHidlDataspace(src->data_space);
3249 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3250
3251 activeStreams.insert(streamId);
3252 // Create Buffer ID map if necessary
3253 if (mBufferIdMaps.count(streamId) == 0) {
3254 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3255 }
3256 }
3257 // remove BufferIdMap for deleted streams
3258 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3259 int streamId = it->first;
3260 bool active = activeStreams.count(streamId) > 0;
3261 if (!active) {
3262 it = mBufferIdMaps.erase(it);
3263 } else {
3264 ++it;
3265 }
3266 }
3267
3268 res = mapToStreamConfigurationMode(
3269 (camera3_stream_configuration_mode_t) config->operation_mode,
3270 /*out*/ &requestedConfiguration.operationMode);
3271 if (res != OK) {
3272 return res;
3273 }
3274
3275 // Invoke configureStreams
3276
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003277 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003279
3280 // See if we have v3.3 HAL
3281 sp<device::V3_3::ICameraDeviceSession> hidlSession_3_3;
3282 auto castResult = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3283 if (castResult.isOk()) {
3284 hidlSession_3_3 = castResult;
3285 } else {
3286 ALOGE("%s: Transaction error when casting ICameraDeviceSession: %s", __FUNCTION__,
3287 castResult.description().c_str());
3288 }
3289 if (hidlSession_3_3 != nullptr) {
3290 // We do; use v3.3 for the call
3291 ALOGV("%s: v3.3 device found", __FUNCTION__);
3292 auto err = hidlSession_3_3->configureStreams_3_3(requestedConfiguration,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003293 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003294 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 finalConfiguration = halConfiguration;
3296 status = s;
3297 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003298 if (!err.isOk()) {
3299 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3300 return DEAD_OBJECT;
3301 }
3302 } else {
3303 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3304 ALOGV("%s: v3.2 device found", __FUNCTION__);
3305 HalStreamConfiguration finalConfiguration_3_2;
3306 auto err = mHidlSession->configureStreams(requestedConfiguration,
3307 [&status, &finalConfiguration_3_2]
3308 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3309 finalConfiguration_3_2 = halConfiguration;
3310 status = s;
3311 });
3312 if (!err.isOk()) {
3313 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3314 return DEAD_OBJECT;
3315 }
3316 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3317 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3318 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3319 finalConfiguration.streams[i].overrideDataSpace =
3320 requestedConfiguration.streams[i].dataSpace;
3321 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322 }
3323
3324 if (status != common::V1_0::Status::OK ) {
3325 return CameraProviderManager::mapToStatusT(status);
3326 }
3327
3328 // And convert output stream configuration from HIDL
3329
3330 for (size_t i = 0; i < config->num_streams; i++) {
3331 camera3_stream_t *dst = config->streams[i];
3332 int streamId = Camera3Stream::cast(dst)->getId();
3333
3334 // Start scan at i, with the assumption that the stream order matches
3335 size_t realIdx = i;
3336 bool found = false;
3337 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003338 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 found = true;
3340 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003341 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003342 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3343 }
3344 if (!found) {
3345 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3346 __FUNCTION__, streamId);
3347 return INVALID_OPERATION;
3348 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003349 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003350
Emilian Peev710c1422017-08-30 11:19:38 +01003351 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3352 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003353 dstStream->setDataSpaceOverride(false);
3354 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3355 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3356
Emilian Peev31abd0a2017-05-11 18:37:46 +01003357 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3358 if (dst->format != overrideFormat) {
3359 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3360 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003361 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003362 if (dst->data_space != overrideDataSpace) {
3363 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3364 streamId, dst->format);
3365 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003366 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003367 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003368 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3369
Emilian Peev31abd0a2017-05-11 18:37:46 +01003370 // Override allowed with IMPLEMENTATION_DEFINED
3371 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003372 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003373 }
3374
Emilian Peev31abd0a2017-05-11 18:37:46 +01003375 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003376 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003377 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003378 __FUNCTION__, streamId);
3379 return INVALID_OPERATION;
3380 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003381 dstStream->setUsage(
3382 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003383 } else {
3384 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003385 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3387 __FUNCTION__, streamId);
3388 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003389 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003390 dstStream->setUsage(
3391 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003392 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003393 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003394 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003396 return res;
3397}
3398
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003399void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3400 /*out*/device::V3_2::CaptureRequest* captureRequest,
3401 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003402 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003403 if (captureRequest == nullptr || handlesCreated == nullptr) {
3404 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3405 __FUNCTION__, captureRequest, handlesCreated);
3406 return;
3407 }
3408
3409 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003410
3411 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003412
3413 {
3414 std::lock_guard<std::mutex> lock(mInflightLock);
3415 if (request->input_buffer != nullptr) {
3416 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3417 buffer_handle_t buf = *(request->input_buffer->buffer);
3418 auto pair = getBufferId(buf, streamId);
3419 bool isNewBuffer = pair.first;
3420 uint64_t bufferId = pair.second;
3421 captureRequest->inputBuffer.streamId = streamId;
3422 captureRequest->inputBuffer.bufferId = bufferId;
3423 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3424 captureRequest->inputBuffer.status = BufferStatus::OK;
3425 native_handle_t *acquireFence = nullptr;
3426 if (request->input_buffer->acquire_fence != -1) {
3427 acquireFence = native_handle_create(1,0);
3428 acquireFence->data[0] = request->input_buffer->acquire_fence;
3429 handlesCreated->push_back(acquireFence);
3430 }
3431 captureRequest->inputBuffer.acquireFence = acquireFence;
3432 captureRequest->inputBuffer.releaseFence = nullptr;
3433
3434 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3435 request->input_buffer->buffer,
3436 request->input_buffer->acquire_fence);
3437 } else {
3438 captureRequest->inputBuffer.streamId = -1;
3439 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3440 }
3441
3442 captureRequest->outputBuffers.resize(request->num_output_buffers);
3443 for (size_t i = 0; i < request->num_output_buffers; i++) {
3444 const camera3_stream_buffer_t *src = request->output_buffers + i;
3445 StreamBuffer &dst = captureRequest->outputBuffers[i];
3446 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3447 buffer_handle_t buf = *(src->buffer);
3448 auto pair = getBufferId(buf, streamId);
3449 bool isNewBuffer = pair.first;
3450 dst.streamId = streamId;
3451 dst.bufferId = pair.second;
3452 dst.buffer = isNewBuffer ? buf : nullptr;
3453 dst.status = BufferStatus::OK;
3454 native_handle_t *acquireFence = nullptr;
3455 if (src->acquire_fence != -1) {
3456 acquireFence = native_handle_create(1,0);
3457 acquireFence->data[0] = src->acquire_fence;
3458 handlesCreated->push_back(acquireFence);
3459 }
3460 dst.acquireFence = acquireFence;
3461 dst.releaseFence = nullptr;
3462
3463 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3464 src->buffer, src->acquire_fence);
3465 }
3466 }
3467}
3468
3469status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3470 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3471 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3472 if (!valid()) return INVALID_OPERATION;
3473
3474 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3475 size_t batchSize = requests.size();
3476 captureRequests.resize(batchSize);
3477 std::vector<native_handle_t*> handlesCreated;
3478
3479 for (size_t i = 0; i < batchSize; i++) {
3480 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3481 }
3482
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003483 std::vector<device::V3_2::BufferCache> cachesToRemove;
3484 {
3485 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3486 for (auto& pair : mFreedBuffers) {
3487 // The stream might have been removed since onBufferFreed
3488 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3489 cachesToRemove.push_back({pair.first, pair.second});
3490 }
3491 }
3492 mFreedBuffers.clear();
3493 }
3494
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003495 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3496 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003497
3498 // Write metadata to FMQ.
3499 for (size_t i = 0; i < batchSize; i++) {
3500 camera3_capture_request_t* request = requests[i];
3501 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3502
3503 if (request->settings != nullptr) {
3504 size_t settingsSize = get_camera_metadata_size(request->settings);
3505 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3506 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3507 captureRequest->settings.resize(0);
3508 captureRequest->fmqSettingsSize = settingsSize;
3509 } else {
3510 if (mRequestMetadataQueue != nullptr) {
3511 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3512 }
3513 captureRequest->settings.setToExternal(
3514 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3515 get_camera_metadata_size(request->settings));
3516 captureRequest->fmqSettingsSize = 0u;
3517 }
3518 } else {
3519 // A null request settings maps to a size-0 CameraMetadata
3520 captureRequest->settings.resize(0);
3521 captureRequest->fmqSettingsSize = 0u;
3522 }
3523 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003524 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003525 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3526 status = s;
3527 *numRequestProcessed = n;
3528 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003529 if (!err.isOk()) {
3530 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3531 return DEAD_OBJECT;
3532 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003533 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3534 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3535 __FUNCTION__, *numRequestProcessed, batchSize);
3536 status = common::V1_0::Status::INTERNAL_ERROR;
3537 }
3538
3539 for (auto& handle : handlesCreated) {
3540 native_handle_delete(handle);
3541 }
3542 return CameraProviderManager::mapToStatusT(status);
3543}
3544
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003545status_t Camera3Device::HalInterface::processCaptureRequest(
3546 camera3_capture_request_t *request) {
3547 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003548 if (!valid()) return INVALID_OPERATION;
3549 status_t res = OK;
3550
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551 uint32_t numRequestProcessed = 0;
3552 std::vector<camera3_capture_request_t*> requests(1);
3553 requests[0] = request;
3554 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 return res;
3557}
3558
3559status_t Camera3Device::HalInterface::flush() {
3560 ATRACE_NAME("CameraHal::flush");
3561 if (!valid()) return INVALID_OPERATION;
3562 status_t res = OK;
3563
Emilian Peev31abd0a2017-05-11 18:37:46 +01003564 auto err = mHidlSession->flush();
3565 if (!err.isOk()) {
3566 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3567 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003568 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003569 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003570 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003571
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003572 return res;
3573}
3574
Emilian Peev31abd0a2017-05-11 18:37:46 +01003575status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003576 ATRACE_NAME("CameraHal::dump");
3577 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003578
Emilian Peev31abd0a2017-05-11 18:37:46 +01003579 // Handled by CameraProviderManager::dump
3580
3581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003582}
3583
3584status_t Camera3Device::HalInterface::close() {
3585 ATRACE_NAME("CameraHal::close()");
3586 if (!valid()) return INVALID_OPERATION;
3587 status_t res = OK;
3588
Emilian Peev31abd0a2017-05-11 18:37:46 +01003589 auto err = mHidlSession->close();
3590 // Interface will be dead shortly anyway, so don't log errors
3591 if (!err.isOk()) {
3592 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003593 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003594
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003595 return res;
3596}
3597
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003598void Camera3Device::HalInterface::getInflightBufferKeys(
3599 std::vector<std::pair<int32_t, int32_t>>* out) {
3600 std::lock_guard<std::mutex> lock(mInflightLock);
3601 out->clear();
3602 out->reserve(mInflightBufferMap.size());
3603 for (auto& pair : mInflightBufferMap) {
3604 uint64_t key = pair.first;
3605 int32_t streamId = key & 0xFFFFFFFF;
3606 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3607 out->push_back(std::make_pair(frameNumber, streamId));
3608 }
3609 return;
3610}
3611
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003612status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003613 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003614 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003615 auto pair = std::make_pair(buffer, acquireFence);
3616 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003617 return OK;
3618}
3619
3620status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003621 int32_t frameNumber, int32_t streamId,
3622 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003623 std::lock_guard<std::mutex> lock(mInflightLock);
3624
3625 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3626 auto it = mInflightBufferMap.find(key);
3627 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003628 auto pair = it->second;
3629 *buffer = pair.first;
3630 int acquireFence = pair.second;
3631 if (acquireFence > 0) {
3632 ::close(acquireFence);
3633 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003634 mInflightBufferMap.erase(it);
3635 return OK;
3636}
3637
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003638std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3639 const buffer_handle_t& buf, int streamId) {
3640 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3641
3642 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3643 auto it = bIdMap.find(buf);
3644 if (it == bIdMap.end()) {
3645 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003646 ALOGV("stream %d now have %zu buffer caches, buf %p",
3647 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003648 return std::make_pair(true, mNextBufferId - 1);
3649 } else {
3650 return std::make_pair(false, it->second);
3651 }
3652}
3653
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003654void Camera3Device::HalInterface::onBufferFreed(
3655 int streamId, const native_handle_t* handle) {
3656 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3657 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3658 auto mapIt = mBufferIdMaps.find(streamId);
3659 if (mapIt == mBufferIdMaps.end()) {
3660 // streamId might be from a deleted stream here
3661 ALOGI("%s: stream %d has been removed",
3662 __FUNCTION__, streamId);
3663 return;
3664 }
3665 BufferIdMap& bIdMap = mapIt->second;
3666 auto it = bIdMap.find(handle);
3667 if (it == bIdMap.end()) {
3668 ALOGW("%s: cannot find buffer %p in stream %d",
3669 __FUNCTION__, handle, streamId);
3670 return;
3671 } else {
3672 bufferId = it->second;
3673 bIdMap.erase(it);
3674 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3675 __FUNCTION__, streamId, bIdMap.size(), handle);
3676 }
3677 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3678}
3679
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003680/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003681 * RequestThread inner class methods
3682 */
3683
3684Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003685 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003686 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003687 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003688 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003689 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003690 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003691 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003692 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003693 mReconfigured(false),
3694 mDoPause(false),
3695 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003696 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003697 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003698 mCurrentAfTriggerId(0),
3699 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003700 mRepeatingLastFrameNumber(
3701 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003702 mPrepareVideoStream(false),
3703 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003704 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003705}
3706
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003707Camera3Device::RequestThread::~RequestThread() {}
3708
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003709void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003710 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003711 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 Mutex::Autolock l(mRequestLock);
3713 mListener = listener;
3714}
3715
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003716void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003717 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003718 Mutex::Autolock l(mRequestLock);
3719 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003720 // Prepare video stream for high speed recording.
3721 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003722}
3723
Jianing Wei90e59c92014-03-12 18:29:36 -07003724status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003725 List<sp<CaptureRequest> > &requests,
3726 /*out*/
3727 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003728 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003729 Mutex::Autolock l(mRequestLock);
3730 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3731 ++it) {
3732 mRequestQueue.push_back(*it);
3733 }
3734
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003735 if (lastFrameNumber != NULL) {
3736 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3737 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3738 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3739 *lastFrameNumber);
3740 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003741
Jianing Wei90e59c92014-03-12 18:29:36 -07003742 unpauseForNewRequests();
3743
3744 return OK;
3745}
3746
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003747
3748status_t Camera3Device::RequestThread::queueTrigger(
3749 RequestTrigger trigger[],
3750 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003751 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003752 Mutex::Autolock l(mTriggerMutex);
3753 status_t ret;
3754
3755 for (size_t i = 0; i < count; ++i) {
3756 ret = queueTriggerLocked(trigger[i]);
3757
3758 if (ret != OK) {
3759 return ret;
3760 }
3761 }
3762
3763 return OK;
3764}
3765
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003766const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3767 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003768 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003769 if (d != nullptr) return d->mId;
3770 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003771}
3772
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003773status_t Camera3Device::RequestThread::queueTriggerLocked(
3774 RequestTrigger trigger) {
3775
3776 uint32_t tag = trigger.metadataTag;
3777 ssize_t index = mTriggerMap.indexOfKey(tag);
3778
3779 switch (trigger.getTagType()) {
3780 case TYPE_BYTE:
3781 // fall-through
3782 case TYPE_INT32:
3783 break;
3784 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003785 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3786 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003787 return INVALID_OPERATION;
3788 }
3789
3790 /**
3791 * Collect only the latest trigger, since we only have 1 field
3792 * in the request settings per trigger tag, and can't send more than 1
3793 * trigger per request.
3794 */
3795 if (index != NAME_NOT_FOUND) {
3796 mTriggerMap.editValueAt(index) = trigger;
3797 } else {
3798 mTriggerMap.add(tag, trigger);
3799 }
3800
3801 return OK;
3802}
3803
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003804status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003805 const RequestList &requests,
3806 /*out*/
3807 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003808 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003809 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003810 if (lastFrameNumber != NULL) {
3811 *lastFrameNumber = mRepeatingLastFrameNumber;
3812 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003813 mRepeatingRequests.clear();
3814 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3815 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003816
3817 unpauseForNewRequests();
3818
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003819 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003820 return OK;
3821}
3822
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003823bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003824 if (mRepeatingRequests.empty()) {
3825 return false;
3826 }
3827 int32_t requestId = requestIn->mResultExtras.requestId;
3828 const RequestList &repeatRequests = mRepeatingRequests;
3829 // All repeating requests are guaranteed to have same id so only check first quest
3830 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3831 return (firstRequest->mResultExtras.requestId == requestId);
3832}
3833
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003834status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003835 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003836 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003837 return clearRepeatingRequestsLocked(lastFrameNumber);
3838
3839}
3840
3841status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003842 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003843 if (lastFrameNumber != NULL) {
3844 *lastFrameNumber = mRepeatingLastFrameNumber;
3845 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003846 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003847 return OK;
3848}
3849
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003850status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003851 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003852 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003853 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003854 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003855
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003856 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003857
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003858 // Send errors for all requests pending in the request queue, including
3859 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003860 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003861 if (listener != NULL) {
3862 for (RequestList::iterator it = mRequestQueue.begin();
3863 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003864 // Abort the input buffers for reprocess requests.
3865 if ((*it)->mInputStream != NULL) {
3866 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003867 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3868 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003869 if (res != OK) {
3870 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3871 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3872 } else {
3873 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3874 if (res != OK) {
3875 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3876 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3877 }
3878 }
3879 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003880 // Set the frame number this request would have had, if it
3881 // had been submitted; this frame number will not be reused.
3882 // The requestId and burstId fields were set when the request was
3883 // submitted originally (in convertMetadataListToRequestListLocked)
3884 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003885 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003886 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003887 }
3888 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003889 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003890
3891 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003892 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003893 if (lastFrameNumber != NULL) {
3894 *lastFrameNumber = mRepeatingLastFrameNumber;
3895 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003896 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003897 return OK;
3898}
3899
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003900status_t Camera3Device::RequestThread::flush() {
3901 ATRACE_CALL();
3902 Mutex::Autolock l(mFlushLock);
3903
Emilian Peev08dd2452017-04-06 16:55:14 +01003904 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003905}
3906
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003907void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003908 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003909 Mutex::Autolock l(mPauseLock);
3910 mDoPause = paused;
3911 mDoPauseSignal.signal();
3912}
3913
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003914status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3915 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003916 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003917 Mutex::Autolock l(mLatestRequestMutex);
3918 status_t res;
3919 while (mLatestRequestId != requestId) {
3920 nsecs_t startTime = systemTime();
3921
3922 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3923 if (res != OK) return res;
3924
3925 timeout -= (systemTime() - startTime);
3926 }
3927
3928 return OK;
3929}
3930
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003931void Camera3Device::RequestThread::requestExit() {
3932 // Call parent to set up shutdown
3933 Thread::requestExit();
3934 // The exit from any possible waits
3935 mDoPauseSignal.signal();
3936 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003937
3938 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3939 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003940}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003941
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003942void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003943 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003944 bool surfaceAbandoned = false;
3945 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003946 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003947 {
3948 Mutex::Autolock l(mRequestLock);
3949 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3950 // repeating requests.
3951 for (const auto& request : mRepeatingRequests) {
3952 for (const auto& s : request->mOutputStreams) {
3953 if (s->isAbandoned()) {
3954 surfaceAbandoned = true;
3955 clearRepeatingRequestsLocked(&lastFrameNumber);
3956 break;
3957 }
3958 }
3959 if (surfaceAbandoned) {
3960 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003961 }
3962 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003963 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003964 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003965
3966 if (listener != NULL && surfaceAbandoned) {
3967 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003968 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003969}
3970
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003971bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003972 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003973 status_t res;
3974 size_t batchSize = mNextRequests.size();
3975 std::vector<camera3_capture_request_t*> requests(batchSize);
3976 uint32_t numRequestProcessed = 0;
3977 for (size_t i = 0; i < batchSize; i++) {
3978 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3979 }
3980
3981 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3982 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3983
3984 bool triggerRemoveFailed = false;
3985 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3986 for (size_t i = 0; i < numRequestProcessed; i++) {
3987 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3988 nextRequest.submitted = true;
3989
3990
3991 // Update the latest request sent to HAL
3992 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3993 Mutex::Autolock al(mLatestRequestMutex);
3994
3995 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3996 mLatestRequest.acquire(cloned);
3997
3998 sp<Camera3Device> parent = mParent.promote();
3999 if (parent != NULL) {
4000 parent->monitorMetadata(TagMonitor::REQUEST,
4001 nextRequest.halRequest.frame_number,
4002 0, mLatestRequest);
4003 }
4004 }
4005
4006 if (nextRequest.halRequest.settings != NULL) {
4007 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4008 }
4009
4010 if (!triggerRemoveFailed) {
4011 // Remove any previously queued triggers (after unlock)
4012 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4013 if (removeTriggerRes != OK) {
4014 triggerRemoveFailed = true;
4015 triggerFailedRequest = nextRequest;
4016 }
4017 }
4018 }
4019
4020 if (triggerRemoveFailed) {
4021 SET_ERR("RequestThread: Unable to remove triggers "
4022 "(capture request %d, HAL device: %s (%d)",
4023 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4024 cleanUpFailedRequests(/*sendRequestError*/ false);
4025 return false;
4026 }
4027
4028 if (res != OK) {
4029 // Should only get a failure here for malformed requests or device-level
4030 // errors, so consider all errors fatal. Bad metadata failures should
4031 // come through notify.
4032 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4033 mNextRequests[numRequestProcessed].halRequest.frame_number,
4034 strerror(-res), res);
4035 cleanUpFailedRequests(/*sendRequestError*/ false);
4036 return false;
4037 }
4038 return true;
4039}
4040
4041bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4042 status_t res;
4043
4044 for (auto& nextRequest : mNextRequests) {
4045 // Submit request and block until ready for next one
4046 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4047 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4048
4049 if (res != OK) {
4050 // Should only get a failure here for malformed requests or device-level
4051 // errors, so consider all errors fatal. Bad metadata failures should
4052 // come through notify.
4053 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4054 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4055 res);
4056 cleanUpFailedRequests(/*sendRequestError*/ false);
4057 return false;
4058 }
4059
4060 // Mark that the request has be submitted successfully.
4061 nextRequest.submitted = true;
4062
4063 // Update the latest request sent to HAL
4064 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4065 Mutex::Autolock al(mLatestRequestMutex);
4066
4067 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4068 mLatestRequest.acquire(cloned);
4069
4070 sp<Camera3Device> parent = mParent.promote();
4071 if (parent != NULL) {
4072 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4073 0, mLatestRequest);
4074 }
4075 }
4076
4077 if (nextRequest.halRequest.settings != NULL) {
4078 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4079 }
4080
4081 // Remove any previously queued triggers (after unlock)
4082 res = removeTriggers(mPrevRequest);
4083 if (res != OK) {
4084 SET_ERR("RequestThread: Unable to remove triggers "
4085 "(capture request %d, HAL device: %s (%d)",
4086 nextRequest.halRequest.frame_number, strerror(-res), res);
4087 cleanUpFailedRequests(/*sendRequestError*/ false);
4088 return false;
4089 }
4090 }
4091 return true;
4092}
4093
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004094nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4095 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4096 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4097 find_camera_metadata_ro_entry(request,
4098 ANDROID_CONTROL_AE_MODE,
4099 &e);
4100 if (e.count == 0) return maxExpectedDuration;
4101
4102 switch (e.data.u8[0]) {
4103 case ANDROID_CONTROL_AE_MODE_OFF:
4104 find_camera_metadata_ro_entry(request,
4105 ANDROID_SENSOR_EXPOSURE_TIME,
4106 &e);
4107 if (e.count > 0) {
4108 maxExpectedDuration = e.data.i64[0];
4109 }
4110 find_camera_metadata_ro_entry(request,
4111 ANDROID_SENSOR_FRAME_DURATION,
4112 &e);
4113 if (e.count > 0) {
4114 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4115 }
4116 break;
4117 default:
4118 find_camera_metadata_ro_entry(request,
4119 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4120 &e);
4121 if (e.count > 1) {
4122 maxExpectedDuration = 1e9 / e.data.u8[0];
4123 }
4124 break;
4125 }
4126
4127 return maxExpectedDuration;
4128}
4129
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004130bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004132 status_t res;
4133
4134 // Handle paused state.
4135 if (waitIfPaused()) {
4136 return true;
4137 }
4138
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004139 // Wait for the next batch of requests.
4140 waitForNextRequestBatch();
4141 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004142 return true;
4143 }
4144
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004145 // Get the latest request ID, if any
4146 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004147 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004148 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004149 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004150 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004151 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004152 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4153 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004154 }
4155
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004156 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004157 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004158 if (res == TIMED_OUT) {
4159 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004160 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004161 // Check if any stream is abandoned.
4162 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004163 return true;
4164 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004165 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004166 return false;
4167 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004168
Zhijun Hecc27e112013-10-03 16:12:43 -07004169 // Inform waitUntilRequestProcessed thread of a new request ID
4170 {
4171 Mutex::Autolock al(mLatestRequestMutex);
4172
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004173 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004174 mLatestRequestSignal.signal();
4175 }
4176
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004177 // Submit a batch of requests to HAL.
4178 // Use flush lock only when submitting multilple requests in a batch.
4179 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4180 // which may take a long time to finish so synchronizing flush() and
4181 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4182 // For now, only synchronize for high speed recording and we should figure something out for
4183 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004184 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004185
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004186 if (useFlushLock) {
4187 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004188 }
4189
Zhijun Hef0645c12016-08-02 00:58:11 -07004190 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004191 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004192
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004193 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004194 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004195 if (mInterface->supportBatchRequest()) {
4196 submitRequestSuccess = sendRequestsBatch();
4197 } else {
4198 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004199 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004200 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4201 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004202
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004203 if (useFlushLock) {
4204 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004206
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004207 // Unset as current request
4208 {
4209 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004210 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004211 }
4212
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004213 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214}
4215
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004216status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004217 ATRACE_CALL();
4218
Shuzhen Wang4a472662017-02-26 23:29:04 -08004219 for (size_t i = 0; i < mNextRequests.size(); i++) {
4220 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004221 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4222 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4223 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4224
4225 // Prepare a request to HAL
4226 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4227
4228 // Insert any queued triggers (before metadata is locked)
4229 status_t res = insertTriggers(captureRequest);
4230
4231 if (res < 0) {
4232 SET_ERR("RequestThread: Unable to insert triggers "
4233 "(capture request %d, HAL device: %s (%d)",
4234 halRequest->frame_number, strerror(-res), res);
4235 return INVALID_OPERATION;
4236 }
4237 int triggerCount = res;
4238 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4239 mPrevTriggers = triggerCount;
4240
4241 // If the request is the same as last, or we had triggers last time
4242 if (mPrevRequest != captureRequest || triggersMixedIn) {
4243 /**
4244 * HAL workaround:
4245 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4246 */
4247 res = addDummyTriggerIds(captureRequest);
4248 if (res != OK) {
4249 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4250 "(capture request %d, HAL device: %s (%d)",
4251 halRequest->frame_number, strerror(-res), res);
4252 return INVALID_OPERATION;
4253 }
4254
4255 /**
4256 * The request should be presorted so accesses in HAL
4257 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4258 */
4259 captureRequest->mSettings.sort();
4260 halRequest->settings = captureRequest->mSettings.getAndLock();
4261 mPrevRequest = captureRequest;
4262 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4263
4264 IF_ALOGV() {
4265 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4266 find_camera_metadata_ro_entry(
4267 halRequest->settings,
4268 ANDROID_CONTROL_AF_TRIGGER,
4269 &e
4270 );
4271 if (e.count > 0) {
4272 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4273 __FUNCTION__,
4274 halRequest->frame_number,
4275 e.data.u8[0]);
4276 }
4277 }
4278 } else {
4279 // leave request.settings NULL to indicate 'reuse latest given'
4280 ALOGVV("%s: Request settings are REUSED",
4281 __FUNCTION__);
4282 }
4283
4284 uint32_t totalNumBuffers = 0;
4285
4286 // Fill in buffers
4287 if (captureRequest->mInputStream != NULL) {
4288 halRequest->input_buffer = &captureRequest->mInputBuffer;
4289 totalNumBuffers += 1;
4290 } else {
4291 halRequest->input_buffer = NULL;
4292 }
4293
4294 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4295 captureRequest->mOutputStreams.size());
4296 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004297 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4298 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004299
4300 // Prepare video buffers for high speed recording on the first video request.
4301 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4302 // Only try to prepare video stream on the first video request.
4303 mPrepareVideoStream = false;
4304
4305 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4306 while (res == NOT_ENOUGH_DATA) {
4307 res = outputStream->prepareNextBuffer();
4308 }
4309 if (res != OK) {
4310 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4311 __FUNCTION__, strerror(-res), res);
4312 outputStream->cancelPrepare();
4313 }
4314 }
4315
Shuzhen Wang4a472662017-02-26 23:29:04 -08004316 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4317 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004318 if (res != OK) {
4319 // Can't get output buffer from gralloc queue - this could be due to
4320 // abandoned queue or other consumer misbehavior, so not a fatal
4321 // error
4322 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4323 " %s (%d)", strerror(-res), res);
4324
4325 return TIMED_OUT;
4326 }
4327 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004328
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004329 }
4330 totalNumBuffers += halRequest->num_output_buffers;
4331
4332 // Log request in the in-flight queue
4333 sp<Camera3Device> parent = mParent.promote();
4334 if (parent == NULL) {
4335 // Should not happen, and nowhere to send errors to, so just log it
4336 CLOGE("RequestThread: Parent is gone");
4337 return INVALID_OPERATION;
4338 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004339
4340 // If this request list is for constrained high speed recording (not
4341 // preview), and the current request is not the last one in the batch,
4342 // do not send callback to the app.
4343 bool hasCallback = true;
4344 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4345 hasCallback = false;
4346 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004347 res = parent->registerInFlight(halRequest->frame_number,
4348 totalNumBuffers, captureRequest->mResultExtras,
4349 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004350 hasCallback,
4351 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004352 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4353 ", burstId = %" PRId32 ".",
4354 __FUNCTION__,
4355 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4356 captureRequest->mResultExtras.burstId);
4357 if (res != OK) {
4358 SET_ERR("RequestThread: Unable to register new in-flight request:"
4359 " %s (%d)", strerror(-res), res);
4360 return INVALID_OPERATION;
4361 }
4362 }
4363
4364 return OK;
4365}
4366
Igor Murashkin1e479c02013-09-06 16:55:14 -07004367CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004368 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004369 Mutex::Autolock al(mLatestRequestMutex);
4370
4371 ALOGV("RequestThread::%s", __FUNCTION__);
4372
4373 return mLatestRequest;
4374}
4375
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004376bool Camera3Device::RequestThread::isStreamPending(
4377 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004378 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004379 Mutex::Autolock l(mRequestLock);
4380
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004382 if (!nextRequest.submitted) {
4383 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4384 if (stream == s) return true;
4385 }
4386 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004387 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004388 }
4389
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004390 for (const auto& request : mRequestQueue) {
4391 for (const auto& s : request->mOutputStreams) {
4392 if (stream == s) return true;
4393 }
4394 if (stream == request->mInputStream) return true;
4395 }
4396
4397 for (const auto& request : mRepeatingRequests) {
4398 for (const auto& s : request->mOutputStreams) {
4399 if (stream == s) return true;
4400 }
4401 if (stream == request->mInputStream) return true;
4402 }
4403
4404 return false;
4405}
Jianing Weicb0652e2014-03-12 18:29:36 -07004406
Emilian Peev40ead602017-09-26 15:46:36 +01004407bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4408 ATRACE_CALL();
4409 Mutex::Autolock l(mRequestLock);
4410
4411 for (const auto& nextRequest : mNextRequests) {
4412 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4413 if (s.first == streamId) {
4414 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4415 if (it != s.second.end()) {
4416 return true;
4417 }
4418 }
4419 }
4420 }
4421
4422 for (const auto& request : mRequestQueue) {
4423 for (const auto& s : request->mOutputSurfaces) {
4424 if (s.first == streamId) {
4425 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4426 if (it != s.second.end()) {
4427 return true;
4428 }
4429 }
4430 }
4431 }
4432
4433 for (const auto& request : mRepeatingRequests) {
4434 for (const auto& s : request->mOutputSurfaces) {
4435 if (s.first == streamId) {
4436 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4437 if (it != s.second.end()) {
4438 return true;
4439 }
4440 }
4441 }
4442 }
4443
4444 return false;
4445}
4446
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004447nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004448 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004449 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004450 return mExpectedInflightDuration > kMinInflightDuration ?
4451 mExpectedInflightDuration : kMinInflightDuration;
4452}
4453
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004454void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4455 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004456 return;
4457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004458
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004459 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004460 // Skip the ones that have been submitted successfully.
4461 if (nextRequest.submitted) {
4462 continue;
4463 }
4464
4465 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4466 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4467 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4468
4469 if (halRequest->settings != NULL) {
4470 captureRequest->mSettings.unlock(halRequest->settings);
4471 }
4472
4473 if (captureRequest->mInputStream != NULL) {
4474 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4475 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4476 }
4477
4478 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004479 //Buffers that failed processing could still have
4480 //valid acquire fence.
4481 int acquireFence = (*outputBuffers)[i].acquire_fence;
4482 if (0 <= acquireFence) {
4483 close(acquireFence);
4484 outputBuffers->editItemAt(i).acquire_fence = -1;
4485 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004486 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4487 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4488 }
4489
4490 if (sendRequestError) {
4491 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004492 sp<NotificationListener> listener = mListener.promote();
4493 if (listener != NULL) {
4494 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004495 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004496 captureRequest->mResultExtras);
4497 }
4498 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004499
4500 // Remove yet-to-be submitted inflight request from inflightMap
4501 {
4502 sp<Camera3Device> parent = mParent.promote();
4503 if (parent != NULL) {
4504 Mutex::Autolock l(parent->mInFlightLock);
4505 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4506 if (idx >= 0) {
4507 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4508 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4509 parent->removeInFlightMapEntryLocked(idx);
4510 }
4511 }
4512 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004513 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004514
4515 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004516 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004517}
4518
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004519void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004520 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004521 // Optimized a bit for the simple steady-state case (single repeating
4522 // request), to avoid putting that request in the queue temporarily.
4523 Mutex::Autolock l(mRequestLock);
4524
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004525 assert(mNextRequests.empty());
4526
4527 NextRequest nextRequest;
4528 nextRequest.captureRequest = waitForNextRequestLocked();
4529 if (nextRequest.captureRequest == nullptr) {
4530 return;
4531 }
4532
4533 nextRequest.halRequest = camera3_capture_request_t();
4534 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004535 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004536
4537 // Wait for additional requests
4538 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4539
4540 for (size_t i = 1; i < batchSize; i++) {
4541 NextRequest additionalRequest;
4542 additionalRequest.captureRequest = waitForNextRequestLocked();
4543 if (additionalRequest.captureRequest == nullptr) {
4544 break;
4545 }
4546
4547 additionalRequest.halRequest = camera3_capture_request_t();
4548 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004549 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004550 }
4551
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004552 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004553 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004554 mNextRequests.size(), batchSize);
4555 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004556 }
4557
4558 return;
4559}
4560
4561sp<Camera3Device::CaptureRequest>
4562 Camera3Device::RequestThread::waitForNextRequestLocked() {
4563 status_t res;
4564 sp<CaptureRequest> nextRequest;
4565
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004566 while (mRequestQueue.empty()) {
4567 if (!mRepeatingRequests.empty()) {
4568 // Always atomically enqueue all requests in a repeating request
4569 // list. Guarantees a complete in-sequence set of captures to
4570 // application.
4571 const RequestList &requests = mRepeatingRequests;
4572 RequestList::const_iterator firstRequest =
4573 requests.begin();
4574 nextRequest = *firstRequest;
4575 mRequestQueue.insert(mRequestQueue.end(),
4576 ++firstRequest,
4577 requests.end());
4578 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004579
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004580 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004581
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004582 break;
4583 }
4584
4585 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4586
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004587 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4588 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004589 Mutex::Autolock pl(mPauseLock);
4590 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004591 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004592 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004593 // Let the tracker know
4594 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4595 if (statusTracker != 0) {
4596 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4597 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004598 }
4599 // Stop waiting for now and let thread management happen
4600 return NULL;
4601 }
4602 }
4603
4604 if (nextRequest == NULL) {
4605 // Don't have a repeating request already in hand, so queue
4606 // must have an entry now.
4607 RequestList::iterator firstRequest =
4608 mRequestQueue.begin();
4609 nextRequest = *firstRequest;
4610 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004611 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4612 sp<NotificationListener> listener = mListener.promote();
4613 if (listener != NULL) {
4614 listener->notifyRequestQueueEmpty();
4615 }
4616 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004617 }
4618
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004619 // In case we've been unpaused by setPaused clearing mDoPause, need to
4620 // update internal pause state (capture/setRepeatingRequest unpause
4621 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004622 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004623 if (mPaused) {
4624 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4625 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4626 if (statusTracker != 0) {
4627 statusTracker->markComponentActive(mStatusId);
4628 }
4629 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004630 mPaused = false;
4631
4632 // Check if we've reconfigured since last time, and reset the preview
4633 // request if so. Can't use 'NULL request == repeat' across configure calls.
4634 if (mReconfigured) {
4635 mPrevRequest.clear();
4636 mReconfigured = false;
4637 }
4638
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004639 if (nextRequest != NULL) {
4640 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004641 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4642 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004643
4644 // Since RequestThread::clear() removes buffers from the input stream,
4645 // get the right buffer here before unlocking mRequestLock
4646 if (nextRequest->mInputStream != NULL) {
4647 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4648 if (res != OK) {
4649 // Can't get input buffer from gralloc queue - this could be due to
4650 // disconnected queue or other producer misbehavior, so not a fatal
4651 // error
4652 ALOGE("%s: Can't get input buffer, skipping request:"
4653 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004654
4655 sp<NotificationListener> listener = mListener.promote();
4656 if (listener != NULL) {
4657 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004658 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004659 nextRequest->mResultExtras);
4660 }
4661 return NULL;
4662 }
4663 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004664 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004666 return nextRequest;
4667}
4668
4669bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004670 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004671 status_t res;
4672 Mutex::Autolock l(mPauseLock);
4673 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004674 if (mPaused == false) {
4675 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004676 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4677 // Let the tracker know
4678 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4679 if (statusTracker != 0) {
4680 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4681 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004682 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004683
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004684 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004685 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004686 return true;
4687 }
4688 }
4689 // We don't set mPaused to false here, because waitForNextRequest needs
4690 // to further manage the paused state in case of starvation.
4691 return false;
4692}
4693
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004694void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004695 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004696 // With work to do, mark thread as unpaused.
4697 // If paused by request (setPaused), don't resume, to avoid
4698 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004699 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004700 Mutex::Autolock p(mPauseLock);
4701 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004702 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4703 if (mPaused) {
4704 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4705 if (statusTracker != 0) {
4706 statusTracker->markComponentActive(mStatusId);
4707 }
4708 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004709 mPaused = false;
4710 }
4711}
4712
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004713void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4714 sp<Camera3Device> parent = mParent.promote();
4715 if (parent != NULL) {
4716 va_list args;
4717 va_start(args, fmt);
4718
4719 parent->setErrorStateV(fmt, args);
4720
4721 va_end(args);
4722 }
4723}
4724
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004725status_t Camera3Device::RequestThread::insertTriggers(
4726 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004727 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004728 Mutex::Autolock al(mTriggerMutex);
4729
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004730 sp<Camera3Device> parent = mParent.promote();
4731 if (parent == NULL) {
4732 CLOGE("RequestThread: Parent is gone");
4733 return DEAD_OBJECT;
4734 }
4735
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004736 CameraMetadata &metadata = request->mSettings;
4737 size_t count = mTriggerMap.size();
4738
4739 for (size_t i = 0; i < count; ++i) {
4740 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004741 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004742
4743 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4744 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4745 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004746 if (isAeTrigger) {
4747 request->mResultExtras.precaptureTriggerId = triggerId;
4748 mCurrentPreCaptureTriggerId = triggerId;
4749 } else {
4750 request->mResultExtras.afTriggerId = triggerId;
4751 mCurrentAfTriggerId = triggerId;
4752 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004753 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004754 }
4755
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004756 camera_metadata_entry entry = metadata.find(tag);
4757
4758 if (entry.count > 0) {
4759 /**
4760 * Already has an entry for this trigger in the request.
4761 * Rewrite it with our requested trigger value.
4762 */
4763 RequestTrigger oldTrigger = trigger;
4764
4765 oldTrigger.entryValue = entry.data.u8[0];
4766
4767 mTriggerReplacedMap.add(tag, oldTrigger);
4768 } else {
4769 /**
4770 * More typical, no trigger entry, so we just add it
4771 */
4772 mTriggerRemovedMap.add(tag, trigger);
4773 }
4774
4775 status_t res;
4776
4777 switch (trigger.getTagType()) {
4778 case TYPE_BYTE: {
4779 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4780 res = metadata.update(tag,
4781 &entryValue,
4782 /*count*/1);
4783 break;
4784 }
4785 case TYPE_INT32:
4786 res = metadata.update(tag,
4787 &trigger.entryValue,
4788 /*count*/1);
4789 break;
4790 default:
4791 ALOGE("%s: Type not supported: 0x%x",
4792 __FUNCTION__,
4793 trigger.getTagType());
4794 return INVALID_OPERATION;
4795 }
4796
4797 if (res != OK) {
4798 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4799 ", value %d", __FUNCTION__, trigger.getTagName(),
4800 trigger.entryValue);
4801 return res;
4802 }
4803
4804 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4805 trigger.getTagName(),
4806 trigger.entryValue);
4807 }
4808
4809 mTriggerMap.clear();
4810
4811 return count;
4812}
4813
4814status_t Camera3Device::RequestThread::removeTriggers(
4815 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004816 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004817 Mutex::Autolock al(mTriggerMutex);
4818
4819 CameraMetadata &metadata = request->mSettings;
4820
4821 /**
4822 * Replace all old entries with their old values.
4823 */
4824 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4825 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4826
4827 status_t res;
4828
4829 uint32_t tag = trigger.metadataTag;
4830 switch (trigger.getTagType()) {
4831 case TYPE_BYTE: {
4832 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4833 res = metadata.update(tag,
4834 &entryValue,
4835 /*count*/1);
4836 break;
4837 }
4838 case TYPE_INT32:
4839 res = metadata.update(tag,
4840 &trigger.entryValue,
4841 /*count*/1);
4842 break;
4843 default:
4844 ALOGE("%s: Type not supported: 0x%x",
4845 __FUNCTION__,
4846 trigger.getTagType());
4847 return INVALID_OPERATION;
4848 }
4849
4850 if (res != OK) {
4851 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4852 ", trigger value %d", __FUNCTION__,
4853 trigger.getTagName(), trigger.entryValue);
4854 return res;
4855 }
4856 }
4857 mTriggerReplacedMap.clear();
4858
4859 /**
4860 * Remove all new entries.
4861 */
4862 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4863 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4864 status_t res = metadata.erase(trigger.metadataTag);
4865
4866 if (res != OK) {
4867 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4868 ", trigger value %d", __FUNCTION__,
4869 trigger.getTagName(), trigger.entryValue);
4870 return res;
4871 }
4872 }
4873 mTriggerRemovedMap.clear();
4874
4875 return OK;
4876}
4877
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004878status_t Camera3Device::RequestThread::addDummyTriggerIds(
4879 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004880 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004881 static const int32_t dummyTriggerId = 1;
4882 status_t res;
4883
4884 CameraMetadata &metadata = request->mSettings;
4885
4886 // If AF trigger is active, insert a dummy AF trigger ID if none already
4887 // exists
4888 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4889 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4890 if (afTrigger.count > 0 &&
4891 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4892 afId.count == 0) {
4893 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4894 if (res != OK) return res;
4895 }
4896
4897 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4898 // if none already exists
4899 camera_metadata_entry pcTrigger =
4900 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4901 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4902 if (pcTrigger.count > 0 &&
4903 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4904 pcId.count == 0) {
4905 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4906 &dummyTriggerId, 1);
4907 if (res != OK) return res;
4908 }
4909
4910 return OK;
4911}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004912
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004913/**
4914 * PreparerThread inner class methods
4915 */
4916
4917Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004918 Thread(/*canCallJava*/false), mListener(nullptr),
4919 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004920}
4921
4922Camera3Device::PreparerThread::~PreparerThread() {
4923 Thread::requestExitAndWait();
4924 if (mCurrentStream != nullptr) {
4925 mCurrentStream->cancelPrepare();
4926 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4927 mCurrentStream.clear();
4928 }
4929 clear();
4930}
4931
Ruben Brunkc78ac262015-08-13 17:58:46 -07004932status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004933 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004934 status_t res;
4935
4936 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004937 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004938
Ruben Brunkc78ac262015-08-13 17:58:46 -07004939 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004940 if (res == OK) {
4941 // No preparation needed, fire listener right off
4942 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004943 if (listener != NULL) {
4944 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004945 }
4946 return OK;
4947 } else if (res != NOT_ENOUGH_DATA) {
4948 return res;
4949 }
4950
4951 // Need to prepare, start up thread if necessary
4952 if (!mActive) {
4953 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4954 // isn't running
4955 Thread::requestExitAndWait();
4956 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4957 if (res != OK) {
4958 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004959 if (listener != NULL) {
4960 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004961 }
4962 return res;
4963 }
4964 mCancelNow = false;
4965 mActive = true;
4966 ALOGV("%s: Preparer stream started", __FUNCTION__);
4967 }
4968
4969 // queue up the work
4970 mPendingStreams.push_back(stream);
4971 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4972
4973 return OK;
4974}
4975
4976status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004977 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004978 Mutex::Autolock l(mLock);
4979
4980 for (const auto& stream : mPendingStreams) {
4981 stream->cancelPrepare();
4982 }
4983 mPendingStreams.clear();
4984 mCancelNow = true;
4985
4986 return OK;
4987}
4988
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004989void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004990 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004991 Mutex::Autolock l(mLock);
4992 mListener = listener;
4993}
4994
4995bool Camera3Device::PreparerThread::threadLoop() {
4996 status_t res;
4997 {
4998 Mutex::Autolock l(mLock);
4999 if (mCurrentStream == nullptr) {
5000 // End thread if done with work
5001 if (mPendingStreams.empty()) {
5002 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5003 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5004 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5005 mActive = false;
5006 return false;
5007 }
5008
5009 // Get next stream to prepare
5010 auto it = mPendingStreams.begin();
5011 mCurrentStream = *it;
5012 mPendingStreams.erase(it);
5013 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5014 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5015 } else if (mCancelNow) {
5016 mCurrentStream->cancelPrepare();
5017 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5018 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5019 mCurrentStream.clear();
5020 mCancelNow = false;
5021 return true;
5022 }
5023 }
5024
5025 res = mCurrentStream->prepareNextBuffer();
5026 if (res == NOT_ENOUGH_DATA) return true;
5027 if (res != OK) {
5028 // Something bad happened; try to recover by cancelling prepare and
5029 // signalling listener anyway
5030 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5031 mCurrentStream->getId(), res, strerror(-res));
5032 mCurrentStream->cancelPrepare();
5033 }
5034
5035 // This stream has finished, notify listener
5036 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005037 sp<NotificationListener> listener = mListener.promote();
5038 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005039 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5040 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005041 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005042 }
5043
5044 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5045 mCurrentStream.clear();
5046
5047 return true;
5048}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005049
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005050/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005051 * Static callback forwarding methods from HAL to instance
5052 */
5053
5054void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5055 const camera3_capture_result *result) {
5056 Camera3Device *d =
5057 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005058
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005059 d->processCaptureResult(result);
5060}
5061
5062void Camera3Device::sNotify(const camera3_callback_ops *cb,
5063 const camera3_notify_msg *msg) {
5064 Camera3Device *d =
5065 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5066 d->notify(msg);
5067}
5068
5069}; // namespace android