blob: c0db8e7634aa98720477b042e761cb7e80fec04c [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
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002042status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2043 Mutex::Autolock il(mInterfaceLock);
2044 Mutex::Autolock l(mLock);
2045
2046 int idx = mOutputStreams.indexOfKey(streamId);
2047 if (idx == NAME_NOT_FOUND) {
2048 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2049 return BAD_VALUE;
2050 }
2051
2052 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2053 return stream->dropBuffers(dropping);
2054}
2055
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002056/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002057 * Camera3Device private methods
2058 */
2059
2060sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002061 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062 ATRACE_CALL();
2063 status_t res;
2064
2065 sp<CaptureRequest> newRequest = new CaptureRequest;
2066 newRequest->mSettings = request;
2067
2068 camera_metadata_entry_t inputStreams =
2069 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2070 if (inputStreams.count > 0) {
2071 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002072 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002073 CLOGE("Request references unknown input stream %d",
2074 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 return NULL;
2076 }
2077 // Lazy completion of stream configuration (allocation/registration)
2078 // on first use
2079 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002080 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002081 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002082 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002084 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002085 return NULL;
2086 }
2087 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002088 // Check if stream is being prepared
2089 if (mInputStream->isPreparing()) {
2090 CLOGE("Request references an input stream that's being prepared!");
2091 return NULL;
2092 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093
2094 newRequest->mInputStream = mInputStream;
2095 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2096 }
2097
2098 camera_metadata_entry_t streams =
2099 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2100 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002101 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 return NULL;
2103 }
2104
2105 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002106 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002108 CLOGE("Request references unknown stream %d",
2109 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110 return NULL;
2111 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002112 sp<Camera3OutputStreamInterface> stream =
2113 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114
Zhijun He5d677d12016-05-29 16:52:39 -07002115 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002116 auto iter = surfaceMap.find(streams.data.i32[i]);
2117 if (iter != surfaceMap.end()) {
2118 const std::vector<size_t>& surfaces = iter->second;
2119 for (const auto& surface : surfaces) {
2120 if (stream->isConsumerConfigurationDeferred(surface)) {
2121 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2122 "due to deferred consumer", stream->getId(), surface);
2123 return NULL;
2124 }
2125 }
2126 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002127 }
2128
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 // Lazy completion of stream configuration (allocation/registration)
2130 // on first use
2131 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002132 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002134 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2135 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 return NULL;
2137 }
2138 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002139 // Check if stream is being prepared
2140 if (stream->isPreparing()) {
2141 CLOGE("Request references an output stream that's being prepared!");
2142 return NULL;
2143 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144
2145 newRequest->mOutputStreams.push(stream);
2146 }
2147 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002148 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149
2150 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002151}
2152
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002153bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2154 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2155 Size size = mSupportedOpaqueInputSizes[i];
2156 if (size.width == width && size.height == height) {
2157 return true;
2158 }
2159 }
2160
2161 return false;
2162}
2163
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002164void Camera3Device::cancelStreamsConfigurationLocked() {
2165 int res = OK;
2166 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2167 res = mInputStream->cancelConfiguration();
2168 if (res != OK) {
2169 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2170 mInputStream->getId(), strerror(-res), res);
2171 }
2172 }
2173
2174 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2175 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2176 if (outputStream->isConfiguring()) {
2177 res = outputStream->cancelConfiguration();
2178 if (res != OK) {
2179 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2180 outputStream->getId(), strerror(-res), res);
2181 }
2182 }
2183 }
2184
2185 // Return state to that at start of call, so that future configures
2186 // properly clean things up
2187 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2188 mNeedConfig = true;
2189}
2190
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002191status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002192 ATRACE_CALL();
2193 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002196 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002197 return INVALID_OPERATION;
2198 }
2199
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002200 if (operatingMode < 0) {
2201 CLOGE("Invalid operating mode: %d", operatingMode);
2202 return BAD_VALUE;
2203 }
2204
2205 bool isConstrainedHighSpeed =
2206 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2207 operatingMode;
2208
2209 if (mOperatingMode != operatingMode) {
2210 mNeedConfig = true;
2211 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2212 mOperatingMode = operatingMode;
2213 }
2214
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002215 if (!mNeedConfig) {
2216 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2217 return OK;
2218 }
2219
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002220 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2221 // adding a dummy stream instead.
2222 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2223 if (mOutputStreams.size() == 0) {
2224 addDummyStreamLocked();
2225 } else {
2226 tryRemoveDummyStreamLocked();
2227 }
2228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002229 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002230 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231
2232 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002233 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2235
2236 Vector<camera3_stream_t*> streams;
2237 streams.setCapacity(config.num_streams);
2238
2239 if (mInputStream != NULL) {
2240 camera3_stream_t *inputStream;
2241 inputStream = mInputStream->startConfiguration();
2242 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002243 CLOGE("Can't start input stream configuration");
2244 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245 return INVALID_OPERATION;
2246 }
2247 streams.add(inputStream);
2248 }
2249
2250 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002251
2252 // Don't configure bidi streams twice, nor add them twice to the list
2253 if (mOutputStreams[i].get() ==
2254 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2255
2256 config.num_streams--;
2257 continue;
2258 }
2259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002260 camera3_stream_t *outputStream;
2261 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2262 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002263 CLOGE("Can't start output stream configuration");
2264 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 return INVALID_OPERATION;
2266 }
2267 streams.add(outputStream);
2268 }
2269
2270 config.streams = streams.editArray();
2271
2272 // Do the HAL configuration; will potentially touch stream
2273 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002274
2275 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002277 if (res == BAD_VALUE) {
2278 // HAL rejected this set of streams as unsupported, clean up config
2279 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002280 CLOGE("Set of requested inputs/outputs not supported by HAL");
2281 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002282 return BAD_VALUE;
2283 } else if (res != OK) {
2284 // Some other kind of error from configure_streams - this is not
2285 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002286 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2287 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288 return res;
2289 }
2290
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002291 // Finish all stream configuration immediately.
2292 // TODO: Try to relax this later back to lazy completion, which should be
2293 // faster
2294
Igor Murashkin073f8572013-05-02 14:59:28 -07002295 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002296 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002297 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002298 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002299 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002300 cancelStreamsConfigurationLocked();
2301 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002302 }
2303 }
2304
2305 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002306 sp<Camera3OutputStreamInterface> outputStream =
2307 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002308 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002309 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002310 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002311 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002312 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002313 cancelStreamsConfigurationLocked();
2314 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002315 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002316 }
2317 }
2318
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 // Request thread needs to know to avoid using repeat-last-settings protocol
2320 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002321 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002322
Zhijun He90f7c372016-08-16 16:19:43 -07002323 char value[PROPERTY_VALUE_MAX];
2324 property_get("camera.fifo.disable", value, "0");
2325 int32_t disableFifo = atoi(value);
2326 if (disableFifo != 1) {
2327 // Boost priority of request thread to SCHED_FIFO.
2328 pid_t requestThreadTid = mRequestThread->getTid();
2329 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002330 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002331 if (res != OK) {
2332 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2333 strerror(-res), res);
2334 } else {
2335 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2336 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002337 }
2338
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002339 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002340
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002341 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002342
Ruben Brunk183f0562015-08-12 12:55:02 -07002343 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2344 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002345
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002346 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002347
Zhijun He0a210512014-07-24 13:45:15 -07002348 // tear down the deleted streams after configure streams.
2349 mDeletedStreams.clear();
2350
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002352}
2353
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002354status_t Camera3Device::addDummyStreamLocked() {
2355 ATRACE_CALL();
2356 status_t res;
2357
2358 if (mDummyStreamId != NO_STREAM) {
2359 // Should never be adding a second dummy stream when one is already
2360 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002361 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2362 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002363 return INVALID_OPERATION;
2364 }
2365
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002366 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002367
2368 sp<Camera3OutputStreamInterface> dummyStream =
2369 new Camera3DummyStream(mNextStreamId);
2370
2371 res = mOutputStreams.add(mNextStreamId, dummyStream);
2372 if (res < 0) {
2373 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2374 return res;
2375 }
2376
2377 mDummyStreamId = mNextStreamId;
2378 mNextStreamId++;
2379
2380 return OK;
2381}
2382
2383status_t Camera3Device::tryRemoveDummyStreamLocked() {
2384 ATRACE_CALL();
2385 status_t res;
2386
2387 if (mDummyStreamId == NO_STREAM) return OK;
2388 if (mOutputStreams.size() == 1) return OK;
2389
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002390 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002391
2392 // Ok, have a dummy stream and there's at least one other output stream,
2393 // so remove the dummy
2394
2395 sp<Camera3StreamInterface> deletedStream;
2396 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2397 if (outputStreamIdx == NAME_NOT_FOUND) {
2398 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2399 return INVALID_OPERATION;
2400 }
2401
2402 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2403 mOutputStreams.removeItemsAt(outputStreamIdx);
2404
2405 // Free up the stream endpoint so that it can be used by some other stream
2406 res = deletedStream->disconnect();
2407 if (res != OK) {
2408 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2409 // fall through since we want to still list the stream as deleted.
2410 }
2411 mDeletedStreams.add(deletedStream);
2412 mDummyStreamId = NO_STREAM;
2413
2414 return res;
2415}
2416
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002417void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002418 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002419 Mutex::Autolock l(mLock);
2420 va_list args;
2421 va_start(args, fmt);
2422
2423 setErrorStateLockedV(fmt, args);
2424
2425 va_end(args);
2426}
2427
2428void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002429 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002430 Mutex::Autolock l(mLock);
2431 setErrorStateLockedV(fmt, args);
2432}
2433
2434void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2435 va_list args;
2436 va_start(args, fmt);
2437
2438 setErrorStateLockedV(fmt, args);
2439
2440 va_end(args);
2441}
2442
2443void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002444 // Print out all error messages to log
2445 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002446 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002447
2448 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002449 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002450
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002451 mErrorCause = errorCause;
2452
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002453 if (mRequestThread != nullptr) {
2454 mRequestThread->setPaused(true);
2455 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002456 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002457
2458 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002459 sp<NotificationListener> listener = mListener.promote();
2460 if (listener != NULL) {
2461 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002462 CaptureResultExtras());
2463 }
2464
2465 // Save stack trace. View by dumping it later.
2466 CameraTraces::saveTrace();
2467 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002468}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002469
2470/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002471 * In-flight request management
2472 */
2473
Jianing Weicb0652e2014-03-12 18:29:36 -07002474status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002475 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002476 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002477 ATRACE_CALL();
2478 Mutex::Autolock l(mInFlightLock);
2479
2480 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002481 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002482 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002483 if (res < 0) return res;
2484
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002485 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002486 // hold mLock to prevent race with disconnect
2487 Mutex::Autolock l(mLock);
2488 if (mStatusTracker != nullptr) {
2489 mStatusTracker->markComponentActive(mInFlightStatusId);
2490 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002491 }
2492
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002493 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002494 return OK;
2495}
2496
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002497void Camera3Device::returnOutputBuffers(
2498 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2499 nsecs_t timestamp) {
2500 for (size_t i = 0; i < numBuffers; i++)
2501 {
2502 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2503 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2504 // Note: stream may be deallocated at this point, if this buffer was
2505 // the last reference to it.
2506 if (res != OK) {
2507 ALOGE("Can't return buffer to its stream: %s (%d)",
2508 strerror(-res), res);
2509 }
2510 }
2511}
2512
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002513void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002514 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002515 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002516 mInFlightMap.removeItemsAt(idx, 1);
2517
2518 // Indicate idle inFlightMap to the status tracker
2519 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002520 // hold mLock to prevent race with disconnect
2521 Mutex::Autolock l(mLock);
2522 if (mStatusTracker != nullptr) {
2523 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2524 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002525 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002526 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002527}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002528
2529void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2530
2531 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2532 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2533
2534 nsecs_t sensorTimestamp = request.sensorTimestamp;
2535 nsecs_t shutterTimestamp = request.shutterTimestamp;
2536
2537 // Check if it's okay to remove the request from InFlightMap:
2538 // In the case of a successful request:
2539 // all input and output buffers, all result metadata, shutter callback
2540 // arrived.
2541 // In the case of a unsuccessful request:
2542 // all input and output buffers arrived.
2543 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002544 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002545 (request.haveResultMetadata && shutterTimestamp != 0))) {
2546 ATRACE_ASYNC_END("frame capture", frameNumber);
2547
Shuzhen Wang403044a2017-02-26 23:29:04 -08002548 // Sanity check - if sensor timestamp matches shutter timestamp in the
2549 // case of request having callback.
2550 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002551 sensorTimestamp != shutterTimestamp) {
2552 SET_ERR("sensor timestamp (%" PRId64
2553 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2554 sensorTimestamp, frameNumber, shutterTimestamp);
2555 }
2556
2557 // for an unsuccessful request, it may have pending output buffers to
2558 // return.
2559 assert(request.requestStatus != OK ||
2560 request.pendingOutputBuffers.size() == 0);
2561 returnOutputBuffers(request.pendingOutputBuffers.array(),
2562 request.pendingOutputBuffers.size(), 0);
2563
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002564 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002565 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2566 }
2567
2568 // Sanity check - if we have too many in-flight frames, something has
2569 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002570 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002571 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002572 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2573 kInFlightWarnLimitHighSpeed) {
2574 CLOGE("In-flight list too large for high speed configuration: %zu",
2575 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002576 }
2577}
2578
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002579void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002580 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002581 { // First return buffers cached in mInFlightMap
2582 Mutex::Autolock l(mInFlightLock);
2583 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2584 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2585 returnOutputBuffers(request.pendingOutputBuffers.array(),
2586 request.pendingOutputBuffers.size(), 0);
2587 }
2588 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002589 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002590 }
2591
2592 // Then return all inflight buffers not returned by HAL
2593 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2594 mInterface->getInflightBufferKeys(&inflightKeys);
2595
2596 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2597 for (auto& pair : inflightKeys) {
2598 int32_t frameNumber = pair.first;
2599 int32_t streamId = pair.second;
2600 buffer_handle_t* buffer;
2601 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2602 if (res != OK) {
2603 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2604 __FUNCTION__, frameNumber, streamId);
2605 continue;
2606 }
2607
2608 camera3_stream_buffer_t streamBuffer;
2609 streamBuffer.buffer = buffer;
2610 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2611 streamBuffer.acquire_fence = -1;
2612 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002613
2614 // First check if the buffer belongs to deleted stream
2615 bool streamDeleted = false;
2616 for (auto& stream : mDeletedStreams) {
2617 if (streamId == stream->getId()) {
2618 streamDeleted = true;
2619 // Return buffer to deleted stream
2620 camera3_stream* halStream = stream->asHalStream();
2621 streamBuffer.stream = halStream;
2622 switch (halStream->stream_type) {
2623 case CAMERA3_STREAM_OUTPUT:
2624 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2625 if (res != OK) {
2626 ALOGE("%s: Can't return output buffer for frame %d to"
2627 " stream %d: %s (%d)", __FUNCTION__,
2628 frameNumber, streamId, strerror(-res), res);
2629 }
2630 break;
2631 case CAMERA3_STREAM_INPUT:
2632 res = stream->returnInputBuffer(streamBuffer);
2633 if (res != OK) {
2634 ALOGE("%s: Can't return input buffer for frame %d to"
2635 " stream %d: %s (%d)", __FUNCTION__,
2636 frameNumber, streamId, strerror(-res), res);
2637 }
2638 break;
2639 default: // Bi-direcitonal stream is deprecated
2640 ALOGE("%s: stream %d has unknown stream type %d",
2641 __FUNCTION__, streamId, halStream->stream_type);
2642 break;
2643 }
2644 break;
2645 }
2646 }
2647 if (streamDeleted) {
2648 continue;
2649 }
2650
2651 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002652 if (streamId == inputStreamId) {
2653 streamBuffer.stream = mInputStream->asHalStream();
2654 res = mInputStream->returnInputBuffer(streamBuffer);
2655 if (res != OK) {
2656 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002657 " stream %d: %s (%d)", __FUNCTION__,
2658 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002659 }
2660 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002661 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2662 if (idx == NAME_NOT_FOUND) {
2663 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2664 continue;
2665 }
2666 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002667 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2668 }
2669 }
2670}
2671
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002672void Camera3Device::insertResultLocked(CaptureResult *result,
2673 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002674 if (result == nullptr) return;
2675
Emilian Peev71c73a22017-03-21 16:35:51 +00002676 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2677 result->mMetadata.getAndLock());
2678 set_camera_metadata_vendor_id(meta, mVendorTagId);
2679 result->mMetadata.unlock(meta);
2680
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002681 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2682 (int32_t*)&frameNumber, 1) != OK) {
2683 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2684 return;
2685 }
2686
2687 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2688 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2689 return;
2690 }
2691
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002692 // Valid result, insert into queue
2693 List<CaptureResult>::iterator queuedResult =
2694 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2695 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2696 ", burstId = %" PRId32, __FUNCTION__,
2697 queuedResult->mResultExtras.requestId,
2698 queuedResult->mResultExtras.frameNumber,
2699 queuedResult->mResultExtras.burstId);
2700
2701 mResultSignal.signal();
2702}
2703
2704
2705void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002706 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002707 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002708 Mutex::Autolock l(mOutputLock);
2709
2710 CaptureResult captureResult;
2711 captureResult.mResultExtras = resultExtras;
2712 captureResult.mMetadata = partialResult;
2713
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002714 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002715}
2716
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002717
2718void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2719 CaptureResultExtras &resultExtras,
2720 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002721 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002722 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002723 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002724 if (pendingMetadata.isEmpty())
2725 return;
2726
2727 Mutex::Autolock l(mOutputLock);
2728
2729 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002730 if (reprocess) {
2731 if (frameNumber < mNextReprocessResultFrameNumber) {
2732 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002733 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002734 frameNumber, mNextReprocessResultFrameNumber);
2735 return;
2736 }
2737 mNextReprocessResultFrameNumber = frameNumber + 1;
2738 } else {
2739 if (frameNumber < mNextResultFrameNumber) {
2740 SET_ERR("Out-of-order capture result metadata submitted! "
2741 "(got frame number %d, expecting %d)",
2742 frameNumber, mNextResultFrameNumber);
2743 return;
2744 }
2745 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002746 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002747
2748 CaptureResult captureResult;
2749 captureResult.mResultExtras = resultExtras;
2750 captureResult.mMetadata = pendingMetadata;
2751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 // Append any previous partials to form a complete result
2753 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2754 captureResult.mMetadata.append(collectedPartialResult);
2755 }
2756
2757 captureResult.mMetadata.sort();
2758
2759 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002760 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2761 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002762 SET_ERR("No timestamp provided by HAL for frame %d!",
2763 frameNumber);
2764 return;
2765 }
2766
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002767 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2768 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2769
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002770 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771}
2772
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002773/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002774 * Camera HAL device callback methods
2775 */
2776
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002777void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002778 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002779
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002780 status_t res;
2781
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002782 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002783 if (result->result == NULL && result->num_output_buffers == 0 &&
2784 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002785 SET_ERR("No result data provided by HAL for frame %d",
2786 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002787 return;
2788 }
Zhijun He204e3292014-07-14 17:09:23 -07002789
Zhijun He204e3292014-07-14 17:09:23 -07002790 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002791 result->result != NULL &&
2792 result->partial_result != 1) {
2793 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2794 " if partial result is not supported",
2795 frameNumber, result->partial_result);
2796 return;
2797 }
2798
2799 bool isPartialResult = false;
2800 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002801 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002802 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002803
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002804 // Get shutter timestamp and resultExtras from list of in-flight requests,
2805 // where it was added by the shutter notification for this frame. If the
2806 // shutter timestamp isn't received yet, append the output buffers to the
2807 // in-flight request and they will be returned when the shutter timestamp
2808 // arrives. Update the in-flight status and remove the in-flight entry if
2809 // all result data and shutter timestamp have been received.
2810 nsecs_t shutterTimestamp = 0;
2811
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002812 {
2813 Mutex::Autolock l(mInFlightLock);
2814 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2815 if (idx == NAME_NOT_FOUND) {
2816 SET_ERR("Unknown frame number for capture result: %d",
2817 frameNumber);
2818 return;
2819 }
2820 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002821 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2822 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002823 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002824 __FUNCTION__, request.resultExtras.requestId,
2825 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002826 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002827 // Always update the partial count to the latest one if it's not 0
2828 // (buffers only). When framework aggregates adjacent partial results
2829 // into one, the latest partial count will be used.
2830 if (result->partial_result != 0)
2831 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002832
2833 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002834 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002835 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2836 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2837 " the range of [1, %d] when metadata is included in the result",
2838 frameNumber, result->partial_result, mNumPartialResults);
2839 return;
2840 }
2841 isPartialResult = (result->partial_result < mNumPartialResults);
2842 if (isPartialResult) {
2843 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002844 }
2845
Shuzhen Wang4a472662017-02-26 23:29:04 -08002846 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002847 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002848 sendPartialCaptureResult(result->result, request.resultExtras,
2849 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002850 }
2851 }
2852
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002853 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002854 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002855
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002856 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002857 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002858 if (request.haveResultMetadata) {
2859 SET_ERR("Called multiple times with metadata for frame %d",
2860 frameNumber);
2861 return;
2862 }
Zhijun He204e3292014-07-14 17:09:23 -07002863 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002864 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002865 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002866 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002867 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002868 request.haveResultMetadata = true;
2869 }
2870
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002871 uint32_t numBuffersReturned = result->num_output_buffers;
2872 if (result->input_buffer != NULL) {
2873 if (hasInputBufferInRequest) {
2874 numBuffersReturned += 1;
2875 } else {
2876 ALOGW("%s: Input buffer should be NULL if there is no input"
2877 " buffer sent in the request",
2878 __FUNCTION__);
2879 }
2880 }
2881 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002882 if (request.numBuffersLeft < 0) {
2883 SET_ERR("Too many buffers returned for frame %d",
2884 frameNumber);
2885 return;
2886 }
2887
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002888 camera_metadata_ro_entry_t entry;
2889 res = find_camera_metadata_ro_entry(result->result,
2890 ANDROID_SENSOR_TIMESTAMP, &entry);
2891 if (res == OK && entry.count == 1) {
2892 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002893 }
2894
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002895 // If shutter event isn't received yet, append the output buffers to
2896 // the in-flight request. Otherwise, return the output buffers to
2897 // streams.
2898 if (shutterTimestamp == 0) {
2899 request.pendingOutputBuffers.appendArray(result->output_buffers,
2900 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002901 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002902 returnOutputBuffers(result->output_buffers,
2903 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002904 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002905
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002906 if (result->result != NULL && !isPartialResult) {
2907 if (shutterTimestamp == 0) {
2908 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002909 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002910 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002911 CameraMetadata metadata;
2912 metadata = result->result;
2913 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002914 collectedPartialResult, frameNumber,
2915 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002916 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002917 }
2918
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002919 removeInFlightRequestIfReadyLocked(idx);
2920 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002921
Zhijun Hef0d962a2014-06-30 10:24:11 -07002922 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002923 if (hasInputBufferInRequest) {
2924 Camera3Stream *stream =
2925 Camera3Stream::cast(result->input_buffer->stream);
2926 res = stream->returnInputBuffer(*(result->input_buffer));
2927 // Note: stream may be deallocated at this point, if this buffer was the
2928 // last reference to it.
2929 if (res != OK) {
2930 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2931 " its stream:%s (%d)", __FUNCTION__,
2932 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002933 }
2934 } else {
2935 ALOGW("%s: Input buffer should be NULL if there is no input"
2936 " buffer sent in the request, skipping input buffer return.",
2937 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002938 }
2939 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002940}
2941
2942void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002943 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002944 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002945 {
2946 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002947 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002948 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002949
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002950 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002951 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002952 return;
2953 }
2954
2955 switch (msg->type) {
2956 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002957 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002958 break;
2959 }
2960 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002961 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002962 break;
2963 }
2964 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002965 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002966 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002967 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002968}
2969
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002971 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002972 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002973 // Map camera HAL error codes to ICameraDeviceCallback error codes
2974 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002975 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002976 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002977 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002978 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002979 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002980 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002981 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002982 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002983 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002984 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002985 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002986 };
2987
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002988 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002989 ((msg.error_code >= 0) &&
2990 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2991 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002992 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002993
2994 int streamId = 0;
2995 if (msg.error_stream != NULL) {
2996 Camera3Stream *stream =
2997 Camera3Stream::cast(msg.error_stream);
2998 streamId = stream->getId();
2999 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003000 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3001 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003002 streamId, msg.error_code);
3003
3004 CaptureResultExtras resultExtras;
3005 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003006 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003007 // SET_ERR calls notifyError
3008 SET_ERR("Camera HAL reported serious device error");
3009 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3011 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3012 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003013 {
3014 Mutex::Autolock l(mInFlightLock);
3015 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3016 if (idx >= 0) {
3017 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3018 r.requestStatus = msg.error_code;
3019 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003020 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3021 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3022 errorCode) {
3023 r.skipResultMetadata = true;
3024 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003025 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3026 errorCode) {
3027 // In case of missing result check whether the buffers
3028 // returned. If they returned, then remove inflight
3029 // request.
3030 removeInFlightRequestIfReadyLocked(idx);
3031 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003032 } else {
3033 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003034 ALOGE("Camera %s: %s: cannot find in-flight request on "
3035 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003036 resultExtras.frameNumber);
3037 }
3038 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003039 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003040 if (listener != NULL) {
3041 listener->notifyError(errorCode, resultExtras);
3042 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003043 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003044 }
3045 break;
3046 default:
3047 // SET_ERR calls notifyError
3048 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3049 break;
3050 }
3051}
3052
3053void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003054 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003055 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003056 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003057
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003058 // Set timestamp for the request in the in-flight tracking
3059 // and get the request ID to send upstream
3060 {
3061 Mutex::Autolock l(mInFlightLock);
3062 idx = mInFlightMap.indexOfKey(msg.frame_number);
3063 if (idx >= 0) {
3064 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003065
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003066 // Verify ordering of shutter notifications
3067 {
3068 Mutex::Autolock l(mOutputLock);
3069 // TODO: need to track errors for tighter bounds on expected frame number.
3070 if (r.hasInputBuffer) {
3071 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3072 SET_ERR("Shutter notification out-of-order. Expected "
3073 "notification for frame %d, got frame %d",
3074 mNextReprocessShutterFrameNumber, msg.frame_number);
3075 return;
3076 }
3077 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3078 } else {
3079 if (msg.frame_number < mNextShutterFrameNumber) {
3080 SET_ERR("Shutter notification out-of-order. Expected "
3081 "notification for frame %d, got frame %d",
3082 mNextShutterFrameNumber, msg.frame_number);
3083 return;
3084 }
3085 mNextShutterFrameNumber = msg.frame_number + 1;
3086 }
3087 }
3088
Shuzhen Wang4a472662017-02-26 23:29:04 -08003089 r.shutterTimestamp = msg.timestamp;
3090 if (r.hasCallback) {
3091 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003094 // Call listener, if any
3095 if (listener != NULL) {
3096 listener->notifyShutter(r.resultExtras, msg.timestamp);
3097 }
3098 // send pending result and buffers
3099 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3100 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003101 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003102 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003103 returnOutputBuffers(r.pendingOutputBuffers.array(),
3104 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3105 r.pendingOutputBuffers.clear();
3106
3107 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003108 }
3109 }
3110 if (idx < 0) {
3111 SET_ERR("Shutter notification for non-existent frame number %d",
3112 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003113 }
3114}
3115
3116
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003117CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003118 ALOGV("%s", __FUNCTION__);
3119
Igor Murashkin1e479c02013-09-06 16:55:14 -07003120 CameraMetadata retVal;
3121
3122 if (mRequestThread != NULL) {
3123 retVal = mRequestThread->getLatestRequest();
3124 }
3125
Igor Murashkin1e479c02013-09-06 16:55:14 -07003126 return retVal;
3127}
3128
Jianing Weicb0652e2014-03-12 18:29:36 -07003129
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003130void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3131 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3132 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3133}
3134
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003135/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003136 * HalInterface inner class methods
3137 */
3138
Yifan Hongf79b5542017-04-11 14:44:25 -07003139Camera3Device::HalInterface::HalInterface(
3140 sp<ICameraDeviceSession> &session,
3141 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003142 mHidlSession(session),
3143 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003144
Emilian Peev31abd0a2017-05-11 18:37:46 +01003145Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003146
3147Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003148 mHidlSession(other.mHidlSession),
3149 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003150
3151bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003152 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003153}
3154
3155void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003156 mHidlSession.clear();
3157}
3158
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003159bool Camera3Device::HalInterface::supportBatchRequest() {
3160 return mHidlSession != nullptr;
3161}
3162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003163status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3164 camera3_request_template_t templateId,
3165 /*out*/ camera_metadata_t **requestTemplate) {
3166 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3167 if (!valid()) return INVALID_OPERATION;
3168 status_t res = OK;
3169
Emilian Peev31abd0a2017-05-11 18:37:46 +01003170 common::V1_0::Status status;
3171 RequestTemplate id;
3172 switch (templateId) {
3173 case CAMERA3_TEMPLATE_PREVIEW:
3174 id = RequestTemplate::PREVIEW;
3175 break;
3176 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3177 id = RequestTemplate::STILL_CAPTURE;
3178 break;
3179 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3180 id = RequestTemplate::VIDEO_RECORD;
3181 break;
3182 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3183 id = RequestTemplate::VIDEO_SNAPSHOT;
3184 break;
3185 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3186 id = RequestTemplate::ZERO_SHUTTER_LAG;
3187 break;
3188 case CAMERA3_TEMPLATE_MANUAL:
3189 id = RequestTemplate::MANUAL;
3190 break;
3191 default:
3192 // Unknown template ID
3193 return BAD_VALUE;
3194 }
3195 auto err = mHidlSession->constructDefaultRequestSettings(id,
3196 [&status, &requestTemplate]
3197 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3198 status = s;
3199 if (status == common::V1_0::Status::OK) {
3200 const camera_metadata *r =
3201 reinterpret_cast<const camera_metadata_t*>(request.data());
3202 size_t expectedSize = request.size();
3203 int ret = validate_camera_metadata_structure(r, &expectedSize);
3204 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3205 *requestTemplate = clone_camera_metadata(r);
3206 if (*requestTemplate == nullptr) {
3207 ALOGE("%s: Unable to clone camera metadata received from HAL",
3208 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003209 status = common::V1_0::Status::INTERNAL_ERROR;
3210 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211 } else {
3212 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3213 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003214 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003215 }
3216 });
3217 if (!err.isOk()) {
3218 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3219 res = DEAD_OBJECT;
3220 } else {
3221 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003222 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003223
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003224 return res;
3225}
3226
3227status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3228 ATRACE_NAME("CameraHal::configureStreams");
3229 if (!valid()) return INVALID_OPERATION;
3230 status_t res = OK;
3231
Emilian Peev31abd0a2017-05-11 18:37:46 +01003232 // Convert stream config to HIDL
3233 std::set<int> activeStreams;
3234 StreamConfiguration requestedConfiguration;
3235 requestedConfiguration.streams.resize(config->num_streams);
3236 for (size_t i = 0; i < config->num_streams; i++) {
3237 Stream &dst = requestedConfiguration.streams[i];
3238 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003239
Emilian Peev31abd0a2017-05-11 18:37:46 +01003240 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3241 cam3stream->setBufferFreedListener(this);
3242 int streamId = cam3stream->getId();
3243 StreamType streamType;
3244 switch (src->stream_type) {
3245 case CAMERA3_STREAM_OUTPUT:
3246 streamType = StreamType::OUTPUT;
3247 break;
3248 case CAMERA3_STREAM_INPUT:
3249 streamType = StreamType::INPUT;
3250 break;
3251 default:
3252 ALOGE("%s: Stream %d: Unsupported stream type %d",
3253 __FUNCTION__, streamId, config->streams[i]->stream_type);
3254 return BAD_VALUE;
3255 }
3256 dst.id = streamId;
3257 dst.streamType = streamType;
3258 dst.width = src->width;
3259 dst.height = src->height;
3260 dst.format = mapToPixelFormat(src->format);
Emilian Peev050f5dc2017-05-18 14:43:56 +01003261 dst.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peev31abd0a2017-05-11 18:37:46 +01003262 dst.dataSpace = mapToHidlDataspace(src->data_space);
3263 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3264
3265 activeStreams.insert(streamId);
3266 // Create Buffer ID map if necessary
3267 if (mBufferIdMaps.count(streamId) == 0) {
3268 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3269 }
3270 }
3271 // remove BufferIdMap for deleted streams
3272 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3273 int streamId = it->first;
3274 bool active = activeStreams.count(streamId) > 0;
3275 if (!active) {
3276 it = mBufferIdMaps.erase(it);
3277 } else {
3278 ++it;
3279 }
3280 }
3281
3282 res = mapToStreamConfigurationMode(
3283 (camera3_stream_configuration_mode_t) config->operation_mode,
3284 /*out*/ &requestedConfiguration.operationMode);
3285 if (res != OK) {
3286 return res;
3287 }
3288
3289 // Invoke configureStreams
3290
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003291 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003293
3294 // See if we have v3.3 HAL
3295 sp<device::V3_3::ICameraDeviceSession> hidlSession_3_3;
3296 auto castResult = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3297 if (castResult.isOk()) {
3298 hidlSession_3_3 = castResult;
3299 } else {
3300 ALOGE("%s: Transaction error when casting ICameraDeviceSession: %s", __FUNCTION__,
3301 castResult.description().c_str());
3302 }
3303 if (hidlSession_3_3 != nullptr) {
3304 // We do; use v3.3 for the call
3305 ALOGV("%s: v3.3 device found", __FUNCTION__);
3306 auto err = hidlSession_3_3->configureStreams_3_3(requestedConfiguration,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003307 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003308 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003309 finalConfiguration = halConfiguration;
3310 status = s;
3311 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003312 if (!err.isOk()) {
3313 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3314 return DEAD_OBJECT;
3315 }
3316 } else {
3317 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3318 ALOGV("%s: v3.2 device found", __FUNCTION__);
3319 HalStreamConfiguration finalConfiguration_3_2;
3320 auto err = mHidlSession->configureStreams(requestedConfiguration,
3321 [&status, &finalConfiguration_3_2]
3322 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3323 finalConfiguration_3_2 = halConfiguration;
3324 status = s;
3325 });
3326 if (!err.isOk()) {
3327 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3328 return DEAD_OBJECT;
3329 }
3330 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3331 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3332 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3333 finalConfiguration.streams[i].overrideDataSpace =
3334 requestedConfiguration.streams[i].dataSpace;
3335 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003336 }
3337
3338 if (status != common::V1_0::Status::OK ) {
3339 return CameraProviderManager::mapToStatusT(status);
3340 }
3341
3342 // And convert output stream configuration from HIDL
3343
3344 for (size_t i = 0; i < config->num_streams; i++) {
3345 camera3_stream_t *dst = config->streams[i];
3346 int streamId = Camera3Stream::cast(dst)->getId();
3347
3348 // Start scan at i, with the assumption that the stream order matches
3349 size_t realIdx = i;
3350 bool found = false;
3351 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003352 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003353 found = true;
3354 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003355 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003356 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3357 }
3358 if (!found) {
3359 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3360 __FUNCTION__, streamId);
3361 return INVALID_OPERATION;
3362 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003363 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003364
Emilian Peev710c1422017-08-30 11:19:38 +01003365 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3366 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003367 dstStream->setDataSpaceOverride(false);
3368 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3369 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3370
Emilian Peev31abd0a2017-05-11 18:37:46 +01003371 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3372 if (dst->format != overrideFormat) {
3373 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3374 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003375 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003376 if (dst->data_space != overrideDataSpace) {
3377 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3378 streamId, dst->format);
3379 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003380 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003381 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003382 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3383
Emilian Peev31abd0a2017-05-11 18:37:46 +01003384 // Override allowed with IMPLEMENTATION_DEFINED
3385 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003386 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003387 }
3388
Emilian Peev31abd0a2017-05-11 18:37:46 +01003389 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003390 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003391 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003392 __FUNCTION__, streamId);
3393 return INVALID_OPERATION;
3394 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003395 dstStream->setUsage(
3396 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003397 } else {
3398 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003399 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003400 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3401 __FUNCTION__, streamId);
3402 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003403 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003404 dstStream->setUsage(
3405 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003406 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003407 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003408 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003409
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003410 return res;
3411}
3412
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003413void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3414 /*out*/device::V3_2::CaptureRequest* captureRequest,
3415 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003416 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003417 if (captureRequest == nullptr || handlesCreated == nullptr) {
3418 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3419 __FUNCTION__, captureRequest, handlesCreated);
3420 return;
3421 }
3422
3423 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003424
3425 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003426
3427 {
3428 std::lock_guard<std::mutex> lock(mInflightLock);
3429 if (request->input_buffer != nullptr) {
3430 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3431 buffer_handle_t buf = *(request->input_buffer->buffer);
3432 auto pair = getBufferId(buf, streamId);
3433 bool isNewBuffer = pair.first;
3434 uint64_t bufferId = pair.second;
3435 captureRequest->inputBuffer.streamId = streamId;
3436 captureRequest->inputBuffer.bufferId = bufferId;
3437 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3438 captureRequest->inputBuffer.status = BufferStatus::OK;
3439 native_handle_t *acquireFence = nullptr;
3440 if (request->input_buffer->acquire_fence != -1) {
3441 acquireFence = native_handle_create(1,0);
3442 acquireFence->data[0] = request->input_buffer->acquire_fence;
3443 handlesCreated->push_back(acquireFence);
3444 }
3445 captureRequest->inputBuffer.acquireFence = acquireFence;
3446 captureRequest->inputBuffer.releaseFence = nullptr;
3447
3448 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3449 request->input_buffer->buffer,
3450 request->input_buffer->acquire_fence);
3451 } else {
3452 captureRequest->inputBuffer.streamId = -1;
3453 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3454 }
3455
3456 captureRequest->outputBuffers.resize(request->num_output_buffers);
3457 for (size_t i = 0; i < request->num_output_buffers; i++) {
3458 const camera3_stream_buffer_t *src = request->output_buffers + i;
3459 StreamBuffer &dst = captureRequest->outputBuffers[i];
3460 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3461 buffer_handle_t buf = *(src->buffer);
3462 auto pair = getBufferId(buf, streamId);
3463 bool isNewBuffer = pair.first;
3464 dst.streamId = streamId;
3465 dst.bufferId = pair.second;
3466 dst.buffer = isNewBuffer ? buf : nullptr;
3467 dst.status = BufferStatus::OK;
3468 native_handle_t *acquireFence = nullptr;
3469 if (src->acquire_fence != -1) {
3470 acquireFence = native_handle_create(1,0);
3471 acquireFence->data[0] = src->acquire_fence;
3472 handlesCreated->push_back(acquireFence);
3473 }
3474 dst.acquireFence = acquireFence;
3475 dst.releaseFence = nullptr;
3476
3477 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3478 src->buffer, src->acquire_fence);
3479 }
3480 }
3481}
3482
3483status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3484 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3485 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3486 if (!valid()) return INVALID_OPERATION;
3487
3488 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3489 size_t batchSize = requests.size();
3490 captureRequests.resize(batchSize);
3491 std::vector<native_handle_t*> handlesCreated;
3492
3493 for (size_t i = 0; i < batchSize; i++) {
3494 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3495 }
3496
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003497 std::vector<device::V3_2::BufferCache> cachesToRemove;
3498 {
3499 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3500 for (auto& pair : mFreedBuffers) {
3501 // The stream might have been removed since onBufferFreed
3502 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3503 cachesToRemove.push_back({pair.first, pair.second});
3504 }
3505 }
3506 mFreedBuffers.clear();
3507 }
3508
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003509 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3510 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003511
3512 // Write metadata to FMQ.
3513 for (size_t i = 0; i < batchSize; i++) {
3514 camera3_capture_request_t* request = requests[i];
3515 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3516
3517 if (request->settings != nullptr) {
3518 size_t settingsSize = get_camera_metadata_size(request->settings);
3519 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3520 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3521 captureRequest->settings.resize(0);
3522 captureRequest->fmqSettingsSize = settingsSize;
3523 } else {
3524 if (mRequestMetadataQueue != nullptr) {
3525 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3526 }
3527 captureRequest->settings.setToExternal(
3528 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3529 get_camera_metadata_size(request->settings));
3530 captureRequest->fmqSettingsSize = 0u;
3531 }
3532 } else {
3533 // A null request settings maps to a size-0 CameraMetadata
3534 captureRequest->settings.resize(0);
3535 captureRequest->fmqSettingsSize = 0u;
3536 }
3537 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003538 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003539 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3540 status = s;
3541 *numRequestProcessed = n;
3542 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003543 if (!err.isOk()) {
3544 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3545 return DEAD_OBJECT;
3546 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003547 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3548 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3549 __FUNCTION__, *numRequestProcessed, batchSize);
3550 status = common::V1_0::Status::INTERNAL_ERROR;
3551 }
3552
3553 for (auto& handle : handlesCreated) {
3554 native_handle_delete(handle);
3555 }
3556 return CameraProviderManager::mapToStatusT(status);
3557}
3558
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559status_t Camera3Device::HalInterface::processCaptureRequest(
3560 camera3_capture_request_t *request) {
3561 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003562 if (!valid()) return INVALID_OPERATION;
3563 status_t res = OK;
3564
Emilian Peev31abd0a2017-05-11 18:37:46 +01003565 uint32_t numRequestProcessed = 0;
3566 std::vector<camera3_capture_request_t*> requests(1);
3567 requests[0] = request;
3568 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3569
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003570 return res;
3571}
3572
3573status_t Camera3Device::HalInterface::flush() {
3574 ATRACE_NAME("CameraHal::flush");
3575 if (!valid()) return INVALID_OPERATION;
3576 status_t res = OK;
3577
Emilian Peev31abd0a2017-05-11 18:37:46 +01003578 auto err = mHidlSession->flush();
3579 if (!err.isOk()) {
3580 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3581 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003582 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003583 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003584 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003586 return res;
3587}
3588
Emilian Peev31abd0a2017-05-11 18:37:46 +01003589status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003590 ATRACE_NAME("CameraHal::dump");
3591 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003592
Emilian Peev31abd0a2017-05-11 18:37:46 +01003593 // Handled by CameraProviderManager::dump
3594
3595 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003596}
3597
3598status_t Camera3Device::HalInterface::close() {
3599 ATRACE_NAME("CameraHal::close()");
3600 if (!valid()) return INVALID_OPERATION;
3601 status_t res = OK;
3602
Emilian Peev31abd0a2017-05-11 18:37:46 +01003603 auto err = mHidlSession->close();
3604 // Interface will be dead shortly anyway, so don't log errors
3605 if (!err.isOk()) {
3606 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003607 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003608
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003609 return res;
3610}
3611
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003612void Camera3Device::HalInterface::getInflightBufferKeys(
3613 std::vector<std::pair<int32_t, int32_t>>* out) {
3614 std::lock_guard<std::mutex> lock(mInflightLock);
3615 out->clear();
3616 out->reserve(mInflightBufferMap.size());
3617 for (auto& pair : mInflightBufferMap) {
3618 uint64_t key = pair.first;
3619 int32_t streamId = key & 0xFFFFFFFF;
3620 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3621 out->push_back(std::make_pair(frameNumber, streamId));
3622 }
3623 return;
3624}
3625
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003626status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003627 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003628 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003629 auto pair = std::make_pair(buffer, acquireFence);
3630 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003631 return OK;
3632}
3633
3634status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003635 int32_t frameNumber, int32_t streamId,
3636 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003637 std::lock_guard<std::mutex> lock(mInflightLock);
3638
3639 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3640 auto it = mInflightBufferMap.find(key);
3641 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003642 auto pair = it->second;
3643 *buffer = pair.first;
3644 int acquireFence = pair.second;
3645 if (acquireFence > 0) {
3646 ::close(acquireFence);
3647 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003648 mInflightBufferMap.erase(it);
3649 return OK;
3650}
3651
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003652std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3653 const buffer_handle_t& buf, int streamId) {
3654 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3655
3656 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3657 auto it = bIdMap.find(buf);
3658 if (it == bIdMap.end()) {
3659 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003660 ALOGV("stream %d now have %zu buffer caches, buf %p",
3661 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003662 return std::make_pair(true, mNextBufferId - 1);
3663 } else {
3664 return std::make_pair(false, it->second);
3665 }
3666}
3667
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003668void Camera3Device::HalInterface::onBufferFreed(
3669 int streamId, const native_handle_t* handle) {
3670 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3671 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3672 auto mapIt = mBufferIdMaps.find(streamId);
3673 if (mapIt == mBufferIdMaps.end()) {
3674 // streamId might be from a deleted stream here
3675 ALOGI("%s: stream %d has been removed",
3676 __FUNCTION__, streamId);
3677 return;
3678 }
3679 BufferIdMap& bIdMap = mapIt->second;
3680 auto it = bIdMap.find(handle);
3681 if (it == bIdMap.end()) {
3682 ALOGW("%s: cannot find buffer %p in stream %d",
3683 __FUNCTION__, handle, streamId);
3684 return;
3685 } else {
3686 bufferId = it->second;
3687 bIdMap.erase(it);
3688 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3689 __FUNCTION__, streamId, bIdMap.size(), handle);
3690 }
3691 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3692}
3693
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003694/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003695 * RequestThread inner class methods
3696 */
3697
3698Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003699 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003700 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003701 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003702 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003703 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003704 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003705 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003706 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003707 mReconfigured(false),
3708 mDoPause(false),
3709 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003710 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003711 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003712 mCurrentAfTriggerId(0),
3713 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003714 mRepeatingLastFrameNumber(
3715 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003716 mPrepareVideoStream(false),
3717 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003718 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003719}
3720
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003721Camera3Device::RequestThread::~RequestThread() {}
3722
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003723void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003724 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003725 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003726 Mutex::Autolock l(mRequestLock);
3727 mListener = listener;
3728}
3729
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003730void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003731 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003732 Mutex::Autolock l(mRequestLock);
3733 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003734 // Prepare video stream for high speed recording.
3735 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003736}
3737
Jianing Wei90e59c92014-03-12 18:29:36 -07003738status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003739 List<sp<CaptureRequest> > &requests,
3740 /*out*/
3741 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003742 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003743 Mutex::Autolock l(mRequestLock);
3744 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3745 ++it) {
3746 mRequestQueue.push_back(*it);
3747 }
3748
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003749 if (lastFrameNumber != NULL) {
3750 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3751 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3752 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3753 *lastFrameNumber);
3754 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003755
Jianing Wei90e59c92014-03-12 18:29:36 -07003756 unpauseForNewRequests();
3757
3758 return OK;
3759}
3760
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003761
3762status_t Camera3Device::RequestThread::queueTrigger(
3763 RequestTrigger trigger[],
3764 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003765 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003766 Mutex::Autolock l(mTriggerMutex);
3767 status_t ret;
3768
3769 for (size_t i = 0; i < count; ++i) {
3770 ret = queueTriggerLocked(trigger[i]);
3771
3772 if (ret != OK) {
3773 return ret;
3774 }
3775 }
3776
3777 return OK;
3778}
3779
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003780const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3781 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003782 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003783 if (d != nullptr) return d->mId;
3784 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003785}
3786
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003787status_t Camera3Device::RequestThread::queueTriggerLocked(
3788 RequestTrigger trigger) {
3789
3790 uint32_t tag = trigger.metadataTag;
3791 ssize_t index = mTriggerMap.indexOfKey(tag);
3792
3793 switch (trigger.getTagType()) {
3794 case TYPE_BYTE:
3795 // fall-through
3796 case TYPE_INT32:
3797 break;
3798 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003799 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3800 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003801 return INVALID_OPERATION;
3802 }
3803
3804 /**
3805 * Collect only the latest trigger, since we only have 1 field
3806 * in the request settings per trigger tag, and can't send more than 1
3807 * trigger per request.
3808 */
3809 if (index != NAME_NOT_FOUND) {
3810 mTriggerMap.editValueAt(index) = trigger;
3811 } else {
3812 mTriggerMap.add(tag, trigger);
3813 }
3814
3815 return OK;
3816}
3817
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003818status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003819 const RequestList &requests,
3820 /*out*/
3821 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003822 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003823 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003824 if (lastFrameNumber != NULL) {
3825 *lastFrameNumber = mRepeatingLastFrameNumber;
3826 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003827 mRepeatingRequests.clear();
3828 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3829 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003830
3831 unpauseForNewRequests();
3832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003833 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003834 return OK;
3835}
3836
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003837bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003838 if (mRepeatingRequests.empty()) {
3839 return false;
3840 }
3841 int32_t requestId = requestIn->mResultExtras.requestId;
3842 const RequestList &repeatRequests = mRepeatingRequests;
3843 // All repeating requests are guaranteed to have same id so only check first quest
3844 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3845 return (firstRequest->mResultExtras.requestId == requestId);
3846}
3847
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003848status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003849 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003850 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003851 return clearRepeatingRequestsLocked(lastFrameNumber);
3852
3853}
3854
3855status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003856 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003857 if (lastFrameNumber != NULL) {
3858 *lastFrameNumber = mRepeatingLastFrameNumber;
3859 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003860 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003861 return OK;
3862}
3863
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003864status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003865 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003866 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003867 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003868 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003869
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003870 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003871
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003872 // Send errors for all requests pending in the request queue, including
3873 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003874 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003875 if (listener != NULL) {
3876 for (RequestList::iterator it = mRequestQueue.begin();
3877 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003878 // Abort the input buffers for reprocess requests.
3879 if ((*it)->mInputStream != NULL) {
3880 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003881 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3882 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003883 if (res != OK) {
3884 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3885 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3886 } else {
3887 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3888 if (res != OK) {
3889 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3890 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3891 }
3892 }
3893 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003894 // Set the frame number this request would have had, if it
3895 // had been submitted; this frame number will not be reused.
3896 // The requestId and burstId fields were set when the request was
3897 // submitted originally (in convertMetadataListToRequestListLocked)
3898 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003899 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003900 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003901 }
3902 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003903 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003904
3905 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003906 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003907 if (lastFrameNumber != NULL) {
3908 *lastFrameNumber = mRepeatingLastFrameNumber;
3909 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003910 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003911 return OK;
3912}
3913
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003914status_t Camera3Device::RequestThread::flush() {
3915 ATRACE_CALL();
3916 Mutex::Autolock l(mFlushLock);
3917
Emilian Peev08dd2452017-04-06 16:55:14 +01003918 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003919}
3920
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003921void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003922 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003923 Mutex::Autolock l(mPauseLock);
3924 mDoPause = paused;
3925 mDoPauseSignal.signal();
3926}
3927
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003928status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3929 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003930 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003931 Mutex::Autolock l(mLatestRequestMutex);
3932 status_t res;
3933 while (mLatestRequestId != requestId) {
3934 nsecs_t startTime = systemTime();
3935
3936 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3937 if (res != OK) return res;
3938
3939 timeout -= (systemTime() - startTime);
3940 }
3941
3942 return OK;
3943}
3944
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003945void Camera3Device::RequestThread::requestExit() {
3946 // Call parent to set up shutdown
3947 Thread::requestExit();
3948 // The exit from any possible waits
3949 mDoPauseSignal.signal();
3950 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003951
3952 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3953 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003954}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003955
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003956void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003957 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003958 bool surfaceAbandoned = false;
3959 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003960 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003961 {
3962 Mutex::Autolock l(mRequestLock);
3963 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3964 // repeating requests.
3965 for (const auto& request : mRepeatingRequests) {
3966 for (const auto& s : request->mOutputStreams) {
3967 if (s->isAbandoned()) {
3968 surfaceAbandoned = true;
3969 clearRepeatingRequestsLocked(&lastFrameNumber);
3970 break;
3971 }
3972 }
3973 if (surfaceAbandoned) {
3974 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003975 }
3976 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003977 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003978 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003979
3980 if (listener != NULL && surfaceAbandoned) {
3981 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003982 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003983}
3984
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003985bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003986 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003987 status_t res;
3988 size_t batchSize = mNextRequests.size();
3989 std::vector<camera3_capture_request_t*> requests(batchSize);
3990 uint32_t numRequestProcessed = 0;
3991 for (size_t i = 0; i < batchSize; i++) {
3992 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3993 }
3994
3995 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3996 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3997
3998 bool triggerRemoveFailed = false;
3999 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4000 for (size_t i = 0; i < numRequestProcessed; i++) {
4001 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4002 nextRequest.submitted = true;
4003
4004
4005 // Update the latest request sent to HAL
4006 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4007 Mutex::Autolock al(mLatestRequestMutex);
4008
4009 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4010 mLatestRequest.acquire(cloned);
4011
4012 sp<Camera3Device> parent = mParent.promote();
4013 if (parent != NULL) {
4014 parent->monitorMetadata(TagMonitor::REQUEST,
4015 nextRequest.halRequest.frame_number,
4016 0, mLatestRequest);
4017 }
4018 }
4019
4020 if (nextRequest.halRequest.settings != NULL) {
4021 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4022 }
4023
4024 if (!triggerRemoveFailed) {
4025 // Remove any previously queued triggers (after unlock)
4026 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4027 if (removeTriggerRes != OK) {
4028 triggerRemoveFailed = true;
4029 triggerFailedRequest = nextRequest;
4030 }
4031 }
4032 }
4033
4034 if (triggerRemoveFailed) {
4035 SET_ERR("RequestThread: Unable to remove triggers "
4036 "(capture request %d, HAL device: %s (%d)",
4037 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4038 cleanUpFailedRequests(/*sendRequestError*/ false);
4039 return false;
4040 }
4041
4042 if (res != OK) {
4043 // Should only get a failure here for malformed requests or device-level
4044 // errors, so consider all errors fatal. Bad metadata failures should
4045 // come through notify.
4046 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4047 mNextRequests[numRequestProcessed].halRequest.frame_number,
4048 strerror(-res), res);
4049 cleanUpFailedRequests(/*sendRequestError*/ false);
4050 return false;
4051 }
4052 return true;
4053}
4054
4055bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4056 status_t res;
4057
4058 for (auto& nextRequest : mNextRequests) {
4059 // Submit request and block until ready for next one
4060 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4061 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4062
4063 if (res != OK) {
4064 // Should only get a failure here for malformed requests or device-level
4065 // errors, so consider all errors fatal. Bad metadata failures should
4066 // come through notify.
4067 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4068 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4069 res);
4070 cleanUpFailedRequests(/*sendRequestError*/ false);
4071 return false;
4072 }
4073
4074 // Mark that the request has be submitted successfully.
4075 nextRequest.submitted = true;
4076
4077 // Update the latest request sent to HAL
4078 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4079 Mutex::Autolock al(mLatestRequestMutex);
4080
4081 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4082 mLatestRequest.acquire(cloned);
4083
4084 sp<Camera3Device> parent = mParent.promote();
4085 if (parent != NULL) {
4086 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4087 0, mLatestRequest);
4088 }
4089 }
4090
4091 if (nextRequest.halRequest.settings != NULL) {
4092 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4093 }
4094
4095 // Remove any previously queued triggers (after unlock)
4096 res = removeTriggers(mPrevRequest);
4097 if (res != OK) {
4098 SET_ERR("RequestThread: Unable to remove triggers "
4099 "(capture request %d, HAL device: %s (%d)",
4100 nextRequest.halRequest.frame_number, strerror(-res), res);
4101 cleanUpFailedRequests(/*sendRequestError*/ false);
4102 return false;
4103 }
4104 }
4105 return true;
4106}
4107
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004108nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4109 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4110 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4111 find_camera_metadata_ro_entry(request,
4112 ANDROID_CONTROL_AE_MODE,
4113 &e);
4114 if (e.count == 0) return maxExpectedDuration;
4115
4116 switch (e.data.u8[0]) {
4117 case ANDROID_CONTROL_AE_MODE_OFF:
4118 find_camera_metadata_ro_entry(request,
4119 ANDROID_SENSOR_EXPOSURE_TIME,
4120 &e);
4121 if (e.count > 0) {
4122 maxExpectedDuration = e.data.i64[0];
4123 }
4124 find_camera_metadata_ro_entry(request,
4125 ANDROID_SENSOR_FRAME_DURATION,
4126 &e);
4127 if (e.count > 0) {
4128 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4129 }
4130 break;
4131 default:
4132 find_camera_metadata_ro_entry(request,
4133 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4134 &e);
4135 if (e.count > 1) {
4136 maxExpectedDuration = 1e9 / e.data.u8[0];
4137 }
4138 break;
4139 }
4140
4141 return maxExpectedDuration;
4142}
4143
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004144bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004145 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004146 status_t res;
4147
4148 // Handle paused state.
4149 if (waitIfPaused()) {
4150 return true;
4151 }
4152
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004153 // Wait for the next batch of requests.
4154 waitForNextRequestBatch();
4155 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004156 return true;
4157 }
4158
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004159 // Get the latest request ID, if any
4160 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004161 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004162 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004163 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004164 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004165 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004166 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4167 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004168 }
4169
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004170 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004171 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004172 if (res == TIMED_OUT) {
4173 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004174 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004175 // Check if any stream is abandoned.
4176 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004177 return true;
4178 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004179 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004180 return false;
4181 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004182
Zhijun Hecc27e112013-10-03 16:12:43 -07004183 // Inform waitUntilRequestProcessed thread of a new request ID
4184 {
4185 Mutex::Autolock al(mLatestRequestMutex);
4186
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004187 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004188 mLatestRequestSignal.signal();
4189 }
4190
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004191 // Submit a batch of requests to HAL.
4192 // Use flush lock only when submitting multilple requests in a batch.
4193 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4194 // which may take a long time to finish so synchronizing flush() and
4195 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4196 // For now, only synchronize for high speed recording and we should figure something out for
4197 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004198 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004199
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004200 if (useFlushLock) {
4201 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004202 }
4203
Zhijun Hef0645c12016-08-02 00:58:11 -07004204 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004205 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004206
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004207 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004208 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004209 if (mInterface->supportBatchRequest()) {
4210 submitRequestSuccess = sendRequestsBatch();
4211 } else {
4212 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004213 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004214 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4215 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004216
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004217 if (useFlushLock) {
4218 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004219 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004220
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004221 // Unset as current request
4222 {
4223 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004224 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004225 }
4226
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004227 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004228}
4229
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004230status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004231 ATRACE_CALL();
4232
Shuzhen Wang4a472662017-02-26 23:29:04 -08004233 for (size_t i = 0; i < mNextRequests.size(); i++) {
4234 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004235 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4236 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4237 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4238
4239 // Prepare a request to HAL
4240 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4241
4242 // Insert any queued triggers (before metadata is locked)
4243 status_t res = insertTriggers(captureRequest);
4244
4245 if (res < 0) {
4246 SET_ERR("RequestThread: Unable to insert triggers "
4247 "(capture request %d, HAL device: %s (%d)",
4248 halRequest->frame_number, strerror(-res), res);
4249 return INVALID_OPERATION;
4250 }
4251 int triggerCount = res;
4252 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4253 mPrevTriggers = triggerCount;
4254
4255 // If the request is the same as last, or we had triggers last time
4256 if (mPrevRequest != captureRequest || triggersMixedIn) {
4257 /**
4258 * HAL workaround:
4259 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4260 */
4261 res = addDummyTriggerIds(captureRequest);
4262 if (res != OK) {
4263 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4264 "(capture request %d, HAL device: %s (%d)",
4265 halRequest->frame_number, strerror(-res), res);
4266 return INVALID_OPERATION;
4267 }
4268
4269 /**
4270 * The request should be presorted so accesses in HAL
4271 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4272 */
4273 captureRequest->mSettings.sort();
4274 halRequest->settings = captureRequest->mSettings.getAndLock();
4275 mPrevRequest = captureRequest;
4276 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4277
4278 IF_ALOGV() {
4279 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4280 find_camera_metadata_ro_entry(
4281 halRequest->settings,
4282 ANDROID_CONTROL_AF_TRIGGER,
4283 &e
4284 );
4285 if (e.count > 0) {
4286 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4287 __FUNCTION__,
4288 halRequest->frame_number,
4289 e.data.u8[0]);
4290 }
4291 }
4292 } else {
4293 // leave request.settings NULL to indicate 'reuse latest given'
4294 ALOGVV("%s: Request settings are REUSED",
4295 __FUNCTION__);
4296 }
4297
4298 uint32_t totalNumBuffers = 0;
4299
4300 // Fill in buffers
4301 if (captureRequest->mInputStream != NULL) {
4302 halRequest->input_buffer = &captureRequest->mInputBuffer;
4303 totalNumBuffers += 1;
4304 } else {
4305 halRequest->input_buffer = NULL;
4306 }
4307
4308 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4309 captureRequest->mOutputStreams.size());
4310 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004311 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4312 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004313
4314 // Prepare video buffers for high speed recording on the first video request.
4315 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4316 // Only try to prepare video stream on the first video request.
4317 mPrepareVideoStream = false;
4318
4319 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4320 while (res == NOT_ENOUGH_DATA) {
4321 res = outputStream->prepareNextBuffer();
4322 }
4323 if (res != OK) {
4324 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4325 __FUNCTION__, strerror(-res), res);
4326 outputStream->cancelPrepare();
4327 }
4328 }
4329
Shuzhen Wang4a472662017-02-26 23:29:04 -08004330 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4331 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004332 if (res != OK) {
4333 // Can't get output buffer from gralloc queue - this could be due to
4334 // abandoned queue or other consumer misbehavior, so not a fatal
4335 // error
4336 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4337 " %s (%d)", strerror(-res), res);
4338
4339 return TIMED_OUT;
4340 }
4341 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004342
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004343 }
4344 totalNumBuffers += halRequest->num_output_buffers;
4345
4346 // Log request in the in-flight queue
4347 sp<Camera3Device> parent = mParent.promote();
4348 if (parent == NULL) {
4349 // Should not happen, and nowhere to send errors to, so just log it
4350 CLOGE("RequestThread: Parent is gone");
4351 return INVALID_OPERATION;
4352 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004353
4354 // If this request list is for constrained high speed recording (not
4355 // preview), and the current request is not the last one in the batch,
4356 // do not send callback to the app.
4357 bool hasCallback = true;
4358 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4359 hasCallback = false;
4360 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004361 res = parent->registerInFlight(halRequest->frame_number,
4362 totalNumBuffers, captureRequest->mResultExtras,
4363 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004364 hasCallback,
4365 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004366 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4367 ", burstId = %" PRId32 ".",
4368 __FUNCTION__,
4369 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4370 captureRequest->mResultExtras.burstId);
4371 if (res != OK) {
4372 SET_ERR("RequestThread: Unable to register new in-flight request:"
4373 " %s (%d)", strerror(-res), res);
4374 return INVALID_OPERATION;
4375 }
4376 }
4377
4378 return OK;
4379}
4380
Igor Murashkin1e479c02013-09-06 16:55:14 -07004381CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004382 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004383 Mutex::Autolock al(mLatestRequestMutex);
4384
4385 ALOGV("RequestThread::%s", __FUNCTION__);
4386
4387 return mLatestRequest;
4388}
4389
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004390bool Camera3Device::RequestThread::isStreamPending(
4391 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004392 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004393 Mutex::Autolock l(mRequestLock);
4394
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004395 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004396 if (!nextRequest.submitted) {
4397 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4398 if (stream == s) return true;
4399 }
4400 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004401 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004402 }
4403
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004404 for (const auto& request : mRequestQueue) {
4405 for (const auto& s : request->mOutputStreams) {
4406 if (stream == s) return true;
4407 }
4408 if (stream == request->mInputStream) return true;
4409 }
4410
4411 for (const auto& request : mRepeatingRequests) {
4412 for (const auto& s : request->mOutputStreams) {
4413 if (stream == s) return true;
4414 }
4415 if (stream == request->mInputStream) return true;
4416 }
4417
4418 return false;
4419}
Jianing Weicb0652e2014-03-12 18:29:36 -07004420
Emilian Peev40ead602017-09-26 15:46:36 +01004421bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4422 ATRACE_CALL();
4423 Mutex::Autolock l(mRequestLock);
4424
4425 for (const auto& nextRequest : mNextRequests) {
4426 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4427 if (s.first == streamId) {
4428 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4429 if (it != s.second.end()) {
4430 return true;
4431 }
4432 }
4433 }
4434 }
4435
4436 for (const auto& request : mRequestQueue) {
4437 for (const auto& s : request->mOutputSurfaces) {
4438 if (s.first == streamId) {
4439 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4440 if (it != s.second.end()) {
4441 return true;
4442 }
4443 }
4444 }
4445 }
4446
4447 for (const auto& request : mRepeatingRequests) {
4448 for (const auto& s : request->mOutputSurfaces) {
4449 if (s.first == streamId) {
4450 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4451 if (it != s.second.end()) {
4452 return true;
4453 }
4454 }
4455 }
4456 }
4457
4458 return false;
4459}
4460
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004461nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004462 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004463 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004464 return mExpectedInflightDuration > kMinInflightDuration ?
4465 mExpectedInflightDuration : kMinInflightDuration;
4466}
4467
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004468void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4469 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004470 return;
4471 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004472
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004473 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004474 // Skip the ones that have been submitted successfully.
4475 if (nextRequest.submitted) {
4476 continue;
4477 }
4478
4479 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4480 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4481 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4482
4483 if (halRequest->settings != NULL) {
4484 captureRequest->mSettings.unlock(halRequest->settings);
4485 }
4486
4487 if (captureRequest->mInputStream != NULL) {
4488 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4489 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4490 }
4491
4492 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004493 //Buffers that failed processing could still have
4494 //valid acquire fence.
4495 int acquireFence = (*outputBuffers)[i].acquire_fence;
4496 if (0 <= acquireFence) {
4497 close(acquireFence);
4498 outputBuffers->editItemAt(i).acquire_fence = -1;
4499 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004500 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4501 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4502 }
4503
4504 if (sendRequestError) {
4505 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004506 sp<NotificationListener> listener = mListener.promote();
4507 if (listener != NULL) {
4508 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004509 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004510 captureRequest->mResultExtras);
4511 }
4512 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004513
4514 // Remove yet-to-be submitted inflight request from inflightMap
4515 {
4516 sp<Camera3Device> parent = mParent.promote();
4517 if (parent != NULL) {
4518 Mutex::Autolock l(parent->mInFlightLock);
4519 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4520 if (idx >= 0) {
4521 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4522 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4523 parent->removeInFlightMapEntryLocked(idx);
4524 }
4525 }
4526 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004527 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004528
4529 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004530 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004531}
4532
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004533void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004534 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004535 // Optimized a bit for the simple steady-state case (single repeating
4536 // request), to avoid putting that request in the queue temporarily.
4537 Mutex::Autolock l(mRequestLock);
4538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004539 assert(mNextRequests.empty());
4540
4541 NextRequest nextRequest;
4542 nextRequest.captureRequest = waitForNextRequestLocked();
4543 if (nextRequest.captureRequest == nullptr) {
4544 return;
4545 }
4546
4547 nextRequest.halRequest = camera3_capture_request_t();
4548 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004549 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004550
4551 // Wait for additional requests
4552 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4553
4554 for (size_t i = 1; i < batchSize; i++) {
4555 NextRequest additionalRequest;
4556 additionalRequest.captureRequest = waitForNextRequestLocked();
4557 if (additionalRequest.captureRequest == nullptr) {
4558 break;
4559 }
4560
4561 additionalRequest.halRequest = camera3_capture_request_t();
4562 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004563 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004564 }
4565
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004566 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004567 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004568 mNextRequests.size(), batchSize);
4569 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004570 }
4571
4572 return;
4573}
4574
4575sp<Camera3Device::CaptureRequest>
4576 Camera3Device::RequestThread::waitForNextRequestLocked() {
4577 status_t res;
4578 sp<CaptureRequest> nextRequest;
4579
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004580 while (mRequestQueue.empty()) {
4581 if (!mRepeatingRequests.empty()) {
4582 // Always atomically enqueue all requests in a repeating request
4583 // list. Guarantees a complete in-sequence set of captures to
4584 // application.
4585 const RequestList &requests = mRepeatingRequests;
4586 RequestList::const_iterator firstRequest =
4587 requests.begin();
4588 nextRequest = *firstRequest;
4589 mRequestQueue.insert(mRequestQueue.end(),
4590 ++firstRequest,
4591 requests.end());
4592 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004593
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004594 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004595
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004596 break;
4597 }
4598
4599 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4600
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004601 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4602 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004603 Mutex::Autolock pl(mPauseLock);
4604 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004605 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004606 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004607 // Let the tracker know
4608 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4609 if (statusTracker != 0) {
4610 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4611 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004612 }
4613 // Stop waiting for now and let thread management happen
4614 return NULL;
4615 }
4616 }
4617
4618 if (nextRequest == NULL) {
4619 // Don't have a repeating request already in hand, so queue
4620 // must have an entry now.
4621 RequestList::iterator firstRequest =
4622 mRequestQueue.begin();
4623 nextRequest = *firstRequest;
4624 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004625 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4626 sp<NotificationListener> listener = mListener.promote();
4627 if (listener != NULL) {
4628 listener->notifyRequestQueueEmpty();
4629 }
4630 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004631 }
4632
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004633 // In case we've been unpaused by setPaused clearing mDoPause, need to
4634 // update internal pause state (capture/setRepeatingRequest unpause
4635 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004636 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004637 if (mPaused) {
4638 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4639 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4640 if (statusTracker != 0) {
4641 statusTracker->markComponentActive(mStatusId);
4642 }
4643 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004644 mPaused = false;
4645
4646 // Check if we've reconfigured since last time, and reset the preview
4647 // request if so. Can't use 'NULL request == repeat' across configure calls.
4648 if (mReconfigured) {
4649 mPrevRequest.clear();
4650 mReconfigured = false;
4651 }
4652
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004653 if (nextRequest != NULL) {
4654 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004655 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4656 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004657
4658 // Since RequestThread::clear() removes buffers from the input stream,
4659 // get the right buffer here before unlocking mRequestLock
4660 if (nextRequest->mInputStream != NULL) {
4661 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4662 if (res != OK) {
4663 // Can't get input buffer from gralloc queue - this could be due to
4664 // disconnected queue or other producer misbehavior, so not a fatal
4665 // error
4666 ALOGE("%s: Can't get input buffer, skipping request:"
4667 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004668
4669 sp<NotificationListener> listener = mListener.promote();
4670 if (listener != NULL) {
4671 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004672 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004673 nextRequest->mResultExtras);
4674 }
4675 return NULL;
4676 }
4677 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004678 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004679
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004680 return nextRequest;
4681}
4682
4683bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004684 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004685 status_t res;
4686 Mutex::Autolock l(mPauseLock);
4687 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004688 if (mPaused == false) {
4689 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004690 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4691 // Let the tracker know
4692 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4693 if (statusTracker != 0) {
4694 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4695 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004696 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004697
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004698 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004699 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004700 return true;
4701 }
4702 }
4703 // We don't set mPaused to false here, because waitForNextRequest needs
4704 // to further manage the paused state in case of starvation.
4705 return false;
4706}
4707
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004708void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004709 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004710 // With work to do, mark thread as unpaused.
4711 // If paused by request (setPaused), don't resume, to avoid
4712 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004713 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004714 Mutex::Autolock p(mPauseLock);
4715 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004716 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4717 if (mPaused) {
4718 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4719 if (statusTracker != 0) {
4720 statusTracker->markComponentActive(mStatusId);
4721 }
4722 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004723 mPaused = false;
4724 }
4725}
4726
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004727void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4728 sp<Camera3Device> parent = mParent.promote();
4729 if (parent != NULL) {
4730 va_list args;
4731 va_start(args, fmt);
4732
4733 parent->setErrorStateV(fmt, args);
4734
4735 va_end(args);
4736 }
4737}
4738
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004739status_t Camera3Device::RequestThread::insertTriggers(
4740 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004741 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004742 Mutex::Autolock al(mTriggerMutex);
4743
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004744 sp<Camera3Device> parent = mParent.promote();
4745 if (parent == NULL) {
4746 CLOGE("RequestThread: Parent is gone");
4747 return DEAD_OBJECT;
4748 }
4749
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004750 CameraMetadata &metadata = request->mSettings;
4751 size_t count = mTriggerMap.size();
4752
4753 for (size_t i = 0; i < count; ++i) {
4754 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004755 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004756
4757 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4758 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4759 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004760 if (isAeTrigger) {
4761 request->mResultExtras.precaptureTriggerId = triggerId;
4762 mCurrentPreCaptureTriggerId = triggerId;
4763 } else {
4764 request->mResultExtras.afTriggerId = triggerId;
4765 mCurrentAfTriggerId = triggerId;
4766 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004767 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004768 }
4769
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004770 camera_metadata_entry entry = metadata.find(tag);
4771
4772 if (entry.count > 0) {
4773 /**
4774 * Already has an entry for this trigger in the request.
4775 * Rewrite it with our requested trigger value.
4776 */
4777 RequestTrigger oldTrigger = trigger;
4778
4779 oldTrigger.entryValue = entry.data.u8[0];
4780
4781 mTriggerReplacedMap.add(tag, oldTrigger);
4782 } else {
4783 /**
4784 * More typical, no trigger entry, so we just add it
4785 */
4786 mTriggerRemovedMap.add(tag, trigger);
4787 }
4788
4789 status_t res;
4790
4791 switch (trigger.getTagType()) {
4792 case TYPE_BYTE: {
4793 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4794 res = metadata.update(tag,
4795 &entryValue,
4796 /*count*/1);
4797 break;
4798 }
4799 case TYPE_INT32:
4800 res = metadata.update(tag,
4801 &trigger.entryValue,
4802 /*count*/1);
4803 break;
4804 default:
4805 ALOGE("%s: Type not supported: 0x%x",
4806 __FUNCTION__,
4807 trigger.getTagType());
4808 return INVALID_OPERATION;
4809 }
4810
4811 if (res != OK) {
4812 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4813 ", value %d", __FUNCTION__, trigger.getTagName(),
4814 trigger.entryValue);
4815 return res;
4816 }
4817
4818 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4819 trigger.getTagName(),
4820 trigger.entryValue);
4821 }
4822
4823 mTriggerMap.clear();
4824
4825 return count;
4826}
4827
4828status_t Camera3Device::RequestThread::removeTriggers(
4829 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004830 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004831 Mutex::Autolock al(mTriggerMutex);
4832
4833 CameraMetadata &metadata = request->mSettings;
4834
4835 /**
4836 * Replace all old entries with their old values.
4837 */
4838 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4839 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4840
4841 status_t res;
4842
4843 uint32_t tag = trigger.metadataTag;
4844 switch (trigger.getTagType()) {
4845 case TYPE_BYTE: {
4846 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4847 res = metadata.update(tag,
4848 &entryValue,
4849 /*count*/1);
4850 break;
4851 }
4852 case TYPE_INT32:
4853 res = metadata.update(tag,
4854 &trigger.entryValue,
4855 /*count*/1);
4856 break;
4857 default:
4858 ALOGE("%s: Type not supported: 0x%x",
4859 __FUNCTION__,
4860 trigger.getTagType());
4861 return INVALID_OPERATION;
4862 }
4863
4864 if (res != OK) {
4865 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4866 ", trigger value %d", __FUNCTION__,
4867 trigger.getTagName(), trigger.entryValue);
4868 return res;
4869 }
4870 }
4871 mTriggerReplacedMap.clear();
4872
4873 /**
4874 * Remove all new entries.
4875 */
4876 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4877 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4878 status_t res = metadata.erase(trigger.metadataTag);
4879
4880 if (res != OK) {
4881 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4882 ", trigger value %d", __FUNCTION__,
4883 trigger.getTagName(), trigger.entryValue);
4884 return res;
4885 }
4886 }
4887 mTriggerRemovedMap.clear();
4888
4889 return OK;
4890}
4891
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004892status_t Camera3Device::RequestThread::addDummyTriggerIds(
4893 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004894 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004895 static const int32_t dummyTriggerId = 1;
4896 status_t res;
4897
4898 CameraMetadata &metadata = request->mSettings;
4899
4900 // If AF trigger is active, insert a dummy AF trigger ID if none already
4901 // exists
4902 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4903 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4904 if (afTrigger.count > 0 &&
4905 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4906 afId.count == 0) {
4907 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4908 if (res != OK) return res;
4909 }
4910
4911 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4912 // if none already exists
4913 camera_metadata_entry pcTrigger =
4914 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4915 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4916 if (pcTrigger.count > 0 &&
4917 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4918 pcId.count == 0) {
4919 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4920 &dummyTriggerId, 1);
4921 if (res != OK) return res;
4922 }
4923
4924 return OK;
4925}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004926
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004927/**
4928 * PreparerThread inner class methods
4929 */
4930
4931Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004932 Thread(/*canCallJava*/false), mListener(nullptr),
4933 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004934}
4935
4936Camera3Device::PreparerThread::~PreparerThread() {
4937 Thread::requestExitAndWait();
4938 if (mCurrentStream != nullptr) {
4939 mCurrentStream->cancelPrepare();
4940 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4941 mCurrentStream.clear();
4942 }
4943 clear();
4944}
4945
Ruben Brunkc78ac262015-08-13 17:58:46 -07004946status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004947 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004948 status_t res;
4949
4950 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004951 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004952
Ruben Brunkc78ac262015-08-13 17:58:46 -07004953 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004954 if (res == OK) {
4955 // No preparation needed, fire listener right off
4956 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004957 if (listener != NULL) {
4958 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004959 }
4960 return OK;
4961 } else if (res != NOT_ENOUGH_DATA) {
4962 return res;
4963 }
4964
4965 // Need to prepare, start up thread if necessary
4966 if (!mActive) {
4967 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4968 // isn't running
4969 Thread::requestExitAndWait();
4970 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4971 if (res != OK) {
4972 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004973 if (listener != NULL) {
4974 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004975 }
4976 return res;
4977 }
4978 mCancelNow = false;
4979 mActive = true;
4980 ALOGV("%s: Preparer stream started", __FUNCTION__);
4981 }
4982
4983 // queue up the work
4984 mPendingStreams.push_back(stream);
4985 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4986
4987 return OK;
4988}
4989
4990status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004991 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004992 Mutex::Autolock l(mLock);
4993
4994 for (const auto& stream : mPendingStreams) {
4995 stream->cancelPrepare();
4996 }
4997 mPendingStreams.clear();
4998 mCancelNow = true;
4999
5000 return OK;
5001}
5002
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005003void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005004 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005005 Mutex::Autolock l(mLock);
5006 mListener = listener;
5007}
5008
5009bool Camera3Device::PreparerThread::threadLoop() {
5010 status_t res;
5011 {
5012 Mutex::Autolock l(mLock);
5013 if (mCurrentStream == nullptr) {
5014 // End thread if done with work
5015 if (mPendingStreams.empty()) {
5016 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5017 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5018 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5019 mActive = false;
5020 return false;
5021 }
5022
5023 // Get next stream to prepare
5024 auto it = mPendingStreams.begin();
5025 mCurrentStream = *it;
5026 mPendingStreams.erase(it);
5027 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5028 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5029 } else if (mCancelNow) {
5030 mCurrentStream->cancelPrepare();
5031 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5032 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5033 mCurrentStream.clear();
5034 mCancelNow = false;
5035 return true;
5036 }
5037 }
5038
5039 res = mCurrentStream->prepareNextBuffer();
5040 if (res == NOT_ENOUGH_DATA) return true;
5041 if (res != OK) {
5042 // Something bad happened; try to recover by cancelling prepare and
5043 // signalling listener anyway
5044 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5045 mCurrentStream->getId(), res, strerror(-res));
5046 mCurrentStream->cancelPrepare();
5047 }
5048
5049 // This stream has finished, notify listener
5050 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005051 sp<NotificationListener> listener = mListener.promote();
5052 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005053 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5054 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005055 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005056 }
5057
5058 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5059 mCurrentStream.clear();
5060
5061 return true;
5062}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005063
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005064/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005065 * Static callback forwarding methods from HAL to instance
5066 */
5067
5068void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5069 const camera3_capture_result *result) {
5070 Camera3Device *d =
5071 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005072
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005073 d->processCaptureResult(result);
5074}
5075
5076void Camera3Device::sNotify(const camera3_callback_ops *cb,
5077 const camera3_notify_msg *msg) {
5078 Camera3Device *d =
5079 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5080 d->notify(msg);
5081}
5082
5083}; // namespace android