blob: d99fc1de1c23e957eb264960a8a7cd95f46e2989 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
Emilian Peev5fbe0ba2017-10-20 15:45:45 +010058#include <android/hardware/camera/device/3.4/ICameraDeviceSession.h>
59
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
80 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080081{
82 ATRACE_CALL();
83 camera3_callback_ops::notify = &sNotify;
84 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092 disconnect();
93}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
123 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Yifan Hongf79b5542017-04-11 14:44:25 -0700128 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700129 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
130 [&queue](const auto& descriptor) {
131 queue = std::make_shared<RequestMetadataQueue>(descriptor);
132 if (!queue->isValid() || queue->availableToWrite() <= 0) {
133 ALOGE("HAL returns empty request metadata fmq, not use it");
134 queue = nullptr;
135 // don't use the queue onwards.
136 }
137 });
138 if (!requestQueueRet.isOk()) {
139 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
140 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700141 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700143
144 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700145 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700146 [&resQueue](const auto& descriptor) {
147 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
148 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700149 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700150 resQueue = nullptr;
151 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700152 }
153 });
154 if (!resultQueueRet.isOk()) {
155 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
156 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700157 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700158 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700159 IF_ALOGV() {
160 session->interfaceChain([](
161 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
162 ALOGV("Session interface chain:");
163 for (auto iface : interfaceChain) {
164 ALOGV(" %s", iface.c_str());
165 }
166 });
167 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700168
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700169 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000170 std::string providerType;
171 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172
173 return initializeCommonLocked();
174}
175
176status_t Camera3Device::initializeCommonLocked() {
177
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700178 /** Start up status tracker thread */
179 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800180 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700181 if (res != OK) {
182 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
183 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800184 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700185 mStatusTracker.clear();
186 return res;
187 }
188
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700189 /** Register in-flight map to the status tracker */
190 mInFlightStatusId = mStatusTracker->addComponent();
191
Zhijun He125684a2015-12-26 15:07:30 -0800192 /** Create buffer manager */
193 mBufferManager = new Camera3BufferManager();
194
Emilian Peev71c73a22017-03-21 16:35:51 +0000195 mTagMonitor.initialize(mVendorTagId);
196
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700197 /** Start up request queue thread */
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700198 mRequestThread = new RequestThread(this, mStatusTracker, mInterface);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800199 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800200 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700201 SET_ERR_L("Unable to start request queue thread: %s (%d)",
202 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800203 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800204 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800205 return res;
206 }
207
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700208 mPreparerThread = new PreparerThread();
209
Ruben Brunk183f0562015-08-12 12:55:02 -0700210 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800211 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700212 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700213 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700214 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800215
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800216 // Measure the clock domain offset between camera and video/hw_composer
217 camera_metadata_entry timestampSource =
218 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
219 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
220 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
221 mTimestampOffset = getMonoToBoottimeOffset();
222 }
223
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700224 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100225 camera_metadata_entry partialResultsCount =
226 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
227 if (partialResultsCount.count > 0) {
228 mNumPartialResults = partialResultsCount.data.i32[0];
229 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700230 }
231
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700232 camera_metadata_entry configs =
233 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
234 for (uint32_t i = 0; i < configs.count; i += 4) {
235 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
236 configs.data.i32[i + 3] ==
237 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
238 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
239 configs.data.i32[i + 2]));
240 }
241 }
242
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800243 return OK;
244}
245
246status_t Camera3Device::disconnect() {
247 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700248 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800249
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700250 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800251
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700253 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700254 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700255 {
256 Mutex::Autolock l(mLock);
257 if (mStatus == STATUS_UNINITIALIZED) return res;
258
259 if (mStatus == STATUS_ACTIVE ||
260 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
261 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700262 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700264 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700266 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700268 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
269 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270 // Continue to close device even in case of error
271 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700272 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800273 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800274
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 if (mStatus == STATUS_ERROR) {
276 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
279 if (mStatusTracker != NULL) {
280 mStatusTracker->requestExit();
281 }
282
283 if (mRequestThread != NULL) {
284 mRequestThread->requestExit();
285 }
286
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700287 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
288 for (size_t i = 0; i < mOutputStreams.size(); i++) {
289 streams.push_back(mOutputStreams[i]);
290 }
291 if (mInputStream != nullptr) {
292 streams.push_back(mInputStream);
293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 }
295
296 // Joining done without holding mLock, otherwise deadlocks may ensue
297 // as the threads try to access parent state
298 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
299 // HAL may be in a bad state, so waiting for request thread
300 // (which may be stuck in the HAL processCaptureRequest call)
301 // could be dangerous.
302 mRequestThread->join();
303 }
304
305 if (mStatusTracker != NULL) {
306 mStatusTracker->join();
307 }
308
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800309 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310 {
311 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700313 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800314 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800316
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700317 // Call close without internal mutex held, as the HAL close may need to
318 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800319 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700320
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700321 flushInflightRequests();
322
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700323 {
324 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800325 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700326 mOutputStreams.clear();
327 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700328 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700330 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800332
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700333 for (auto& weakStream : streams) {
334 sp<Camera3StreamInterface> stream = weakStream.promote();
335 if (stream != nullptr) {
336 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
337 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
338 }
339 }
340
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343}
344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345// For dumping/debugging only -
346// try to acquire a lock a few times, eventually give up to proceed with
347// debug/dump operations
348bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
349 bool gotLock = false;
350 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
351 if (lock.tryLock() == NO_ERROR) {
352 gotLock = true;
353 break;
354 } else {
355 usleep(kDumpSleepDuration);
356 }
357 }
358 return gotLock;
359}
360
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700361Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
362 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100363 const int STREAM_CONFIGURATION_SIZE = 4;
364 const int STREAM_FORMAT_OFFSET = 0;
365 const int STREAM_WIDTH_OFFSET = 1;
366 const int STREAM_HEIGHT_OFFSET = 2;
367 const int STREAM_IS_INPUT_OFFSET = 3;
368 camera_metadata_ro_entry_t availableStreamConfigs =
369 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
370 if (availableStreamConfigs.count == 0 ||
371 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
372 return Size(0, 0);
373 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700374
Emilian Peev08dd2452017-04-06 16:55:14 +0100375 // Get max jpeg size (area-wise).
376 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
377 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
378 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
379 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
380 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
381 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
382 && format == HAL_PIXEL_FORMAT_BLOB &&
383 (width * height > maxJpegWidth * maxJpegHeight)) {
384 maxJpegWidth = width;
385 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700386 }
387 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100388
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700389 return Size(maxJpegWidth, maxJpegHeight);
390}
391
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800392nsecs_t Camera3Device::getMonoToBoottimeOffset() {
393 // try three times to get the clock offset, choose the one
394 // with the minimum gap in measurements.
395 const int tries = 3;
396 nsecs_t bestGap, measured;
397 for (int i = 0; i < tries; ++i) {
398 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
399 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
400 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
401 const nsecs_t gap = tmono2 - tmono;
402 if (i == 0 || gap < bestGap) {
403 bestGap = gap;
404 measured = tbase - ((tmono + tmono2) >> 1);
405 }
406 }
407 return measured;
408}
409
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800410hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
411 int frameworkFormat) {
412 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
413}
414
415DataspaceFlags Camera3Device::mapToHidlDataspace(
416 android_dataspace dataSpace) {
417 return dataSpace;
418}
419
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700420BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100421 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700422 return usage;
423}
424
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800425StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
426 switch (rotation) {
427 case CAMERA3_STREAM_ROTATION_0:
428 return StreamRotation::ROTATION_0;
429 case CAMERA3_STREAM_ROTATION_90:
430 return StreamRotation::ROTATION_90;
431 case CAMERA3_STREAM_ROTATION_180:
432 return StreamRotation::ROTATION_180;
433 case CAMERA3_STREAM_ROTATION_270:
434 return StreamRotation::ROTATION_270;
435 }
436 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
437 return StreamRotation::ROTATION_0;
438}
439
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800440status_t Camera3Device::mapToStreamConfigurationMode(
441 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
442 if (mode == nullptr) return BAD_VALUE;
443 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
444 switch(operationMode) {
445 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
446 *mode = StreamConfigurationMode::NORMAL_MODE;
447 break;
448 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
449 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
450 break;
451 default:
452 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
453 return BAD_VALUE;
454 }
455 } else {
456 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800457 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800458 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800459}
460
461camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
462 switch (status) {
463 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
464 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
465 }
466 return CAMERA3_BUFFER_STATUS_ERROR;
467}
468
469int Camera3Device::mapToFrameworkFormat(
470 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
471 return static_cast<uint32_t>(pixelFormat);
472}
473
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700474android_dataspace Camera3Device::mapToFrameworkDataspace(
475 DataspaceFlags dataSpace) {
476 return static_cast<android_dataspace>(dataSpace);
477}
478
Emilian Peev050f5dc2017-05-18 14:43:56 +0100479uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700480 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700481 return usage;
482}
483
Emilian Peev050f5dc2017-05-18 14:43:56 +0100484uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700485 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700486 return usage;
487}
488
Zhijun Hef7da0962014-04-24 13:27:56 -0700489ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700490 // Get max jpeg size (area-wise).
491 Size maxJpegResolution = getMaxJpegResolution();
492 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800493 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
494 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700495 return BAD_VALUE;
496 }
497
Zhijun Hef7da0962014-04-24 13:27:56 -0700498 // Get max jpeg buffer size
499 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700500 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
501 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
503 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700504 return BAD_VALUE;
505 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700506 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800507 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700508
509 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700510 float scaleFactor = ((float) (width * height)) /
511 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800512 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
513 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700514 if (jpegBufferSize > maxJpegBufferSize) {
515 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700516 }
517
518 return jpegBufferSize;
519}
520
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700521ssize_t Camera3Device::getPointCloudBufferSize() const {
522 const int FLOATS_PER_POINT=4;
523 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
524 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800525 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
526 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700527 return BAD_VALUE;
528 }
529 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
530 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
531 return maxBytesForPointCloud;
532}
533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800534ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800535 const int PER_CONFIGURATION_SIZE = 3;
536 const int WIDTH_OFFSET = 0;
537 const int HEIGHT_OFFSET = 1;
538 const int SIZE_OFFSET = 2;
539 camera_metadata_ro_entry rawOpaqueSizes =
540 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800541 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800542 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800543 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
544 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800545 return BAD_VALUE;
546 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700547
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800548 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
549 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
550 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
551 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
552 }
553 }
554
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
556 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800557 return BAD_VALUE;
558}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700559
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800560status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
561 ATRACE_CALL();
562 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700563
564 // Try to lock, but continue in case of failure (to avoid blocking in
565 // deadlocks)
566 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
567 bool gotLock = tryLockSpinRightRound(mLock);
568
569 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800570 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
571 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700572 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800573 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
574 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700575
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800576 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700577
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800578 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700579 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800580 int n = args.size();
581 for (int i = 0; i < n; i++) {
582 if (args[i] == templatesOption) {
583 dumpTemplates = true;
584 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700585 if (args[i] == monitorOption) {
586 if (i + 1 < n) {
587 String8 monitorTags = String8(args[i + 1]);
588 if (monitorTags == "off") {
589 mTagMonitor.disableMonitoring();
590 } else {
591 mTagMonitor.parseTagsToMonitor(monitorTags);
592 }
593 } else {
594 mTagMonitor.disableMonitoring();
595 }
596 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800597 }
598
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800599 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800600
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800601 const char *status =
602 mStatus == STATUS_ERROR ? "ERROR" :
603 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700604 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
605 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800606 mStatus == STATUS_ACTIVE ? "ACTIVE" :
607 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700608
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800609 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700610 if (mStatus == STATUS_ERROR) {
611 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
612 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800613 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800614 const char *mode =
615 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
616 mOperatingMode == static_cast<int>(
617 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
618 "CUSTOM";
619 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800620
621 if (mInputStream != NULL) {
622 write(fd, lines.string(), lines.size());
623 mInputStream->dump(fd, args);
624 } else {
625 lines.appendFormat(" No input stream.\n");
626 write(fd, lines.string(), lines.size());
627 }
628 for (size_t i = 0; i < mOutputStreams.size(); i++) {
629 mOutputStreams[i]->dump(fd,args);
630 }
631
Zhijun He431503c2016-03-07 17:30:16 -0800632 if (mBufferManager != NULL) {
633 lines = String8(" Camera3 Buffer Manager:\n");
634 write(fd, lines.string(), lines.size());
635 mBufferManager->dump(fd, args);
636 }
Zhijun He125684a2015-12-26 15:07:30 -0800637
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700638 lines = String8(" In-flight requests:\n");
639 if (mInFlightMap.size() == 0) {
640 lines.append(" None\n");
641 } else {
642 for (size_t i = 0; i < mInFlightMap.size(); i++) {
643 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700644 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700645 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800646 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700647 r.numBuffersLeft);
648 }
649 }
650 write(fd, lines.string(), lines.size());
651
Shuzhen Wang686f6442017-06-20 16:16:04 -0700652 if (mRequestThread != NULL) {
653 mRequestThread->dumpCaptureRequestLatency(fd,
654 " ProcessCaptureRequest latency histogram:");
655 }
656
Igor Murashkin1e479c02013-09-06 16:55:14 -0700657 {
658 lines = String8(" Last request sent:\n");
659 write(fd, lines.string(), lines.size());
660
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700661 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700662 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
663 }
664
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800665 if (dumpTemplates) {
666 const char *templateNames[] = {
667 "TEMPLATE_PREVIEW",
668 "TEMPLATE_STILL_CAPTURE",
669 "TEMPLATE_VIDEO_RECORD",
670 "TEMPLATE_VIDEO_SNAPSHOT",
671 "TEMPLATE_ZERO_SHUTTER_LAG",
672 "TEMPLATE_MANUAL"
673 };
674
675 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800676 camera_metadata_t *templateRequest = nullptr;
677 mInterface->constructDefaultRequestSettings(
678 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800679 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800680 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800681 lines.append(" Not supported\n");
682 write(fd, lines.string(), lines.size());
683 } else {
684 write(fd, lines.string(), lines.size());
685 dump_indented_camera_metadata(templateRequest,
686 fd, /*verbosity*/2, /*indentation*/8);
687 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800688 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800689 }
690 }
691
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700692 mTagMonitor.dumpMonitoredMetadata(fd);
693
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800694 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800695 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800697 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800698 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800699
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700700 if (gotLock) mLock.unlock();
701 if (gotInterfaceLock) mInterfaceLock.unlock();
702
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800703 return OK;
704}
705
706const CameraMetadata& Camera3Device::info() const {
707 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800708 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
709 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700710 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800711 mStatus == STATUS_ERROR ?
712 "when in error state" : "before init");
713 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800714 return mDeviceInfo;
715}
716
Jianing Wei90e59c92014-03-12 18:29:36 -0700717status_t Camera3Device::checkStatusOkToCaptureLocked() {
718 switch (mStatus) {
719 case STATUS_ERROR:
720 CLOGE("Device has encountered a serious error");
721 return INVALID_OPERATION;
722 case STATUS_UNINITIALIZED:
723 CLOGE("Device not initialized");
724 return INVALID_OPERATION;
725 case STATUS_UNCONFIGURED:
726 case STATUS_CONFIGURED:
727 case STATUS_ACTIVE:
728 // OK
729 break;
730 default:
731 SET_ERR_L("Unexpected status: %d", mStatus);
732 return INVALID_OPERATION;
733 }
734 return OK;
735}
736
737status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700738 const List<const CameraMetadata> &metadataList,
739 const std::list<const SurfaceMap> &surfaceMaps,
740 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700741 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 if (requestList == NULL) {
743 CLOGE("requestList cannot be NULL.");
744 return BAD_VALUE;
745 }
746
Jianing Weicb0652e2014-03-12 18:29:36 -0700747 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700748 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
749 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
750 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
751 ++metadataIt, ++surfaceMapIt) {
752 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700753 if (newRequest == 0) {
754 CLOGE("Can't create capture request");
755 return BAD_VALUE;
756 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700757
Shuzhen Wang9d066012016-09-30 11:30:20 -0700758 newRequest->mRepeating = repeating;
759
Jianing Weicb0652e2014-03-12 18:29:36 -0700760 // Setup burst Id and request Id
761 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700762 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
763 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700764 CLOGE("RequestID entry exists; but must not be empty in metadata");
765 return BAD_VALUE;
766 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700767 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700768 } else {
769 CLOGE("RequestID does not exist in metadata");
770 return BAD_VALUE;
771 }
772
Jianing Wei90e59c92014-03-12 18:29:36 -0700773 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700774
775 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700776 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
778 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
779 return BAD_VALUE;
780 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700781
782 // Setup batch size if this is a high speed video recording request.
783 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
784 auto firstRequest = requestList->begin();
785 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
786 if (outputStream->isVideoStream()) {
787 (*firstRequest)->mBatchSize = requestList->size();
788 break;
789 }
790 }
791 }
792
Jianing Wei90e59c92014-03-12 18:29:36 -0700793 return OK;
794}
795
Jianing Weicb0652e2014-03-12 18:29:36 -0700796status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800797 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800798
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700799 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700800 std::list<const SurfaceMap> surfaceMaps;
801 convertToRequestList(requests, surfaceMaps, request);
802
803 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
804}
805
806void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
807 std::list<const SurfaceMap>& surfaceMaps,
808 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700809 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700810
811 SurfaceMap surfaceMap;
812 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
813 // With no surface list passed in, stream and surface will have 1-to-1
814 // mapping. So the surface index is 0 for each stream in the surfaceMap.
815 for (size_t i = 0; i < streams.count; i++) {
816 surfaceMap[streams.data.i32[i]].push_back(0);
817 }
818 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800819}
820
Jianing Wei90e59c92014-03-12 18:29:36 -0700821status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 const List<const CameraMetadata> &requests,
823 const std::list<const SurfaceMap> &surfaceMaps,
824 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700825 /*out*/
826 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 ATRACE_CALL();
828 Mutex::Autolock il(mInterfaceLock);
829 Mutex::Autolock l(mLock);
830
831 status_t res = checkStatusOkToCaptureLocked();
832 if (res != OK) {
833 // error logged by previous call
834 return res;
835 }
836
837 RequestList requestList;
838
Shuzhen Wang0129d522016-10-30 22:43:41 -0700839 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
840 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 if (res != OK) {
842 // error logged by previous call
843 return res;
844 }
845
846 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700847 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700849 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850 }
851
852 if (res == OK) {
853 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
854 if (res != OK) {
855 SET_ERR_L("Can't transition to active in %f seconds!",
856 kActiveTimeout/1e9);
857 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800858 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700859 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700860 } else {
861 CLOGE("Cannot queue request. Impossible.");
862 return BAD_VALUE;
863 }
864
865 return res;
866}
867
Yifan Honga640c5a2017-04-12 16:30:31 -0700868// Only one processCaptureResult should be called at a time, so
869// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800870hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800871 const hardware::hidl_vec<
872 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700873 // Ideally we should grab mLock, but that can lead to deadlock, and
874 // it's not super important to get up to date value of mStatus for this
875 // warning print, hence skipping the lock here
876 if (mStatus == STATUS_ERROR) {
877 // Per API contract, HAL should act as closed after device error
878 // But mStatus can be set to error by framework as well, so just log
879 // a warning here.
880 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700881 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700882
883 if (mProcessCaptureResultLock.tryLock() != OK) {
884 // This should never happen; it indicates a wrong client implementation
885 // that doesn't follow the contract. But, we can be tolerant here.
886 ALOGE("%s: callback overlapped! waiting 1s...",
887 __FUNCTION__);
888 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
889 ALOGE("%s: cannot acquire lock in 1s, dropping results",
890 __FUNCTION__);
891 // really don't know what to do, so bail out.
892 return hardware::Void();
893 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800894 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700895 for (const auto& result : results) {
896 processOneCaptureResultLocked(result);
897 }
898 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800899 return hardware::Void();
900}
901
Yifan Honga640c5a2017-04-12 16:30:31 -0700902void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800903 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800904 camera3_capture_result r;
905 status_t res;
906 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700907
908 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
909 if (result.fmqResultSize > 0) {
910 resultMetadata.resize(result.fmqResultSize);
911 if (mResultMetadataQueue == nullptr) {
912 return; // logged in initialize()
913 }
914 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
915 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
916 __FUNCTION__, result.frameNumber, result.fmqResultSize);
917 return;
918 }
919 } else {
920 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
921 result.result.size());
922 }
923
924 if (resultMetadata.size() != 0) {
925 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
926 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800927 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
928 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
929 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800930 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800931 }
932 } else {
933 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800934 }
935
936 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
937 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
938 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
939 auto& bDst = outputBuffers[i];
940 const StreamBuffer &bSrc = result.outputBuffers[i];
941
942 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100943 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800944 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
945 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800946 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800947 }
948 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
949
950 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800951 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 if (res != OK) {
953 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
954 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800955 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800956 }
957 bDst.buffer = buffer;
958 bDst.status = mapHidlBufferStatus(bSrc.status);
959 bDst.acquire_fence = -1;
960 if (bSrc.releaseFence == nullptr) {
961 bDst.release_fence = -1;
962 } else if (bSrc.releaseFence->numFds == 1) {
963 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
964 } else {
965 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
966 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800967 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800968 }
969 }
970 r.num_output_buffers = outputBuffers.size();
971 r.output_buffers = outputBuffers.data();
972
973 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800974 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800975 r.input_buffer = nullptr;
976 } else {
977 if (mInputStream->getId() != result.inputBuffer.streamId) {
978 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
979 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800980 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 }
982 inputBuffer.stream = mInputStream->asHalStream();
983 buffer_handle_t *buffer;
984 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
985 &buffer);
986 if (res != OK) {
987 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
988 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800989 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 }
991 inputBuffer.buffer = buffer;
992 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
993 inputBuffer.acquire_fence = -1;
994 if (result.inputBuffer.releaseFence == nullptr) {
995 inputBuffer.release_fence = -1;
996 } else if (result.inputBuffer.releaseFence->numFds == 1) {
997 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
998 } else {
999 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1000 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001001 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001002 }
1003 r.input_buffer = &inputBuffer;
1004 }
1005
1006 r.partial_result = result.partialResult;
1007
1008 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001009}
1010
1011hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001012 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001013 // Ideally we should grab mLock, but that can lead to deadlock, and
1014 // it's not super important to get up to date value of mStatus for this
1015 // warning print, hence skipping the lock here
1016 if (mStatus == STATUS_ERROR) {
1017 // Per API contract, HAL should act as closed after device error
1018 // But mStatus can be set to error by framework as well, so just log
1019 // a warning here.
1020 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001021 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001022
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001023 for (const auto& msg : msgs) {
1024 notify(msg);
1025 }
1026 return hardware::Void();
1027}
1028
1029void Camera3Device::notify(
1030 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1031
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001032 camera3_notify_msg m;
1033 switch (msg.type) {
1034 case MsgType::ERROR:
1035 m.type = CAMERA3_MSG_ERROR;
1036 m.message.error.frame_number = msg.msg.error.frameNumber;
1037 if (msg.msg.error.errorStreamId >= 0) {
1038 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001039 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001040 ALOGE("%s: Frame %d: Invalid error stream id %d",
1041 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001042 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001043 }
1044 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1045 } else {
1046 m.message.error.error_stream = nullptr;
1047 }
1048 switch (msg.msg.error.errorCode) {
1049 case ErrorCode::ERROR_DEVICE:
1050 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1051 break;
1052 case ErrorCode::ERROR_REQUEST:
1053 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1054 break;
1055 case ErrorCode::ERROR_RESULT:
1056 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1057 break;
1058 case ErrorCode::ERROR_BUFFER:
1059 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1060 break;
1061 }
1062 break;
1063 case MsgType::SHUTTER:
1064 m.type = CAMERA3_MSG_SHUTTER;
1065 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1066 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1067 break;
1068 }
1069 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001070}
1071
Jianing Weicb0652e2014-03-12 18:29:36 -07001072status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001073 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001074 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001075 ATRACE_CALL();
1076
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001078}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001079
Jianing Weicb0652e2014-03-12 18:29:36 -07001080status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1081 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001082 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001083
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001084 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001085 std::list<const SurfaceMap> surfaceMaps;
1086 convertToRequestList(requests, surfaceMaps, request);
1087
1088 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1089 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090}
1091
Jianing Weicb0652e2014-03-12 18:29:36 -07001092status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001093 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001094 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001095 ATRACE_CALL();
1096
Shuzhen Wang0129d522016-10-30 22:43:41 -07001097 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001098}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001099
1100sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001101 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001102 status_t res;
1103
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001104 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001105 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1106 // so unilaterally select normal operating mode.
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001107 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE, mSessionParams);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001108 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001109 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001110 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001111 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001112 } else if (mStatus == STATUS_UNCONFIGURED) {
1113 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001114 CLOGE("No streams configured");
1115 return NULL;
1116 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 }
1118
Shuzhen Wang0129d522016-10-30 22:43:41 -07001119 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001120 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001121}
1122
Jianing Weicb0652e2014-03-12 18:29:36 -07001123status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001124 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001125 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001127
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128 switch (mStatus) {
1129 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001130 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001131 return INVALID_OPERATION;
1132 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001133 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001134 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 case STATUS_UNCONFIGURED:
1136 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 case STATUS_ACTIVE:
1138 // OK
1139 break;
1140 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001141 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001142 return INVALID_OPERATION;
1143 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001144 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001145
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001146 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001147}
1148
1149status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1150 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001151 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001152
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001153 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001154}
1155
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001156status_t Camera3Device::createInputStream(
1157 uint32_t width, uint32_t height, int format, int *id) {
1158 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001159 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001160 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001161 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001162 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1163 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001164
1165 status_t res;
1166 bool wasActive = false;
1167
1168 switch (mStatus) {
1169 case STATUS_ERROR:
1170 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1171 return INVALID_OPERATION;
1172 case STATUS_UNINITIALIZED:
1173 ALOGE("%s: Device not initialized", __FUNCTION__);
1174 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001175 case STATUS_UNCONFIGURED:
1176 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001177 // OK
1178 break;
1179 case STATUS_ACTIVE:
1180 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001181 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001182 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001183 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001184 return res;
1185 }
1186 wasActive = true;
1187 break;
1188 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001190 return INVALID_OPERATION;
1191 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001192 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001193
1194 if (mInputStream != 0) {
1195 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1196 return INVALID_OPERATION;
1197 }
1198
1199 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1200 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001201 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001202
1203 mInputStream = newStream;
1204
1205 *id = mNextStreamId++;
1206
1207 // Continue captures if active at start
1208 if (wasActive) {
1209 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001210 // Reuse current operating mode and session parameters for new stream config
1211 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001212 if (res != OK) {
1213 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1214 __FUNCTION__, mNextStreamId, strerror(-res), res);
1215 return res;
1216 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001218 }
1219
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001220 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001221 return OK;
1222}
1223
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001224status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001225 uint32_t width, uint32_t height, int format,
1226 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001227 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 ATRACE_CALL();
1229
1230 if (consumer == nullptr) {
1231 ALOGE("%s: consumer must not be null", __FUNCTION__);
1232 return BAD_VALUE;
1233 }
1234
1235 std::vector<sp<Surface>> consumers;
1236 consumers.push_back(consumer);
1237
1238 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Emilian Peev40ead602017-09-26 15:46:36 +01001239 format, dataSpace, rotation, id, surfaceIds, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001240}
1241
1242status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1243 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1244 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev40ead602017-09-26 15:46:36 +01001245 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001247
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001248 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001249 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001251 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Emilian Peev050f5dc2017-05-18 14:43:56 +01001252 " consumer usage %" PRIu64 ", isShared %d", mId.string(), mNextStreamId, width, height, format,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001253 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 status_t res;
1256 bool wasActive = false;
1257
1258 switch (mStatus) {
1259 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
1262 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001263 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001265 case STATUS_UNCONFIGURED:
1266 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 // OK
1268 break;
1269 case STATUS_ACTIVE:
1270 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001271 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001273 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return res;
1275 }
1276 wasActive = true;
1277 break;
1278 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001279 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 return INVALID_OPERATION;
1281 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283
1284 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001285
Shuzhen Wang0129d522016-10-30 22:43:41 -07001286 if (consumers.size() == 0 && !hasDeferredConsumer) {
1287 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1288 return BAD_VALUE;
1289 }
Zhijun He5d677d12016-05-29 16:52:39 -07001290
Shuzhen Wang0129d522016-10-30 22:43:41 -07001291 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001292 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1293 return BAD_VALUE;
1294 }
1295
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001297 ssize_t blobBufferSize;
1298 if (dataSpace != HAL_DATASPACE_DEPTH) {
1299 blobBufferSize = getJpegBufferSize(width, height);
1300 if (blobBufferSize <= 0) {
1301 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1302 return BAD_VALUE;
1303 }
1304 } else {
1305 blobBufferSize = getPointCloudBufferSize();
1306 if (blobBufferSize <= 0) {
1307 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1308 return BAD_VALUE;
1309 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001310 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001311 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001312 width, height, blobBufferSize, format, dataSpace, rotation,
1313 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001314 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1315 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1316 if (rawOpaqueBufferSize <= 0) {
1317 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1318 return BAD_VALUE;
1319 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001320 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001321 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1322 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001323 } else if (isShared) {
1324 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1325 width, height, format, consumerUsage, dataSpace, rotation,
1326 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001327 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001328 newStream = new Camera3OutputStream(mNextStreamId,
1329 width, height, format, consumerUsage, dataSpace, rotation,
1330 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001332 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001333 width, height, format, dataSpace, rotation,
1334 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 }
Emilian Peev40ead602017-09-26 15:46:36 +01001336
1337 size_t consumerCount = consumers.size();
1338 for (size_t i = 0; i < consumerCount; i++) {
1339 int id = newStream->getSurfaceId(consumers[i]);
1340 if (id < 0) {
1341 SET_ERR_L("Invalid surface id");
1342 return BAD_VALUE;
1343 }
1344 if (surfaceIds != nullptr) {
1345 surfaceIds->push_back(id);
1346 }
1347 }
1348
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001349 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350
Emilian Peev08dd2452017-04-06 16:55:14 +01001351 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001352
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 res = mOutputStreams.add(mNextStreamId, newStream);
1354 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return res;
1357 }
1358
1359 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001360 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361
1362 // Continue captures if active at start
1363 if (wasActive) {
1364 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001365 // Reuse current operating mode and session parameters for new stream config
1366 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001368 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1369 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return res;
1371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001372 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001374 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001376}
1377
Emilian Peev710c1422017-08-30 11:19:38 +01001378status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001379 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001380 if (nullptr == streamInfo) {
1381 return BAD_VALUE;
1382 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001383 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 switch (mStatus) {
1387 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001388 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return INVALID_OPERATION;
1390 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 case STATUS_UNCONFIGURED:
1394 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 case STATUS_ACTIVE:
1396 // OK
1397 break;
1398 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return INVALID_OPERATION;
1401 }
1402
1403 ssize_t idx = mOutputStreams.indexOfKey(id);
1404 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001405 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return idx;
1407 }
1408
Emilian Peev710c1422017-08-30 11:19:38 +01001409 streamInfo->width = mOutputStreams[idx]->getWidth();
1410 streamInfo->height = mOutputStreams[idx]->getHeight();
1411 streamInfo->format = mOutputStreams[idx]->getFormat();
1412 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1413 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1414 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001415 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1416 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001417 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001418}
1419
1420status_t Camera3Device::setStreamTransform(int id,
1421 int transform) {
1422 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001423 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001425
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 switch (mStatus) {
1427 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001428 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 return INVALID_OPERATION;
1430 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001431 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001433 case STATUS_UNCONFIGURED:
1434 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 case STATUS_ACTIVE:
1436 // OK
1437 break;
1438 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001439 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440 return INVALID_OPERATION;
1441 }
1442
1443 ssize_t idx = mOutputStreams.indexOfKey(id);
1444 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 CLOGE("Stream %d does not exist",
1446 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 return BAD_VALUE;
1448 }
1449
1450 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001451}
1452
1453status_t Camera3Device::deleteStream(int id) {
1454 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001455 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 Mutex::Autolock l(mLock);
1457 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001458
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001459 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001460
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 // CameraDevice semantics require device to already be idle before
1462 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001463 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001464 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001465 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 }
1467
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001468 if (mStatus == STATUS_ERROR) {
1469 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1470 __FUNCTION__, mId.string());
1471 return -EBUSY;
1472 }
1473
Igor Murashkin2fba5842013-04-22 14:03:54 -07001474 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001475 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 if (mInputStream != NULL && id == mInputStream->getId()) {
1477 deletedStream = mInputStream;
1478 mInputStream.clear();
1479 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001480 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001481 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 return BAD_VALUE;
1483 }
Zhijun He5f446352014-01-22 09:49:33 -08001484 }
1485
1486 // Delete output stream or the output part of a bi-directional stream.
1487 if (outputStreamIdx != NAME_NOT_FOUND) {
1488 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 mOutputStreams.removeItem(id);
1490 }
1491
1492 // Free up the stream endpoint so that it can be used by some other stream
1493 res = deletedStream->disconnect();
1494 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 // fall through since we want to still list the stream as deleted.
1497 }
1498 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001499 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500
1501 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001502}
1503
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001504status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001505 ATRACE_CALL();
1506 ALOGV("%s: E", __FUNCTION__);
1507
1508 Mutex::Autolock il(mInterfaceLock);
1509 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001510
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001511 //Filter out any incoming session parameters
1512 const CameraMetadata params(sessionParams);
1513 CameraMetadata filteredParams;
1514 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1515 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
1516 if (availableSessionKeys.count > 0) {
1517 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1518 camera_metadata_ro_entry entry = params.find(
1519 availableSessionKeys.data.i32[i]);
1520 if (entry.count > 0) {
1521 filteredParams.update(entry);
1522 }
1523 }
1524 }
1525
1526 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001527}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001528
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001529status_t Camera3Device::getInputBufferProducer(
1530 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001531 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001532 Mutex::Autolock il(mInterfaceLock);
1533 Mutex::Autolock l(mLock);
1534
1535 if (producer == NULL) {
1536 return BAD_VALUE;
1537 } else if (mInputStream == NULL) {
1538 return INVALID_OPERATION;
1539 }
1540
1541 return mInputStream->getInputBufferProducer(producer);
1542}
1543
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544status_t Camera3Device::createDefaultRequest(int templateId,
1545 CameraMetadata *request) {
1546 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001547 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001548
1549 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1550 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1551 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1552 return BAD_VALUE;
1553 }
1554
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001557 {
1558 Mutex::Autolock l(mLock);
1559 switch (mStatus) {
1560 case STATUS_ERROR:
1561 CLOGE("Device has encountered a serious error");
1562 return INVALID_OPERATION;
1563 case STATUS_UNINITIALIZED:
1564 CLOGE("Device is not initialized!");
1565 return INVALID_OPERATION;
1566 case STATUS_UNCONFIGURED:
1567 case STATUS_CONFIGURED:
1568 case STATUS_ACTIVE:
1569 // OK
1570 break;
1571 default:
1572 SET_ERR_L("Unexpected status: %d", mStatus);
1573 return INVALID_OPERATION;
1574 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001575
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001576 if (!mRequestTemplateCache[templateId].isEmpty()) {
1577 *request = mRequestTemplateCache[templateId];
1578 return OK;
1579 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001580 }
1581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001582 camera_metadata_t *rawRequest;
1583 status_t res = mInterface->constructDefaultRequestSettings(
1584 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001585
1586 {
1587 Mutex::Autolock l(mLock);
1588 if (res == BAD_VALUE) {
1589 ALOGI("%s: template %d is not supported on this camera device",
1590 __FUNCTION__, templateId);
1591 return res;
1592 } else if (res != OK) {
1593 CLOGE("Unable to construct request template %d: %s (%d)",
1594 templateId, strerror(-res), res);
1595 return res;
1596 }
1597
1598 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1599 mRequestTemplateCache[templateId].acquire(rawRequest);
1600
1601 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001602 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603 return OK;
1604}
1605
1606status_t Camera3Device::waitUntilDrained() {
1607 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001609 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001611
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001612 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001613}
1614
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001615status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 switch (mStatus) {
1617 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001618 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001619 ALOGV("%s: Already idle", __FUNCTION__);
1620 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 case STATUS_CONFIGURED:
1622 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 case STATUS_ERROR:
1624 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 break;
1627 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001628 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 return INVALID_OPERATION;
1630 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001631 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1632 maxExpectedDuration);
1633 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001634 if (res != OK) {
1635 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1636 res);
1637 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 return res;
1639}
1640
Ruben Brunk183f0562015-08-12 12:55:02 -07001641
1642void Camera3Device::internalUpdateStatusLocked(Status status) {
1643 mStatus = status;
1644 mRecentStatusUpdates.add(mStatus);
1645 mStatusChanged.broadcast();
1646}
1647
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001648// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001649status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 mRequestThread->setPaused(true);
1651 mPauseStateNotify = true;
1652
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001653 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1654 maxExpectedDuration);
1655 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001656 if (res != OK) {
1657 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001658 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001659 }
1660
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 return res;
1662}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001663
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001664// Resume after internalPauseAndWaitLocked
1665status_t Camera3Device::internalResumeLocked() {
1666 status_t res;
1667
1668 mRequestThread->setPaused(false);
1669
1670 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1671 if (res != OK) {
1672 SET_ERR_L("Can't transition to active in %f seconds!",
1673 kActiveTimeout/1e9);
1674 }
1675 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001676 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677}
1678
Ruben Brunk183f0562015-08-12 12:55:02 -07001679status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001680 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001681
1682 size_t startIndex = 0;
1683 if (mStatusWaiters == 0) {
1684 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1685 // this status list
1686 mRecentStatusUpdates.clear();
1687 } else {
1688 // If other threads are waiting on updates to this status list, set the position of the
1689 // first element that this list will check rather than clearing the list.
1690 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 }
1692
Ruben Brunk183f0562015-08-12 12:55:02 -07001693 mStatusWaiters++;
1694
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 bool stateSeen = false;
1696 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001697 if (active == (mStatus == STATUS_ACTIVE)) {
1698 // Desired state is current
1699 break;
1700 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001701
1702 res = mStatusChanged.waitRelative(mLock, timeout);
1703 if (res != OK) break;
1704
Ruben Brunk183f0562015-08-12 12:55:02 -07001705 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1706 // transitions.
1707 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1708 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1709 __FUNCTION__);
1710
1711 // Encountered desired state since we began waiting
1712 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001713 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1714 stateSeen = true;
1715 break;
1716 }
1717 }
1718 } while (!stateSeen);
1719
Ruben Brunk183f0562015-08-12 12:55:02 -07001720 mStatusWaiters--;
1721
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 return res;
1723}
1724
1725
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001726status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001728 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001730 if (listener != NULL && mListener != NULL) {
1731 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1732 }
1733 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001734 mRequestThread->setNotificationListener(listener);
1735 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001736
1737 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001738}
1739
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001740bool Camera3Device::willNotify3A() {
1741 return false;
1742}
1743
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001745 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001746 status_t res;
1747 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001749 while (mResultQueue.empty()) {
1750 res = mResultSignal.waitRelative(mOutputLock, timeout);
1751 if (res == TIMED_OUT) {
1752 return res;
1753 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001754 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1755 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001756 return res;
1757 }
1758 }
1759 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001760}
1761
Jianing Weicb0652e2014-03-12 18:29:36 -07001762status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001763 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001764 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001766 if (mResultQueue.empty()) {
1767 return NOT_ENOUGH_DATA;
1768 }
1769
Jianing Weicb0652e2014-03-12 18:29:36 -07001770 if (frame == NULL) {
1771 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1772 return BAD_VALUE;
1773 }
1774
1775 CaptureResult &result = *(mResultQueue.begin());
1776 frame->mResultExtras = result.mResultExtras;
1777 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001778 mResultQueue.erase(mResultQueue.begin());
1779
1780 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001781}
1782
1783status_t Camera3Device::triggerAutofocus(uint32_t id) {
1784 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001786
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001787 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1788 // Mix-in this trigger into the next request and only the next request.
1789 RequestTrigger trigger[] = {
1790 {
1791 ANDROID_CONTROL_AF_TRIGGER,
1792 ANDROID_CONTROL_AF_TRIGGER_START
1793 },
1794 {
1795 ANDROID_CONTROL_AF_TRIGGER_ID,
1796 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001797 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001798 };
1799
1800 return mRequestThread->queueTrigger(trigger,
1801 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001802}
1803
1804status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1805 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001807
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001808 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1809 // Mix-in this trigger into the next request and only the next request.
1810 RequestTrigger trigger[] = {
1811 {
1812 ANDROID_CONTROL_AF_TRIGGER,
1813 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1814 },
1815 {
1816 ANDROID_CONTROL_AF_TRIGGER_ID,
1817 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001818 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001819 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001821 return mRequestThread->queueTrigger(trigger,
1822 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001823}
1824
1825status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1826 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001828
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001829 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1830 // Mix-in this trigger into the next request and only the next request.
1831 RequestTrigger trigger[] = {
1832 {
1833 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1834 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1835 },
1836 {
1837 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1838 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001839 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001840 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001841
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001842 return mRequestThread->queueTrigger(trigger,
1843 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001844}
1845
Jianing Weicb0652e2014-03-12 18:29:36 -07001846status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001847 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001848 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001850
Zhijun He7ef20392014-04-21 16:04:17 -07001851 {
1852 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001853 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001854 }
1855
Emilian Peev08dd2452017-04-06 16:55:14 +01001856 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001857}
1858
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001859status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001860 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1861}
1862
1863status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001864 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001865 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001866 Mutex::Autolock il(mInterfaceLock);
1867 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001868
1869 sp<Camera3StreamInterface> stream;
1870 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1871 if (outputStreamIdx == NAME_NOT_FOUND) {
1872 CLOGE("Stream %d does not exist", streamId);
1873 return BAD_VALUE;
1874 }
1875
1876 stream = mOutputStreams.editValueAt(outputStreamIdx);
1877
1878 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001879 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001880 return BAD_VALUE;
1881 }
1882
1883 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001884 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001885 return BAD_VALUE;
1886 }
1887
Ruben Brunkc78ac262015-08-13 17:58:46 -07001888 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001889}
1890
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001891status_t Camera3Device::tearDown(int streamId) {
1892 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001893 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001894 Mutex::Autolock il(mInterfaceLock);
1895 Mutex::Autolock l(mLock);
1896
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001897 sp<Camera3StreamInterface> stream;
1898 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1899 if (outputStreamIdx == NAME_NOT_FOUND) {
1900 CLOGE("Stream %d does not exist", streamId);
1901 return BAD_VALUE;
1902 }
1903
1904 stream = mOutputStreams.editValueAt(outputStreamIdx);
1905
1906 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1907 CLOGE("Stream %d is a target of a in-progress request", streamId);
1908 return BAD_VALUE;
1909 }
1910
1911 return stream->tearDown();
1912}
1913
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001914status_t Camera3Device::addBufferListenerForStream(int streamId,
1915 wp<Camera3StreamBufferListener> listener) {
1916 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001917 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001918 Mutex::Autolock il(mInterfaceLock);
1919 Mutex::Autolock l(mLock);
1920
1921 sp<Camera3StreamInterface> stream;
1922 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1923 if (outputStreamIdx == NAME_NOT_FOUND) {
1924 CLOGE("Stream %d does not exist", streamId);
1925 return BAD_VALUE;
1926 }
1927
1928 stream = mOutputStreams.editValueAt(outputStreamIdx);
1929 stream->addBufferListener(listener);
1930
1931 return OK;
1932}
1933
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001934/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 * Methods called by subclasses
1936 */
1937
1938void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001939 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001940 {
1941 // Need mLock to safely update state and synchronize to current
1942 // state of methods in flight.
1943 Mutex::Autolock l(mLock);
1944 // We can get various system-idle notices from the status tracker
1945 // while starting up. Only care about them if we've actually sent
1946 // in some requests recently.
1947 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1948 return;
1949 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001950 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001952 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001953
1954 // Skip notifying listener if we're doing some user-transparent
1955 // state changes
1956 if (mPauseStateNotify) return;
1957 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001958
1959 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001960 {
1961 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001962 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001963 }
1964 if (idle && listener != NULL) {
1965 listener->notifyIdle();
1966 }
1967}
1968
Shuzhen Wang758c2152017-01-10 18:26:18 -08001969status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001970 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001971 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001972 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1973 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001974
1975 if (surfaceIds == nullptr) {
1976 return BAD_VALUE;
1977 }
1978
Zhijun He5d677d12016-05-29 16:52:39 -07001979 Mutex::Autolock il(mInterfaceLock);
1980 Mutex::Autolock l(mLock);
1981
Shuzhen Wang758c2152017-01-10 18:26:18 -08001982 if (consumers.size() == 0) {
1983 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001984 return BAD_VALUE;
1985 }
1986
1987 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1988 if (idx == NAME_NOT_FOUND) {
1989 CLOGE("Stream %d is unknown", streamId);
1990 return idx;
1991 }
1992 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001993 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001994 if (res != OK) {
1995 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1996 return res;
1997 }
1998
Emilian Peev40ead602017-09-26 15:46:36 +01001999 for (auto &consumer : consumers) {
2000 int id = stream->getSurfaceId(consumer);
2001 if (id < 0) {
2002 CLOGE("Invalid surface id!");
2003 return BAD_VALUE;
2004 }
2005 surfaceIds->push_back(id);
2006 }
2007
Shuzhen Wang0129d522016-10-30 22:43:41 -07002008 if (stream->isConsumerConfigurationDeferred()) {
2009 if (!stream->isConfiguring()) {
2010 CLOGE("Stream %d was already fully configured.", streamId);
2011 return INVALID_OPERATION;
2012 }
Zhijun He5d677d12016-05-29 16:52:39 -07002013
Shuzhen Wang0129d522016-10-30 22:43:41 -07002014 res = stream->finishConfiguration();
2015 if (res != OK) {
2016 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2017 stream->getId(), strerror(-res), res);
2018 return res;
2019 }
Zhijun He5d677d12016-05-29 16:52:39 -07002020 }
2021
2022 return OK;
2023}
2024
Emilian Peev40ead602017-09-26 15:46:36 +01002025status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2026 const std::vector<OutputStreamInfo> &outputInfo,
2027 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2028 Mutex::Autolock il(mInterfaceLock);
2029 Mutex::Autolock l(mLock);
2030
2031 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2032 if (idx == NAME_NOT_FOUND) {
2033 CLOGE("Stream %d is unknown", streamId);
2034 return idx;
2035 }
2036
2037 for (const auto &it : removedSurfaceIds) {
2038 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2039 CLOGE("Shared surface still part of a pending request!");
2040 return -EBUSY;
2041 }
2042 }
2043
2044 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2045 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2046 if (res != OK) {
2047 CLOGE("Stream %d failed to update stream (error %d %s) ",
2048 streamId, res, strerror(-res));
2049 if (res == UNKNOWN_ERROR) {
2050 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2051 __FUNCTION__);
2052 }
2053 return res;
2054 }
2055
2056 return res;
2057}
2058
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002059status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2060 Mutex::Autolock il(mInterfaceLock);
2061 Mutex::Autolock l(mLock);
2062
2063 int idx = mOutputStreams.indexOfKey(streamId);
2064 if (idx == NAME_NOT_FOUND) {
2065 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2066 return BAD_VALUE;
2067 }
2068
2069 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2070 return stream->dropBuffers(dropping);
2071}
2072
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002073/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074 * Camera3Device private methods
2075 */
2076
2077sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002078 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 ATRACE_CALL();
2080 status_t res;
2081
2082 sp<CaptureRequest> newRequest = new CaptureRequest;
2083 newRequest->mSettings = request;
2084
2085 camera_metadata_entry_t inputStreams =
2086 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2087 if (inputStreams.count > 0) {
2088 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002089 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002090 CLOGE("Request references unknown input stream %d",
2091 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092 return NULL;
2093 }
2094 // Lazy completion of stream configuration (allocation/registration)
2095 // on first use
2096 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002097 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002099 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002101 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 return NULL;
2103 }
2104 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002105 // Check if stream is being prepared
2106 if (mInputStream->isPreparing()) {
2107 CLOGE("Request references an input stream that's being prepared!");
2108 return NULL;
2109 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110
2111 newRequest->mInputStream = mInputStream;
2112 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2113 }
2114
2115 camera_metadata_entry_t streams =
2116 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2117 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002118 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119 return NULL;
2120 }
2121
2122 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002123 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002124 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002125 CLOGE("Request references unknown stream %d",
2126 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127 return NULL;
2128 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002129 sp<Camera3OutputStreamInterface> stream =
2130 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002131
Zhijun He5d677d12016-05-29 16:52:39 -07002132 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002133 auto iter = surfaceMap.find(streams.data.i32[i]);
2134 if (iter != surfaceMap.end()) {
2135 const std::vector<size_t>& surfaces = iter->second;
2136 for (const auto& surface : surfaces) {
2137 if (stream->isConsumerConfigurationDeferred(surface)) {
2138 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2139 "due to deferred consumer", stream->getId(), surface);
2140 return NULL;
2141 }
2142 }
2143 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002144 }
2145
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146 // Lazy completion of stream configuration (allocation/registration)
2147 // on first use
2148 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002149 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002151 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2152 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002153 return NULL;
2154 }
2155 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002156 // Check if stream is being prepared
2157 if (stream->isPreparing()) {
2158 CLOGE("Request references an output stream that's being prepared!");
2159 return NULL;
2160 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002161
2162 newRequest->mOutputStreams.push(stream);
2163 }
2164 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002165 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166
2167 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002168}
2169
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002170bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2171 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2172 Size size = mSupportedOpaqueInputSizes[i];
2173 if (size.width == width && size.height == height) {
2174 return true;
2175 }
2176 }
2177
2178 return false;
2179}
2180
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002181void Camera3Device::cancelStreamsConfigurationLocked() {
2182 int res = OK;
2183 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2184 res = mInputStream->cancelConfiguration();
2185 if (res != OK) {
2186 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2187 mInputStream->getId(), strerror(-res), res);
2188 }
2189 }
2190
2191 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2192 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2193 if (outputStream->isConfiguring()) {
2194 res = outputStream->cancelConfiguration();
2195 if (res != OK) {
2196 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2197 outputStream->getId(), strerror(-res), res);
2198 }
2199 }
2200 }
2201
2202 // Return state to that at start of call, so that future configures
2203 // properly clean things up
2204 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2205 mNeedConfig = true;
2206}
2207
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002208status_t Camera3Device::configureStreamsLocked(int operatingMode,
2209 const CameraMetadata& sessionParams) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 ATRACE_CALL();
2211 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002212
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002213 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002214 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002215 return INVALID_OPERATION;
2216 }
2217
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002218 if (operatingMode < 0) {
2219 CLOGE("Invalid operating mode: %d", operatingMode);
2220 return BAD_VALUE;
2221 }
2222
2223 bool isConstrainedHighSpeed =
2224 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2225 operatingMode;
2226
2227 if (mOperatingMode != operatingMode) {
2228 mNeedConfig = true;
2229 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2230 mOperatingMode = operatingMode;
2231 }
2232
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002233 if (!mNeedConfig) {
2234 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2235 return OK;
2236 }
2237
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002238 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2239 // adding a dummy stream instead.
2240 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2241 if (mOutputStreams.size() == 0) {
2242 addDummyStreamLocked();
2243 } else {
2244 tryRemoveDummyStreamLocked();
2245 }
2246
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002248 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249
2250 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002251 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2253
2254 Vector<camera3_stream_t*> streams;
2255 streams.setCapacity(config.num_streams);
2256
2257 if (mInputStream != NULL) {
2258 camera3_stream_t *inputStream;
2259 inputStream = mInputStream->startConfiguration();
2260 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002261 CLOGE("Can't start input stream configuration");
2262 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002263 return INVALID_OPERATION;
2264 }
2265 streams.add(inputStream);
2266 }
2267
2268 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002269
2270 // Don't configure bidi streams twice, nor add them twice to the list
2271 if (mOutputStreams[i].get() ==
2272 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2273
2274 config.num_streams--;
2275 continue;
2276 }
2277
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002278 camera3_stream_t *outputStream;
2279 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2280 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002281 CLOGE("Can't start output stream configuration");
2282 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002283 return INVALID_OPERATION;
2284 }
2285 streams.add(outputStream);
2286 }
2287
2288 config.streams = streams.editArray();
2289
2290 // Do the HAL configuration; will potentially touch stream
2291 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002292
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002293 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
2294 res = mInterface->configureStreams(sessionBuffer, &config);
2295 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002297 if (res == BAD_VALUE) {
2298 // HAL rejected this set of streams as unsupported, clean up config
2299 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002300 CLOGE("Set of requested inputs/outputs not supported by HAL");
2301 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002302 return BAD_VALUE;
2303 } else if (res != OK) {
2304 // Some other kind of error from configure_streams - this is not
2305 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002306 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2307 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 return res;
2309 }
2310
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002311 // Finish all stream configuration immediately.
2312 // TODO: Try to relax this later back to lazy completion, which should be
2313 // faster
2314
Igor Murashkin073f8572013-05-02 14:59:28 -07002315 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002316 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002317 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002318 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002319 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002320 cancelStreamsConfigurationLocked();
2321 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002322 }
2323 }
2324
2325 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002326 sp<Camera3OutputStreamInterface> outputStream =
2327 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002328 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002329 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002330 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002331 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002332 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002333 cancelStreamsConfigurationLocked();
2334 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002335 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002336 }
2337 }
2338
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002339 // Request thread needs to know to avoid using repeat-last-settings protocol
2340 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002341 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002342
Zhijun He90f7c372016-08-16 16:19:43 -07002343 char value[PROPERTY_VALUE_MAX];
2344 property_get("camera.fifo.disable", value, "0");
2345 int32_t disableFifo = atoi(value);
2346 if (disableFifo != 1) {
2347 // Boost priority of request thread to SCHED_FIFO.
2348 pid_t requestThreadTid = mRequestThread->getTid();
2349 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002350 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002351 if (res != OK) {
2352 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2353 strerror(-res), res);
2354 } else {
2355 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2356 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002357 }
2358
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002359 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002360 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2361 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2362 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2363 sessionParams.unlock(newSessionParams);
2364 mSessionParams.unlock(currentSessionParams);
2365 if (updateSessionParams) {
2366 mSessionParams = sessionParams;
2367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002369 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370
Ruben Brunk183f0562015-08-12 12:55:02 -07002371 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2372 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002373
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002374 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002375
Zhijun He0a210512014-07-24 13:45:15 -07002376 // tear down the deleted streams after configure streams.
2377 mDeletedStreams.clear();
2378
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002380}
2381
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002382status_t Camera3Device::addDummyStreamLocked() {
2383 ATRACE_CALL();
2384 status_t res;
2385
2386 if (mDummyStreamId != NO_STREAM) {
2387 // Should never be adding a second dummy stream when one is already
2388 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002389 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2390 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002391 return INVALID_OPERATION;
2392 }
2393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002394 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002395
2396 sp<Camera3OutputStreamInterface> dummyStream =
2397 new Camera3DummyStream(mNextStreamId);
2398
2399 res = mOutputStreams.add(mNextStreamId, dummyStream);
2400 if (res < 0) {
2401 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2402 return res;
2403 }
2404
2405 mDummyStreamId = mNextStreamId;
2406 mNextStreamId++;
2407
2408 return OK;
2409}
2410
2411status_t Camera3Device::tryRemoveDummyStreamLocked() {
2412 ATRACE_CALL();
2413 status_t res;
2414
2415 if (mDummyStreamId == NO_STREAM) return OK;
2416 if (mOutputStreams.size() == 1) return OK;
2417
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002418 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002419
2420 // Ok, have a dummy stream and there's at least one other output stream,
2421 // so remove the dummy
2422
2423 sp<Camera3StreamInterface> deletedStream;
2424 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2425 if (outputStreamIdx == NAME_NOT_FOUND) {
2426 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2427 return INVALID_OPERATION;
2428 }
2429
2430 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2431 mOutputStreams.removeItemsAt(outputStreamIdx);
2432
2433 // Free up the stream endpoint so that it can be used by some other stream
2434 res = deletedStream->disconnect();
2435 if (res != OK) {
2436 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2437 // fall through since we want to still list the stream as deleted.
2438 }
2439 mDeletedStreams.add(deletedStream);
2440 mDummyStreamId = NO_STREAM;
2441
2442 return res;
2443}
2444
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002445void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002446 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002447 Mutex::Autolock l(mLock);
2448 va_list args;
2449 va_start(args, fmt);
2450
2451 setErrorStateLockedV(fmt, args);
2452
2453 va_end(args);
2454}
2455
2456void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002457 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002458 Mutex::Autolock l(mLock);
2459 setErrorStateLockedV(fmt, args);
2460}
2461
2462void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2463 va_list args;
2464 va_start(args, fmt);
2465
2466 setErrorStateLockedV(fmt, args);
2467
2468 va_end(args);
2469}
2470
2471void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002472 // Print out all error messages to log
2473 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002474 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002475
2476 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002477 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002478
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002479 mErrorCause = errorCause;
2480
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002481 if (mRequestThread != nullptr) {
2482 mRequestThread->setPaused(true);
2483 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002484 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002485
2486 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002487 sp<NotificationListener> listener = mListener.promote();
2488 if (listener != NULL) {
2489 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002490 CaptureResultExtras());
2491 }
2492
2493 // Save stack trace. View by dumping it later.
2494 CameraTraces::saveTrace();
2495 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002496}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497
2498/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002499 * In-flight request management
2500 */
2501
Jianing Weicb0652e2014-03-12 18:29:36 -07002502status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002503 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002504 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002505 ATRACE_CALL();
2506 Mutex::Autolock l(mInFlightLock);
2507
2508 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002509 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002510 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002511 if (res < 0) return res;
2512
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002513 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002514 // hold mLock to prevent race with disconnect
2515 Mutex::Autolock l(mLock);
2516 if (mStatusTracker != nullptr) {
2517 mStatusTracker->markComponentActive(mInFlightStatusId);
2518 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002519 }
2520
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002521 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002522 return OK;
2523}
2524
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002525void Camera3Device::returnOutputBuffers(
2526 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2527 nsecs_t timestamp) {
2528 for (size_t i = 0; i < numBuffers; i++)
2529 {
2530 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2531 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2532 // Note: stream may be deallocated at this point, if this buffer was
2533 // the last reference to it.
2534 if (res != OK) {
2535 ALOGE("Can't return buffer to its stream: %s (%d)",
2536 strerror(-res), res);
2537 }
2538 }
2539}
2540
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002541void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002542 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002543 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002544 mInFlightMap.removeItemsAt(idx, 1);
2545
2546 // Indicate idle inFlightMap to the status tracker
2547 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002548 // hold mLock to prevent race with disconnect
2549 Mutex::Autolock l(mLock);
2550 if (mStatusTracker != nullptr) {
2551 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2552 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002553 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002554 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002555}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002556
2557void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2558
2559 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2560 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2561
2562 nsecs_t sensorTimestamp = request.sensorTimestamp;
2563 nsecs_t shutterTimestamp = request.shutterTimestamp;
2564
2565 // Check if it's okay to remove the request from InFlightMap:
2566 // In the case of a successful request:
2567 // all input and output buffers, all result metadata, shutter callback
2568 // arrived.
2569 // In the case of a unsuccessful request:
2570 // all input and output buffers arrived.
2571 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002572 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002573 (request.haveResultMetadata && shutterTimestamp != 0))) {
2574 ATRACE_ASYNC_END("frame capture", frameNumber);
2575
Shuzhen Wang403044a2017-02-26 23:29:04 -08002576 // Sanity check - if sensor timestamp matches shutter timestamp in the
2577 // case of request having callback.
2578 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002579 sensorTimestamp != shutterTimestamp) {
2580 SET_ERR("sensor timestamp (%" PRId64
2581 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2582 sensorTimestamp, frameNumber, shutterTimestamp);
2583 }
2584
2585 // for an unsuccessful request, it may have pending output buffers to
2586 // return.
2587 assert(request.requestStatus != OK ||
2588 request.pendingOutputBuffers.size() == 0);
2589 returnOutputBuffers(request.pendingOutputBuffers.array(),
2590 request.pendingOutputBuffers.size(), 0);
2591
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002592 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002593 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2594 }
2595
2596 // Sanity check - if we have too many in-flight frames, something has
2597 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002598 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002599 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002600 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2601 kInFlightWarnLimitHighSpeed) {
2602 CLOGE("In-flight list too large for high speed configuration: %zu",
2603 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002604 }
2605}
2606
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002607void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002608 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002609 { // First return buffers cached in mInFlightMap
2610 Mutex::Autolock l(mInFlightLock);
2611 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2612 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2613 returnOutputBuffers(request.pendingOutputBuffers.array(),
2614 request.pendingOutputBuffers.size(), 0);
2615 }
2616 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002617 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002618 }
2619
2620 // Then return all inflight buffers not returned by HAL
2621 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2622 mInterface->getInflightBufferKeys(&inflightKeys);
2623
2624 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2625 for (auto& pair : inflightKeys) {
2626 int32_t frameNumber = pair.first;
2627 int32_t streamId = pair.second;
2628 buffer_handle_t* buffer;
2629 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2630 if (res != OK) {
2631 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2632 __FUNCTION__, frameNumber, streamId);
2633 continue;
2634 }
2635
2636 camera3_stream_buffer_t streamBuffer;
2637 streamBuffer.buffer = buffer;
2638 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2639 streamBuffer.acquire_fence = -1;
2640 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002641
2642 // First check if the buffer belongs to deleted stream
2643 bool streamDeleted = false;
2644 for (auto& stream : mDeletedStreams) {
2645 if (streamId == stream->getId()) {
2646 streamDeleted = true;
2647 // Return buffer to deleted stream
2648 camera3_stream* halStream = stream->asHalStream();
2649 streamBuffer.stream = halStream;
2650 switch (halStream->stream_type) {
2651 case CAMERA3_STREAM_OUTPUT:
2652 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2653 if (res != OK) {
2654 ALOGE("%s: Can't return output buffer for frame %d to"
2655 " stream %d: %s (%d)", __FUNCTION__,
2656 frameNumber, streamId, strerror(-res), res);
2657 }
2658 break;
2659 case CAMERA3_STREAM_INPUT:
2660 res = stream->returnInputBuffer(streamBuffer);
2661 if (res != OK) {
2662 ALOGE("%s: Can't return input buffer for frame %d to"
2663 " stream %d: %s (%d)", __FUNCTION__,
2664 frameNumber, streamId, strerror(-res), res);
2665 }
2666 break;
2667 default: // Bi-direcitonal stream is deprecated
2668 ALOGE("%s: stream %d has unknown stream type %d",
2669 __FUNCTION__, streamId, halStream->stream_type);
2670 break;
2671 }
2672 break;
2673 }
2674 }
2675 if (streamDeleted) {
2676 continue;
2677 }
2678
2679 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002680 if (streamId == inputStreamId) {
2681 streamBuffer.stream = mInputStream->asHalStream();
2682 res = mInputStream->returnInputBuffer(streamBuffer);
2683 if (res != OK) {
2684 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002685 " stream %d: %s (%d)", __FUNCTION__,
2686 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002687 }
2688 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002689 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2690 if (idx == NAME_NOT_FOUND) {
2691 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2692 continue;
2693 }
2694 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002695 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2696 }
2697 }
2698}
2699
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002700void Camera3Device::insertResultLocked(CaptureResult *result,
2701 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002702 if (result == nullptr) return;
2703
Emilian Peev71c73a22017-03-21 16:35:51 +00002704 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2705 result->mMetadata.getAndLock());
2706 set_camera_metadata_vendor_id(meta, mVendorTagId);
2707 result->mMetadata.unlock(meta);
2708
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002709 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2710 (int32_t*)&frameNumber, 1) != OK) {
2711 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2712 return;
2713 }
2714
2715 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2716 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2717 return;
2718 }
2719
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002720 // Valid result, insert into queue
2721 List<CaptureResult>::iterator queuedResult =
2722 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2723 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2724 ", burstId = %" PRId32, __FUNCTION__,
2725 queuedResult->mResultExtras.requestId,
2726 queuedResult->mResultExtras.frameNumber,
2727 queuedResult->mResultExtras.burstId);
2728
2729 mResultSignal.signal();
2730}
2731
2732
2733void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002734 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002735 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002736 Mutex::Autolock l(mOutputLock);
2737
2738 CaptureResult captureResult;
2739 captureResult.mResultExtras = resultExtras;
2740 captureResult.mMetadata = partialResult;
2741
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002742 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002743}
2744
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002745
2746void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2747 CaptureResultExtras &resultExtras,
2748 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002749 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002750 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002751 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 if (pendingMetadata.isEmpty())
2753 return;
2754
2755 Mutex::Autolock l(mOutputLock);
2756
2757 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002758 if (reprocess) {
2759 if (frameNumber < mNextReprocessResultFrameNumber) {
2760 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002761 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002762 frameNumber, mNextReprocessResultFrameNumber);
2763 return;
2764 }
2765 mNextReprocessResultFrameNumber = frameNumber + 1;
2766 } else {
2767 if (frameNumber < mNextResultFrameNumber) {
2768 SET_ERR("Out-of-order capture result metadata submitted! "
2769 "(got frame number %d, expecting %d)",
2770 frameNumber, mNextResultFrameNumber);
2771 return;
2772 }
2773 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002774 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002775
2776 CaptureResult captureResult;
2777 captureResult.mResultExtras = resultExtras;
2778 captureResult.mMetadata = pendingMetadata;
2779
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002780 // Append any previous partials to form a complete result
2781 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2782 captureResult.mMetadata.append(collectedPartialResult);
2783 }
2784
2785 captureResult.mMetadata.sort();
2786
2787 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002788 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2789 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790 SET_ERR("No timestamp provided by HAL for frame %d!",
2791 frameNumber);
2792 return;
2793 }
2794
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002795 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2796 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2797
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002798 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002799}
2800
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002801/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802 * Camera HAL device callback methods
2803 */
2804
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002805void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002806 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002807
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002808 status_t res;
2809
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002810 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002811 if (result->result == NULL && result->num_output_buffers == 0 &&
2812 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002813 SET_ERR("No result data provided by HAL for frame %d",
2814 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002815 return;
2816 }
Zhijun He204e3292014-07-14 17:09:23 -07002817
Zhijun He204e3292014-07-14 17:09:23 -07002818 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002819 result->result != NULL &&
2820 result->partial_result != 1) {
2821 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2822 " if partial result is not supported",
2823 frameNumber, result->partial_result);
2824 return;
2825 }
2826
2827 bool isPartialResult = false;
2828 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002829 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002830 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002831
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002832 // Get shutter timestamp and resultExtras from list of in-flight requests,
2833 // where it was added by the shutter notification for this frame. If the
2834 // shutter timestamp isn't received yet, append the output buffers to the
2835 // in-flight request and they will be returned when the shutter timestamp
2836 // arrives. Update the in-flight status and remove the in-flight entry if
2837 // all result data and shutter timestamp have been received.
2838 nsecs_t shutterTimestamp = 0;
2839
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002840 {
2841 Mutex::Autolock l(mInFlightLock);
2842 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2843 if (idx == NAME_NOT_FOUND) {
2844 SET_ERR("Unknown frame number for capture result: %d",
2845 frameNumber);
2846 return;
2847 }
2848 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002849 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2850 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002851 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002852 __FUNCTION__, request.resultExtras.requestId,
2853 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002854 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002855 // Always update the partial count to the latest one if it's not 0
2856 // (buffers only). When framework aggregates adjacent partial results
2857 // into one, the latest partial count will be used.
2858 if (result->partial_result != 0)
2859 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002860
2861 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002862 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002863 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2864 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2865 " the range of [1, %d] when metadata is included in the result",
2866 frameNumber, result->partial_result, mNumPartialResults);
2867 return;
2868 }
2869 isPartialResult = (result->partial_result < mNumPartialResults);
2870 if (isPartialResult) {
2871 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002872 }
2873
Shuzhen Wang4a472662017-02-26 23:29:04 -08002874 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002875 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002876 sendPartialCaptureResult(result->result, request.resultExtras,
2877 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002878 }
2879 }
2880
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002881 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002882 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002883
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002884 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002885 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002886 if (request.haveResultMetadata) {
2887 SET_ERR("Called multiple times with metadata for frame %d",
2888 frameNumber);
2889 return;
2890 }
Zhijun He204e3292014-07-14 17:09:23 -07002891 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002892 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002893 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002894 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002895 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002896 request.haveResultMetadata = true;
2897 }
2898
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002899 uint32_t numBuffersReturned = result->num_output_buffers;
2900 if (result->input_buffer != NULL) {
2901 if (hasInputBufferInRequest) {
2902 numBuffersReturned += 1;
2903 } else {
2904 ALOGW("%s: Input buffer should be NULL if there is no input"
2905 " buffer sent in the request",
2906 __FUNCTION__);
2907 }
2908 }
2909 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002910 if (request.numBuffersLeft < 0) {
2911 SET_ERR("Too many buffers returned for frame %d",
2912 frameNumber);
2913 return;
2914 }
2915
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002916 camera_metadata_ro_entry_t entry;
2917 res = find_camera_metadata_ro_entry(result->result,
2918 ANDROID_SENSOR_TIMESTAMP, &entry);
2919 if (res == OK && entry.count == 1) {
2920 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002921 }
2922
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002923 // If shutter event isn't received yet, append the output buffers to
2924 // the in-flight request. Otherwise, return the output buffers to
2925 // streams.
2926 if (shutterTimestamp == 0) {
2927 request.pendingOutputBuffers.appendArray(result->output_buffers,
2928 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002929 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002930 returnOutputBuffers(result->output_buffers,
2931 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002932 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002933
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002934 if (result->result != NULL && !isPartialResult) {
2935 if (shutterTimestamp == 0) {
2936 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002937 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002938 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002939 CameraMetadata metadata;
2940 metadata = result->result;
2941 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002942 collectedPartialResult, frameNumber,
2943 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002944 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002945 }
2946
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002947 removeInFlightRequestIfReadyLocked(idx);
2948 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002949
Zhijun Hef0d962a2014-06-30 10:24:11 -07002950 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002951 if (hasInputBufferInRequest) {
2952 Camera3Stream *stream =
2953 Camera3Stream::cast(result->input_buffer->stream);
2954 res = stream->returnInputBuffer(*(result->input_buffer));
2955 // Note: stream may be deallocated at this point, if this buffer was the
2956 // last reference to it.
2957 if (res != OK) {
2958 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2959 " its stream:%s (%d)", __FUNCTION__,
2960 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002961 }
2962 } else {
2963 ALOGW("%s: Input buffer should be NULL if there is no input"
2964 " buffer sent in the request, skipping input buffer return.",
2965 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002966 }
2967 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002968}
2969
2970void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002971 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002972 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002973 {
2974 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002975 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002976 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002977
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002978 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002979 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002980 return;
2981 }
2982
2983 switch (msg->type) {
2984 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002985 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002986 break;
2987 }
2988 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002989 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002990 break;
2991 }
2992 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002993 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002994 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002995 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002996}
2997
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002998void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002999 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003000 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003001 // Map camera HAL error codes to ICameraDeviceCallback error codes
3002 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003003 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003004 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003005 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003006 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003007 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003008 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003009 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003010 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003011 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003012 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003013 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003014 };
3015
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003017 ((msg.error_code >= 0) &&
3018 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3019 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003020 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003021
3022 int streamId = 0;
3023 if (msg.error_stream != NULL) {
3024 Camera3Stream *stream =
3025 Camera3Stream::cast(msg.error_stream);
3026 streamId = stream->getId();
3027 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003028 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3029 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003030 streamId, msg.error_code);
3031
3032 CaptureResultExtras resultExtras;
3033 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003035 // SET_ERR calls notifyError
3036 SET_ERR("Camera HAL reported serious device error");
3037 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3039 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3040 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003041 {
3042 Mutex::Autolock l(mInFlightLock);
3043 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3044 if (idx >= 0) {
3045 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3046 r.requestStatus = msg.error_code;
3047 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003048 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3049 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3050 errorCode) {
3051 r.skipResultMetadata = true;
3052 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003053 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3054 errorCode) {
3055 // In case of missing result check whether the buffers
3056 // returned. If they returned, then remove inflight
3057 // request.
3058 removeInFlightRequestIfReadyLocked(idx);
3059 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003060 } else {
3061 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003062 ALOGE("Camera %s: %s: cannot find in-flight request on "
3063 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003064 resultExtras.frameNumber);
3065 }
3066 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003067 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003068 if (listener != NULL) {
3069 listener->notifyError(errorCode, resultExtras);
3070 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003071 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003072 }
3073 break;
3074 default:
3075 // SET_ERR calls notifyError
3076 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3077 break;
3078 }
3079}
3080
3081void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003082 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003083 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003084 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003085
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003086 // Set timestamp for the request in the in-flight tracking
3087 // and get the request ID to send upstream
3088 {
3089 Mutex::Autolock l(mInFlightLock);
3090 idx = mInFlightMap.indexOfKey(msg.frame_number);
3091 if (idx >= 0) {
3092 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003094 // Verify ordering of shutter notifications
3095 {
3096 Mutex::Autolock l(mOutputLock);
3097 // TODO: need to track errors for tighter bounds on expected frame number.
3098 if (r.hasInputBuffer) {
3099 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3100 SET_ERR("Shutter notification out-of-order. Expected "
3101 "notification for frame %d, got frame %d",
3102 mNextReprocessShutterFrameNumber, msg.frame_number);
3103 return;
3104 }
3105 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3106 } else {
3107 if (msg.frame_number < mNextShutterFrameNumber) {
3108 SET_ERR("Shutter notification out-of-order. Expected "
3109 "notification for frame %d, got frame %d",
3110 mNextShutterFrameNumber, msg.frame_number);
3111 return;
3112 }
3113 mNextShutterFrameNumber = msg.frame_number + 1;
3114 }
3115 }
3116
Shuzhen Wang4a472662017-02-26 23:29:04 -08003117 r.shutterTimestamp = msg.timestamp;
3118 if (r.hasCallback) {
3119 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003121 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003122 // Call listener, if any
3123 if (listener != NULL) {
3124 listener->notifyShutter(r.resultExtras, msg.timestamp);
3125 }
3126 // send pending result and buffers
3127 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3128 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003129 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003130 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003131 returnOutputBuffers(r.pendingOutputBuffers.array(),
3132 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3133 r.pendingOutputBuffers.clear();
3134
3135 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003136 }
3137 }
3138 if (idx < 0) {
3139 SET_ERR("Shutter notification for non-existent frame number %d",
3140 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003141 }
3142}
3143
3144
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003145CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003146 ALOGV("%s", __FUNCTION__);
3147
Igor Murashkin1e479c02013-09-06 16:55:14 -07003148 CameraMetadata retVal;
3149
3150 if (mRequestThread != NULL) {
3151 retVal = mRequestThread->getLatestRequest();
3152 }
3153
Igor Murashkin1e479c02013-09-06 16:55:14 -07003154 return retVal;
3155}
3156
Jianing Weicb0652e2014-03-12 18:29:36 -07003157
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003158void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3159 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3160 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3161}
3162
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003163/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003164 * HalInterface inner class methods
3165 */
3166
Yifan Hongf79b5542017-04-11 14:44:25 -07003167Camera3Device::HalInterface::HalInterface(
3168 sp<ICameraDeviceSession> &session,
3169 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003170 mHidlSession(session),
3171 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172
Emilian Peev31abd0a2017-05-11 18:37:46 +01003173Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003174
3175Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003176 mHidlSession(other.mHidlSession),
3177 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003178
3179bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003180 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003181}
3182
3183void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003184 mHidlSession.clear();
3185}
3186
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003187bool Camera3Device::HalInterface::supportBatchRequest() {
3188 return mHidlSession != nullptr;
3189}
3190
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003191status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3192 camera3_request_template_t templateId,
3193 /*out*/ camera_metadata_t **requestTemplate) {
3194 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3195 if (!valid()) return INVALID_OPERATION;
3196 status_t res = OK;
3197
Emilian Peev31abd0a2017-05-11 18:37:46 +01003198 common::V1_0::Status status;
3199 RequestTemplate id;
3200 switch (templateId) {
3201 case CAMERA3_TEMPLATE_PREVIEW:
3202 id = RequestTemplate::PREVIEW;
3203 break;
3204 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3205 id = RequestTemplate::STILL_CAPTURE;
3206 break;
3207 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3208 id = RequestTemplate::VIDEO_RECORD;
3209 break;
3210 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3211 id = RequestTemplate::VIDEO_SNAPSHOT;
3212 break;
3213 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3214 id = RequestTemplate::ZERO_SHUTTER_LAG;
3215 break;
3216 case CAMERA3_TEMPLATE_MANUAL:
3217 id = RequestTemplate::MANUAL;
3218 break;
3219 default:
3220 // Unknown template ID
3221 return BAD_VALUE;
3222 }
3223 auto err = mHidlSession->constructDefaultRequestSettings(id,
3224 [&status, &requestTemplate]
3225 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3226 status = s;
3227 if (status == common::V1_0::Status::OK) {
3228 const camera_metadata *r =
3229 reinterpret_cast<const camera_metadata_t*>(request.data());
3230 size_t expectedSize = request.size();
3231 int ret = validate_camera_metadata_structure(r, &expectedSize);
3232 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3233 *requestTemplate = clone_camera_metadata(r);
3234 if (*requestTemplate == nullptr) {
3235 ALOGE("%s: Unable to clone camera metadata received from HAL",
3236 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003237 status = common::V1_0::Status::INTERNAL_ERROR;
3238 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003239 } else {
3240 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3241 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003242 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003243 }
3244 });
3245 if (!err.isOk()) {
3246 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3247 res = DEAD_OBJECT;
3248 } else {
3249 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003250 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003251
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003252 return res;
3253}
3254
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003255status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
3256 camera3_stream_configuration *config) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003257 ATRACE_NAME("CameraHal::configureStreams");
3258 if (!valid()) return INVALID_OPERATION;
3259 status_t res = OK;
3260
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 // Convert stream config to HIDL
3262 std::set<int> activeStreams;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003263 device::V3_4::StreamConfiguration requestedConfiguration;
3264 requestedConfiguration.v3_2.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003265 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003266 Stream &dst = requestedConfiguration.v3_2.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003267 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003268
Emilian Peev31abd0a2017-05-11 18:37:46 +01003269 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3270 cam3stream->setBufferFreedListener(this);
3271 int streamId = cam3stream->getId();
3272 StreamType streamType;
3273 switch (src->stream_type) {
3274 case CAMERA3_STREAM_OUTPUT:
3275 streamType = StreamType::OUTPUT;
3276 break;
3277 case CAMERA3_STREAM_INPUT:
3278 streamType = StreamType::INPUT;
3279 break;
3280 default:
3281 ALOGE("%s: Stream %d: Unsupported stream type %d",
3282 __FUNCTION__, streamId, config->streams[i]->stream_type);
3283 return BAD_VALUE;
3284 }
3285 dst.id = streamId;
3286 dst.streamType = streamType;
3287 dst.width = src->width;
3288 dst.height = src->height;
3289 dst.format = mapToPixelFormat(src->format);
Emilian Peev050f5dc2017-05-18 14:43:56 +01003290 dst.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peev31abd0a2017-05-11 18:37:46 +01003291 dst.dataSpace = mapToHidlDataspace(src->data_space);
3292 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3293
3294 activeStreams.insert(streamId);
3295 // Create Buffer ID map if necessary
3296 if (mBufferIdMaps.count(streamId) == 0) {
3297 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3298 }
3299 }
3300 // remove BufferIdMap for deleted streams
3301 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3302 int streamId = it->first;
3303 bool active = activeStreams.count(streamId) > 0;
3304 if (!active) {
3305 it = mBufferIdMaps.erase(it);
3306 } else {
3307 ++it;
3308 }
3309 }
3310
3311 res = mapToStreamConfigurationMode(
3312 (camera3_stream_configuration_mode_t) config->operation_mode,
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003313 /*out*/ &requestedConfiguration.v3_2.operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003314 if (res != OK) {
3315 return res;
3316 }
3317
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003318 requestedConfiguration.sessionParams.setToExternal(
3319 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3320 get_camera_metadata_size(sessionParams));
3321
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322 // Invoke configureStreams
3323
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003324 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003325 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003326
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003327 // See if we have v3.4 or v3.3 HAL
3328 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003329 sp<device::V3_3::ICameraDeviceSession> hidlSession_3_3;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003330 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3331 if (castResult_3_4.isOk()) {
3332 hidlSession_3_4 = castResult_3_4;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003333 } else {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003334 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3335 if (castResult_3_3.isOk()) {
3336 hidlSession_3_3 = castResult_3_3;
3337 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003338 }
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003339
3340 if (hidlSession_3_4 != nullptr) {
3341 // We do; use v3.4 for the call
3342 ALOGV("%s: v3.4 device found", __FUNCTION__);
3343 auto err = hidlSession_3_4->configureStreams_3_4(requestedConfiguration,
3344 [&status, &finalConfiguration]
3345 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
3346 finalConfiguration = halConfiguration;
3347 status = s;
3348 });
3349 if (!err.isOk()) {
3350 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3351 return DEAD_OBJECT;
3352 }
3353 } else if (hidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003354 // We do; use v3.3 for the call
3355 ALOGV("%s: v3.3 device found", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003356 auto err = hidlSession_3_3->configureStreams_3_3(requestedConfiguration.v3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003357 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003358 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003359 finalConfiguration = halConfiguration;
3360 status = s;
3361 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003362 if (!err.isOk()) {
3363 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3364 return DEAD_OBJECT;
3365 }
3366 } else {
3367 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3368 ALOGV("%s: v3.2 device found", __FUNCTION__);
3369 HalStreamConfiguration finalConfiguration_3_2;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003370 auto err = mHidlSession->configureStreams(requestedConfiguration.v3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003371 [&status, &finalConfiguration_3_2]
3372 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3373 finalConfiguration_3_2 = halConfiguration;
3374 status = s;
3375 });
3376 if (!err.isOk()) {
3377 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3378 return DEAD_OBJECT;
3379 }
3380 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3381 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3382 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3383 finalConfiguration.streams[i].overrideDataSpace =
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003384 requestedConfiguration.v3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003385 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386 }
3387
3388 if (status != common::V1_0::Status::OK ) {
3389 return CameraProviderManager::mapToStatusT(status);
3390 }
3391
3392 // And convert output stream configuration from HIDL
3393
3394 for (size_t i = 0; i < config->num_streams; i++) {
3395 camera3_stream_t *dst = config->streams[i];
3396 int streamId = Camera3Stream::cast(dst)->getId();
3397
3398 // Start scan at i, with the assumption that the stream order matches
3399 size_t realIdx = i;
3400 bool found = false;
3401 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003402 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003403 found = true;
3404 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003405 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003406 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3407 }
3408 if (!found) {
3409 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3410 __FUNCTION__, streamId);
3411 return INVALID_OPERATION;
3412 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003413 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003414
Emilian Peev710c1422017-08-30 11:19:38 +01003415 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3416 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003417 dstStream->setDataSpaceOverride(false);
3418 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3419 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3420
Emilian Peev31abd0a2017-05-11 18:37:46 +01003421 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3422 if (dst->format != overrideFormat) {
3423 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3424 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003425 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003426 if (dst->data_space != overrideDataSpace) {
3427 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3428 streamId, dst->format);
3429 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003430 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003431 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003432 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3433
Emilian Peev31abd0a2017-05-11 18:37:46 +01003434 // Override allowed with IMPLEMENTATION_DEFINED
3435 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003436 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003437 }
3438
Emilian Peev31abd0a2017-05-11 18:37:46 +01003439 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003440 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003441 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003442 __FUNCTION__, streamId);
3443 return INVALID_OPERATION;
3444 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003445 dstStream->setUsage(
3446 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003447 } else {
3448 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003449 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3451 __FUNCTION__, streamId);
3452 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003453 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003454 dstStream->setUsage(
3455 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003456 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003457 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003458 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003459
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003460 return res;
3461}
3462
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003463void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3464 /*out*/device::V3_2::CaptureRequest* captureRequest,
3465 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003466 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003467 if (captureRequest == nullptr || handlesCreated == nullptr) {
3468 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3469 __FUNCTION__, captureRequest, handlesCreated);
3470 return;
3471 }
3472
3473 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003474
3475 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003476
3477 {
3478 std::lock_guard<std::mutex> lock(mInflightLock);
3479 if (request->input_buffer != nullptr) {
3480 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3481 buffer_handle_t buf = *(request->input_buffer->buffer);
3482 auto pair = getBufferId(buf, streamId);
3483 bool isNewBuffer = pair.first;
3484 uint64_t bufferId = pair.second;
3485 captureRequest->inputBuffer.streamId = streamId;
3486 captureRequest->inputBuffer.bufferId = bufferId;
3487 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3488 captureRequest->inputBuffer.status = BufferStatus::OK;
3489 native_handle_t *acquireFence = nullptr;
3490 if (request->input_buffer->acquire_fence != -1) {
3491 acquireFence = native_handle_create(1,0);
3492 acquireFence->data[0] = request->input_buffer->acquire_fence;
3493 handlesCreated->push_back(acquireFence);
3494 }
3495 captureRequest->inputBuffer.acquireFence = acquireFence;
3496 captureRequest->inputBuffer.releaseFence = nullptr;
3497
3498 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3499 request->input_buffer->buffer,
3500 request->input_buffer->acquire_fence);
3501 } else {
3502 captureRequest->inputBuffer.streamId = -1;
3503 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3504 }
3505
3506 captureRequest->outputBuffers.resize(request->num_output_buffers);
3507 for (size_t i = 0; i < request->num_output_buffers; i++) {
3508 const camera3_stream_buffer_t *src = request->output_buffers + i;
3509 StreamBuffer &dst = captureRequest->outputBuffers[i];
3510 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3511 buffer_handle_t buf = *(src->buffer);
3512 auto pair = getBufferId(buf, streamId);
3513 bool isNewBuffer = pair.first;
3514 dst.streamId = streamId;
3515 dst.bufferId = pair.second;
3516 dst.buffer = isNewBuffer ? buf : nullptr;
3517 dst.status = BufferStatus::OK;
3518 native_handle_t *acquireFence = nullptr;
3519 if (src->acquire_fence != -1) {
3520 acquireFence = native_handle_create(1,0);
3521 acquireFence->data[0] = src->acquire_fence;
3522 handlesCreated->push_back(acquireFence);
3523 }
3524 dst.acquireFence = acquireFence;
3525 dst.releaseFence = nullptr;
3526
3527 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3528 src->buffer, src->acquire_fence);
3529 }
3530 }
3531}
3532
3533status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3534 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3535 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3536 if (!valid()) return INVALID_OPERATION;
3537
3538 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3539 size_t batchSize = requests.size();
3540 captureRequests.resize(batchSize);
3541 std::vector<native_handle_t*> handlesCreated;
3542
3543 for (size_t i = 0; i < batchSize; i++) {
3544 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3545 }
3546
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003547 std::vector<device::V3_2::BufferCache> cachesToRemove;
3548 {
3549 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3550 for (auto& pair : mFreedBuffers) {
3551 // The stream might have been removed since onBufferFreed
3552 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3553 cachesToRemove.push_back({pair.first, pair.second});
3554 }
3555 }
3556 mFreedBuffers.clear();
3557 }
3558
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003559 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3560 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003561
3562 // Write metadata to FMQ.
3563 for (size_t i = 0; i < batchSize; i++) {
3564 camera3_capture_request_t* request = requests[i];
3565 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3566
3567 if (request->settings != nullptr) {
3568 size_t settingsSize = get_camera_metadata_size(request->settings);
3569 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3570 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3571 captureRequest->settings.resize(0);
3572 captureRequest->fmqSettingsSize = settingsSize;
3573 } else {
3574 if (mRequestMetadataQueue != nullptr) {
3575 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3576 }
3577 captureRequest->settings.setToExternal(
3578 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3579 get_camera_metadata_size(request->settings));
3580 captureRequest->fmqSettingsSize = 0u;
3581 }
3582 } else {
3583 // A null request settings maps to a size-0 CameraMetadata
3584 captureRequest->settings.resize(0);
3585 captureRequest->fmqSettingsSize = 0u;
3586 }
3587 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003588 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003589 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3590 status = s;
3591 *numRequestProcessed = n;
3592 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003593 if (!err.isOk()) {
3594 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3595 return DEAD_OBJECT;
3596 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003597 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3598 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3599 __FUNCTION__, *numRequestProcessed, batchSize);
3600 status = common::V1_0::Status::INTERNAL_ERROR;
3601 }
3602
3603 for (auto& handle : handlesCreated) {
3604 native_handle_delete(handle);
3605 }
3606 return CameraProviderManager::mapToStatusT(status);
3607}
3608
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003609status_t Camera3Device::HalInterface::processCaptureRequest(
3610 camera3_capture_request_t *request) {
3611 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003612 if (!valid()) return INVALID_OPERATION;
3613 status_t res = OK;
3614
Emilian Peev31abd0a2017-05-11 18:37:46 +01003615 uint32_t numRequestProcessed = 0;
3616 std::vector<camera3_capture_request_t*> requests(1);
3617 requests[0] = request;
3618 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3619
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003620 return res;
3621}
3622
3623status_t Camera3Device::HalInterface::flush() {
3624 ATRACE_NAME("CameraHal::flush");
3625 if (!valid()) return INVALID_OPERATION;
3626 status_t res = OK;
3627
Emilian Peev31abd0a2017-05-11 18:37:46 +01003628 auto err = mHidlSession->flush();
3629 if (!err.isOk()) {
3630 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3631 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003632 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003633 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003634 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003635
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003636 return res;
3637}
3638
Emilian Peev31abd0a2017-05-11 18:37:46 +01003639status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003640 ATRACE_NAME("CameraHal::dump");
3641 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003642
Emilian Peev31abd0a2017-05-11 18:37:46 +01003643 // Handled by CameraProviderManager::dump
3644
3645 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003646}
3647
3648status_t Camera3Device::HalInterface::close() {
3649 ATRACE_NAME("CameraHal::close()");
3650 if (!valid()) return INVALID_OPERATION;
3651 status_t res = OK;
3652
Emilian Peev31abd0a2017-05-11 18:37:46 +01003653 auto err = mHidlSession->close();
3654 // Interface will be dead shortly anyway, so don't log errors
3655 if (!err.isOk()) {
3656 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003657 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003658
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003659 return res;
3660}
3661
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003662void Camera3Device::HalInterface::getInflightBufferKeys(
3663 std::vector<std::pair<int32_t, int32_t>>* out) {
3664 std::lock_guard<std::mutex> lock(mInflightLock);
3665 out->clear();
3666 out->reserve(mInflightBufferMap.size());
3667 for (auto& pair : mInflightBufferMap) {
3668 uint64_t key = pair.first;
3669 int32_t streamId = key & 0xFFFFFFFF;
3670 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3671 out->push_back(std::make_pair(frameNumber, streamId));
3672 }
3673 return;
3674}
3675
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003676status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003677 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003678 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003679 auto pair = std::make_pair(buffer, acquireFence);
3680 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003681 return OK;
3682}
3683
3684status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003685 int32_t frameNumber, int32_t streamId,
3686 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003687 std::lock_guard<std::mutex> lock(mInflightLock);
3688
3689 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3690 auto it = mInflightBufferMap.find(key);
3691 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003692 auto pair = it->second;
3693 *buffer = pair.first;
3694 int acquireFence = pair.second;
3695 if (acquireFence > 0) {
3696 ::close(acquireFence);
3697 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003698 mInflightBufferMap.erase(it);
3699 return OK;
3700}
3701
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003702std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3703 const buffer_handle_t& buf, int streamId) {
3704 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3705
3706 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3707 auto it = bIdMap.find(buf);
3708 if (it == bIdMap.end()) {
3709 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003710 ALOGV("stream %d now have %zu buffer caches, buf %p",
3711 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003712 return std::make_pair(true, mNextBufferId - 1);
3713 } else {
3714 return std::make_pair(false, it->second);
3715 }
3716}
3717
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003718void Camera3Device::HalInterface::onBufferFreed(
3719 int streamId, const native_handle_t* handle) {
3720 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3721 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3722 auto mapIt = mBufferIdMaps.find(streamId);
3723 if (mapIt == mBufferIdMaps.end()) {
3724 // streamId might be from a deleted stream here
3725 ALOGI("%s: stream %d has been removed",
3726 __FUNCTION__, streamId);
3727 return;
3728 }
3729 BufferIdMap& bIdMap = mapIt->second;
3730 auto it = bIdMap.find(handle);
3731 if (it == bIdMap.end()) {
3732 ALOGW("%s: cannot find buffer %p in stream %d",
3733 __FUNCTION__, handle, streamId);
3734 return;
3735 } else {
3736 bufferId = it->second;
3737 bIdMap.erase(it);
3738 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3739 __FUNCTION__, streamId, bIdMap.size(), handle);
3740 }
3741 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3742}
3743
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003744/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003745 * RequestThread inner class methods
3746 */
3747
3748Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003749 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003750 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003751 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003752 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003753 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003754 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003755 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003756 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003757 mReconfigured(false),
3758 mDoPause(false),
3759 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003760 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003761 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003762 mCurrentAfTriggerId(0),
3763 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003764 mRepeatingLastFrameNumber(
3765 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003766 mPrepareVideoStream(false),
3767 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003768 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003769}
3770
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003771Camera3Device::RequestThread::~RequestThread() {}
3772
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003773void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003774 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003775 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003776 Mutex::Autolock l(mRequestLock);
3777 mListener = listener;
3778}
3779
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003780void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003781 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003782 Mutex::Autolock l(mRequestLock);
3783 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003784 // Prepare video stream for high speed recording.
3785 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003786}
3787
Jianing Wei90e59c92014-03-12 18:29:36 -07003788status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003789 List<sp<CaptureRequest> > &requests,
3790 /*out*/
3791 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003792 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003793 Mutex::Autolock l(mRequestLock);
3794 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3795 ++it) {
3796 mRequestQueue.push_back(*it);
3797 }
3798
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003799 if (lastFrameNumber != NULL) {
3800 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3801 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3802 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3803 *lastFrameNumber);
3804 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003805
Jianing Wei90e59c92014-03-12 18:29:36 -07003806 unpauseForNewRequests();
3807
3808 return OK;
3809}
3810
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003811
3812status_t Camera3Device::RequestThread::queueTrigger(
3813 RequestTrigger trigger[],
3814 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003815 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003816 Mutex::Autolock l(mTriggerMutex);
3817 status_t ret;
3818
3819 for (size_t i = 0; i < count; ++i) {
3820 ret = queueTriggerLocked(trigger[i]);
3821
3822 if (ret != OK) {
3823 return ret;
3824 }
3825 }
3826
3827 return OK;
3828}
3829
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003830const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3831 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003832 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003833 if (d != nullptr) return d->mId;
3834 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003835}
3836
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003837status_t Camera3Device::RequestThread::queueTriggerLocked(
3838 RequestTrigger trigger) {
3839
3840 uint32_t tag = trigger.metadataTag;
3841 ssize_t index = mTriggerMap.indexOfKey(tag);
3842
3843 switch (trigger.getTagType()) {
3844 case TYPE_BYTE:
3845 // fall-through
3846 case TYPE_INT32:
3847 break;
3848 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003849 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3850 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003851 return INVALID_OPERATION;
3852 }
3853
3854 /**
3855 * Collect only the latest trigger, since we only have 1 field
3856 * in the request settings per trigger tag, and can't send more than 1
3857 * trigger per request.
3858 */
3859 if (index != NAME_NOT_FOUND) {
3860 mTriggerMap.editValueAt(index) = trigger;
3861 } else {
3862 mTriggerMap.add(tag, trigger);
3863 }
3864
3865 return OK;
3866}
3867
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003868status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003869 const RequestList &requests,
3870 /*out*/
3871 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003872 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003873 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003874 if (lastFrameNumber != NULL) {
3875 *lastFrameNumber = mRepeatingLastFrameNumber;
3876 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003877 mRepeatingRequests.clear();
3878 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3879 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003880
3881 unpauseForNewRequests();
3882
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003883 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003884 return OK;
3885}
3886
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003887bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003888 if (mRepeatingRequests.empty()) {
3889 return false;
3890 }
3891 int32_t requestId = requestIn->mResultExtras.requestId;
3892 const RequestList &repeatRequests = mRepeatingRequests;
3893 // All repeating requests are guaranteed to have same id so only check first quest
3894 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3895 return (firstRequest->mResultExtras.requestId == requestId);
3896}
3897
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003898status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003899 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003900 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003901 return clearRepeatingRequestsLocked(lastFrameNumber);
3902
3903}
3904
3905status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003906 mRepeatingRequests.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 Talvalaf76e0272013-02-27 18:02:26 -08003911 return OK;
3912}
3913
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003914status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003915 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003916 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003917 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003918 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003919
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003920 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003921
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003922 // Send errors for all requests pending in the request queue, including
3923 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003924 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003925 if (listener != NULL) {
3926 for (RequestList::iterator it = mRequestQueue.begin();
3927 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003928 // Abort the input buffers for reprocess requests.
3929 if ((*it)->mInputStream != NULL) {
3930 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003931 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3932 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003933 if (res != OK) {
3934 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3935 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3936 } else {
3937 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3938 if (res != OK) {
3939 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3940 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3941 }
3942 }
3943 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003944 // Set the frame number this request would have had, if it
3945 // had been submitted; this frame number will not be reused.
3946 // The requestId and burstId fields were set when the request was
3947 // submitted originally (in convertMetadataListToRequestListLocked)
3948 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003949 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003950 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003951 }
3952 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003953 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003954
3955 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003956 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003957 if (lastFrameNumber != NULL) {
3958 *lastFrameNumber = mRepeatingLastFrameNumber;
3959 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003960 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003961 return OK;
3962}
3963
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003964status_t Camera3Device::RequestThread::flush() {
3965 ATRACE_CALL();
3966 Mutex::Autolock l(mFlushLock);
3967
Emilian Peev08dd2452017-04-06 16:55:14 +01003968 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003969}
3970
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003971void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003972 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003973 Mutex::Autolock l(mPauseLock);
3974 mDoPause = paused;
3975 mDoPauseSignal.signal();
3976}
3977
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003978status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3979 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003980 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003981 Mutex::Autolock l(mLatestRequestMutex);
3982 status_t res;
3983 while (mLatestRequestId != requestId) {
3984 nsecs_t startTime = systemTime();
3985
3986 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3987 if (res != OK) return res;
3988
3989 timeout -= (systemTime() - startTime);
3990 }
3991
3992 return OK;
3993}
3994
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003995void Camera3Device::RequestThread::requestExit() {
3996 // Call parent to set up shutdown
3997 Thread::requestExit();
3998 // The exit from any possible waits
3999 mDoPauseSignal.signal();
4000 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004001
4002 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4003 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004004}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004005
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004006void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004007 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004008 bool surfaceAbandoned = false;
4009 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004010 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004011 {
4012 Mutex::Autolock l(mRequestLock);
4013 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4014 // repeating requests.
4015 for (const auto& request : mRepeatingRequests) {
4016 for (const auto& s : request->mOutputStreams) {
4017 if (s->isAbandoned()) {
4018 surfaceAbandoned = true;
4019 clearRepeatingRequestsLocked(&lastFrameNumber);
4020 break;
4021 }
4022 }
4023 if (surfaceAbandoned) {
4024 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004025 }
4026 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004027 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004028 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004029
4030 if (listener != NULL && surfaceAbandoned) {
4031 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004032 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004033}
4034
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004035bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004036 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004037 status_t res;
4038 size_t batchSize = mNextRequests.size();
4039 std::vector<camera3_capture_request_t*> requests(batchSize);
4040 uint32_t numRequestProcessed = 0;
4041 for (size_t i = 0; i < batchSize; i++) {
4042 requests[i] = &mNextRequests.editItemAt(i).halRequest;
4043 }
4044
4045 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
4046 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4047
4048 bool triggerRemoveFailed = false;
4049 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4050 for (size_t i = 0; i < numRequestProcessed; i++) {
4051 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4052 nextRequest.submitted = true;
4053
4054
4055 // Update the latest request sent to HAL
4056 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4057 Mutex::Autolock al(mLatestRequestMutex);
4058
4059 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4060 mLatestRequest.acquire(cloned);
4061
4062 sp<Camera3Device> parent = mParent.promote();
4063 if (parent != NULL) {
4064 parent->monitorMetadata(TagMonitor::REQUEST,
4065 nextRequest.halRequest.frame_number,
4066 0, mLatestRequest);
4067 }
4068 }
4069
4070 if (nextRequest.halRequest.settings != NULL) {
4071 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4072 }
4073
4074 if (!triggerRemoveFailed) {
4075 // Remove any previously queued triggers (after unlock)
4076 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4077 if (removeTriggerRes != OK) {
4078 triggerRemoveFailed = true;
4079 triggerFailedRequest = nextRequest;
4080 }
4081 }
4082 }
4083
4084 if (triggerRemoveFailed) {
4085 SET_ERR("RequestThread: Unable to remove triggers "
4086 "(capture request %d, HAL device: %s (%d)",
4087 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4088 cleanUpFailedRequests(/*sendRequestError*/ false);
4089 return false;
4090 }
4091
4092 if (res != OK) {
4093 // Should only get a failure here for malformed requests or device-level
4094 // errors, so consider all errors fatal. Bad metadata failures should
4095 // come through notify.
4096 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4097 mNextRequests[numRequestProcessed].halRequest.frame_number,
4098 strerror(-res), res);
4099 cleanUpFailedRequests(/*sendRequestError*/ false);
4100 return false;
4101 }
4102 return true;
4103}
4104
4105bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4106 status_t res;
4107
4108 for (auto& nextRequest : mNextRequests) {
4109 // Submit request and block until ready for next one
4110 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4111 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4112
4113 if (res != OK) {
4114 // Should only get a failure here for malformed requests or device-level
4115 // errors, so consider all errors fatal. Bad metadata failures should
4116 // come through notify.
4117 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4118 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4119 res);
4120 cleanUpFailedRequests(/*sendRequestError*/ false);
4121 return false;
4122 }
4123
4124 // Mark that the request has be submitted successfully.
4125 nextRequest.submitted = true;
4126
4127 // Update the latest request sent to HAL
4128 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4129 Mutex::Autolock al(mLatestRequestMutex);
4130
4131 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4132 mLatestRequest.acquire(cloned);
4133
4134 sp<Camera3Device> parent = mParent.promote();
4135 if (parent != NULL) {
4136 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4137 0, mLatestRequest);
4138 }
4139 }
4140
4141 if (nextRequest.halRequest.settings != NULL) {
4142 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4143 }
4144
4145 // Remove any previously queued triggers (after unlock)
4146 res = removeTriggers(mPrevRequest);
4147 if (res != OK) {
4148 SET_ERR("RequestThread: Unable to remove triggers "
4149 "(capture request %d, HAL device: %s (%d)",
4150 nextRequest.halRequest.frame_number, strerror(-res), res);
4151 cleanUpFailedRequests(/*sendRequestError*/ false);
4152 return false;
4153 }
4154 }
4155 return true;
4156}
4157
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004158nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4159 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4160 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4161 find_camera_metadata_ro_entry(request,
4162 ANDROID_CONTROL_AE_MODE,
4163 &e);
4164 if (e.count == 0) return maxExpectedDuration;
4165
4166 switch (e.data.u8[0]) {
4167 case ANDROID_CONTROL_AE_MODE_OFF:
4168 find_camera_metadata_ro_entry(request,
4169 ANDROID_SENSOR_EXPOSURE_TIME,
4170 &e);
4171 if (e.count > 0) {
4172 maxExpectedDuration = e.data.i64[0];
4173 }
4174 find_camera_metadata_ro_entry(request,
4175 ANDROID_SENSOR_FRAME_DURATION,
4176 &e);
4177 if (e.count > 0) {
4178 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4179 }
4180 break;
4181 default:
4182 find_camera_metadata_ro_entry(request,
4183 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4184 &e);
4185 if (e.count > 1) {
4186 maxExpectedDuration = 1e9 / e.data.u8[0];
4187 }
4188 break;
4189 }
4190
4191 return maxExpectedDuration;
4192}
4193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004194bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004195 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196 status_t res;
4197
4198 // Handle paused state.
4199 if (waitIfPaused()) {
4200 return true;
4201 }
4202
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004203 // Wait for the next batch of requests.
4204 waitForNextRequestBatch();
4205 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004206 return true;
4207 }
4208
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004209 // Get the latest request ID, if any
4210 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004211 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004212 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004213 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004214 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004215 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004216 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4217 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004218 }
4219
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004220 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004221 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 if (res == TIMED_OUT) {
4223 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004224 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004225 // Check if any stream is abandoned.
4226 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004227 return true;
4228 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004229 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004230 return false;
4231 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004232
Zhijun Hecc27e112013-10-03 16:12:43 -07004233 // Inform waitUntilRequestProcessed thread of a new request ID
4234 {
4235 Mutex::Autolock al(mLatestRequestMutex);
4236
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004237 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004238 mLatestRequestSignal.signal();
4239 }
4240
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004241 // Submit a batch of requests to HAL.
4242 // Use flush lock only when submitting multilple requests in a batch.
4243 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4244 // which may take a long time to finish so synchronizing flush() and
4245 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4246 // For now, only synchronize for high speed recording and we should figure something out for
4247 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004248 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004249
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004250 if (useFlushLock) {
4251 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004252 }
4253
Zhijun Hef0645c12016-08-02 00:58:11 -07004254 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004255 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004256
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004257 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004258 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004259 if (mInterface->supportBatchRequest()) {
4260 submitRequestSuccess = sendRequestsBatch();
4261 } else {
4262 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004263 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004264 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4265 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004266
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004267 if (useFlushLock) {
4268 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004269 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004270
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004271 // Unset as current request
4272 {
4273 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004274 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004275 }
4276
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004277 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004278}
4279
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004280status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004281 ATRACE_CALL();
4282
Shuzhen Wang4a472662017-02-26 23:29:04 -08004283 for (size_t i = 0; i < mNextRequests.size(); i++) {
4284 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004285 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4286 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4287 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4288
4289 // Prepare a request to HAL
4290 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4291
4292 // Insert any queued triggers (before metadata is locked)
4293 status_t res = insertTriggers(captureRequest);
4294
4295 if (res < 0) {
4296 SET_ERR("RequestThread: Unable to insert triggers "
4297 "(capture request %d, HAL device: %s (%d)",
4298 halRequest->frame_number, strerror(-res), res);
4299 return INVALID_OPERATION;
4300 }
4301 int triggerCount = res;
4302 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4303 mPrevTriggers = triggerCount;
4304
4305 // If the request is the same as last, or we had triggers last time
4306 if (mPrevRequest != captureRequest || triggersMixedIn) {
4307 /**
4308 * HAL workaround:
4309 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4310 */
4311 res = addDummyTriggerIds(captureRequest);
4312 if (res != OK) {
4313 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4314 "(capture request %d, HAL device: %s (%d)",
4315 halRequest->frame_number, strerror(-res), res);
4316 return INVALID_OPERATION;
4317 }
4318
4319 /**
4320 * The request should be presorted so accesses in HAL
4321 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4322 */
4323 captureRequest->mSettings.sort();
4324 halRequest->settings = captureRequest->mSettings.getAndLock();
4325 mPrevRequest = captureRequest;
4326 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4327
4328 IF_ALOGV() {
4329 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4330 find_camera_metadata_ro_entry(
4331 halRequest->settings,
4332 ANDROID_CONTROL_AF_TRIGGER,
4333 &e
4334 );
4335 if (e.count > 0) {
4336 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4337 __FUNCTION__,
4338 halRequest->frame_number,
4339 e.data.u8[0]);
4340 }
4341 }
4342 } else {
4343 // leave request.settings NULL to indicate 'reuse latest given'
4344 ALOGVV("%s: Request settings are REUSED",
4345 __FUNCTION__);
4346 }
4347
4348 uint32_t totalNumBuffers = 0;
4349
4350 // Fill in buffers
4351 if (captureRequest->mInputStream != NULL) {
4352 halRequest->input_buffer = &captureRequest->mInputBuffer;
4353 totalNumBuffers += 1;
4354 } else {
4355 halRequest->input_buffer = NULL;
4356 }
4357
4358 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4359 captureRequest->mOutputStreams.size());
4360 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004361 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4362 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004363
4364 // Prepare video buffers for high speed recording on the first video request.
4365 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4366 // Only try to prepare video stream on the first video request.
4367 mPrepareVideoStream = false;
4368
4369 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4370 while (res == NOT_ENOUGH_DATA) {
4371 res = outputStream->prepareNextBuffer();
4372 }
4373 if (res != OK) {
4374 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4375 __FUNCTION__, strerror(-res), res);
4376 outputStream->cancelPrepare();
4377 }
4378 }
4379
Shuzhen Wang4a472662017-02-26 23:29:04 -08004380 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4381 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004382 if (res != OK) {
4383 // Can't get output buffer from gralloc queue - this could be due to
4384 // abandoned queue or other consumer misbehavior, so not a fatal
4385 // error
4386 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4387 " %s (%d)", strerror(-res), res);
4388
4389 return TIMED_OUT;
4390 }
4391 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004392
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004393 }
4394 totalNumBuffers += halRequest->num_output_buffers;
4395
4396 // Log request in the in-flight queue
4397 sp<Camera3Device> parent = mParent.promote();
4398 if (parent == NULL) {
4399 // Should not happen, and nowhere to send errors to, so just log it
4400 CLOGE("RequestThread: Parent is gone");
4401 return INVALID_OPERATION;
4402 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004403
4404 // If this request list is for constrained high speed recording (not
4405 // preview), and the current request is not the last one in the batch,
4406 // do not send callback to the app.
4407 bool hasCallback = true;
4408 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4409 hasCallback = false;
4410 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004411 res = parent->registerInFlight(halRequest->frame_number,
4412 totalNumBuffers, captureRequest->mResultExtras,
4413 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004414 hasCallback,
4415 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004416 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4417 ", burstId = %" PRId32 ".",
4418 __FUNCTION__,
4419 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4420 captureRequest->mResultExtras.burstId);
4421 if (res != OK) {
4422 SET_ERR("RequestThread: Unable to register new in-flight request:"
4423 " %s (%d)", strerror(-res), res);
4424 return INVALID_OPERATION;
4425 }
4426 }
4427
4428 return OK;
4429}
4430
Igor Murashkin1e479c02013-09-06 16:55:14 -07004431CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004432 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004433 Mutex::Autolock al(mLatestRequestMutex);
4434
4435 ALOGV("RequestThread::%s", __FUNCTION__);
4436
4437 return mLatestRequest;
4438}
4439
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004440bool Camera3Device::RequestThread::isStreamPending(
4441 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004442 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004443 Mutex::Autolock l(mRequestLock);
4444
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004445 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004446 if (!nextRequest.submitted) {
4447 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4448 if (stream == s) return true;
4449 }
4450 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004451 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004452 }
4453
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004454 for (const auto& request : mRequestQueue) {
4455 for (const auto& s : request->mOutputStreams) {
4456 if (stream == s) return true;
4457 }
4458 if (stream == request->mInputStream) return true;
4459 }
4460
4461 for (const auto& request : mRepeatingRequests) {
4462 for (const auto& s : request->mOutputStreams) {
4463 if (stream == s) return true;
4464 }
4465 if (stream == request->mInputStream) return true;
4466 }
4467
4468 return false;
4469}
Jianing Weicb0652e2014-03-12 18:29:36 -07004470
Emilian Peev40ead602017-09-26 15:46:36 +01004471bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4472 ATRACE_CALL();
4473 Mutex::Autolock l(mRequestLock);
4474
4475 for (const auto& nextRequest : mNextRequests) {
4476 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4477 if (s.first == streamId) {
4478 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4479 if (it != s.second.end()) {
4480 return true;
4481 }
4482 }
4483 }
4484 }
4485
4486 for (const auto& request : mRequestQueue) {
4487 for (const auto& s : request->mOutputSurfaces) {
4488 if (s.first == streamId) {
4489 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4490 if (it != s.second.end()) {
4491 return true;
4492 }
4493 }
4494 }
4495 }
4496
4497 for (const auto& request : mRepeatingRequests) {
4498 for (const auto& s : request->mOutputSurfaces) {
4499 if (s.first == streamId) {
4500 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4501 if (it != s.second.end()) {
4502 return true;
4503 }
4504 }
4505 }
4506 }
4507
4508 return false;
4509}
4510
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004511nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004512 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004513 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004514 return mExpectedInflightDuration > kMinInflightDuration ?
4515 mExpectedInflightDuration : kMinInflightDuration;
4516}
4517
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004518void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4519 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004520 return;
4521 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004522
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004523 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004524 // Skip the ones that have been submitted successfully.
4525 if (nextRequest.submitted) {
4526 continue;
4527 }
4528
4529 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4530 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4531 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4532
4533 if (halRequest->settings != NULL) {
4534 captureRequest->mSettings.unlock(halRequest->settings);
4535 }
4536
4537 if (captureRequest->mInputStream != NULL) {
4538 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4539 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4540 }
4541
4542 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004543 //Buffers that failed processing could still have
4544 //valid acquire fence.
4545 int acquireFence = (*outputBuffers)[i].acquire_fence;
4546 if (0 <= acquireFence) {
4547 close(acquireFence);
4548 outputBuffers->editItemAt(i).acquire_fence = -1;
4549 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004550 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4551 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4552 }
4553
4554 if (sendRequestError) {
4555 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004556 sp<NotificationListener> listener = mListener.promote();
4557 if (listener != NULL) {
4558 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004559 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004560 captureRequest->mResultExtras);
4561 }
4562 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004563
4564 // Remove yet-to-be submitted inflight request from inflightMap
4565 {
4566 sp<Camera3Device> parent = mParent.promote();
4567 if (parent != NULL) {
4568 Mutex::Autolock l(parent->mInFlightLock);
4569 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4570 if (idx >= 0) {
4571 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4572 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4573 parent->removeInFlightMapEntryLocked(idx);
4574 }
4575 }
4576 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004577 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004578
4579 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004580 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004581}
4582
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004583void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004584 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004585 // Optimized a bit for the simple steady-state case (single repeating
4586 // request), to avoid putting that request in the queue temporarily.
4587 Mutex::Autolock l(mRequestLock);
4588
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004589 assert(mNextRequests.empty());
4590
4591 NextRequest nextRequest;
4592 nextRequest.captureRequest = waitForNextRequestLocked();
4593 if (nextRequest.captureRequest == nullptr) {
4594 return;
4595 }
4596
4597 nextRequest.halRequest = camera3_capture_request_t();
4598 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004599 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004600
4601 // Wait for additional requests
4602 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4603
4604 for (size_t i = 1; i < batchSize; i++) {
4605 NextRequest additionalRequest;
4606 additionalRequest.captureRequest = waitForNextRequestLocked();
4607 if (additionalRequest.captureRequest == nullptr) {
4608 break;
4609 }
4610
4611 additionalRequest.halRequest = camera3_capture_request_t();
4612 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004613 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004614 }
4615
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004616 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004617 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004618 mNextRequests.size(), batchSize);
4619 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004620 }
4621
4622 return;
4623}
4624
4625sp<Camera3Device::CaptureRequest>
4626 Camera3Device::RequestThread::waitForNextRequestLocked() {
4627 status_t res;
4628 sp<CaptureRequest> nextRequest;
4629
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004630 while (mRequestQueue.empty()) {
4631 if (!mRepeatingRequests.empty()) {
4632 // Always atomically enqueue all requests in a repeating request
4633 // list. Guarantees a complete in-sequence set of captures to
4634 // application.
4635 const RequestList &requests = mRepeatingRequests;
4636 RequestList::const_iterator firstRequest =
4637 requests.begin();
4638 nextRequest = *firstRequest;
4639 mRequestQueue.insert(mRequestQueue.end(),
4640 ++firstRequest,
4641 requests.end());
4642 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004643
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004644 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004645
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004646 break;
4647 }
4648
4649 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4650
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004651 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4652 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004653 Mutex::Autolock pl(mPauseLock);
4654 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004655 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004656 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004657 // Let the tracker know
4658 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4659 if (statusTracker != 0) {
4660 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4661 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004662 }
4663 // Stop waiting for now and let thread management happen
4664 return NULL;
4665 }
4666 }
4667
4668 if (nextRequest == NULL) {
4669 // Don't have a repeating request already in hand, so queue
4670 // must have an entry now.
4671 RequestList::iterator firstRequest =
4672 mRequestQueue.begin();
4673 nextRequest = *firstRequest;
4674 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004675 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4676 sp<NotificationListener> listener = mListener.promote();
4677 if (listener != NULL) {
4678 listener->notifyRequestQueueEmpty();
4679 }
4680 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004681 }
4682
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004683 // In case we've been unpaused by setPaused clearing mDoPause, need to
4684 // update internal pause state (capture/setRepeatingRequest unpause
4685 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004686 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004687 if (mPaused) {
4688 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4689 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4690 if (statusTracker != 0) {
4691 statusTracker->markComponentActive(mStatusId);
4692 }
4693 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004694 mPaused = false;
4695
4696 // Check if we've reconfigured since last time, and reset the preview
4697 // request if so. Can't use 'NULL request == repeat' across configure calls.
4698 if (mReconfigured) {
4699 mPrevRequest.clear();
4700 mReconfigured = false;
4701 }
4702
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004703 if (nextRequest != NULL) {
4704 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004705 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4706 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004707
4708 // Since RequestThread::clear() removes buffers from the input stream,
4709 // get the right buffer here before unlocking mRequestLock
4710 if (nextRequest->mInputStream != NULL) {
4711 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4712 if (res != OK) {
4713 // Can't get input buffer from gralloc queue - this could be due to
4714 // disconnected queue or other producer misbehavior, so not a fatal
4715 // error
4716 ALOGE("%s: Can't get input buffer, skipping request:"
4717 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004718
4719 sp<NotificationListener> listener = mListener.promote();
4720 if (listener != NULL) {
4721 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004722 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004723 nextRequest->mResultExtras);
4724 }
4725 return NULL;
4726 }
4727 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004728 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004729
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004730 return nextRequest;
4731}
4732
4733bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004734 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004735 status_t res;
4736 Mutex::Autolock l(mPauseLock);
4737 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004738 if (mPaused == false) {
4739 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004740 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4741 // Let the tracker know
4742 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4743 if (statusTracker != 0) {
4744 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4745 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004746 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004747
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004748 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004749 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004750 return true;
4751 }
4752 }
4753 // We don't set mPaused to false here, because waitForNextRequest needs
4754 // to further manage the paused state in case of starvation.
4755 return false;
4756}
4757
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004758void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004759 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004760 // With work to do, mark thread as unpaused.
4761 // If paused by request (setPaused), don't resume, to avoid
4762 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004763 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004764 Mutex::Autolock p(mPauseLock);
4765 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004766 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4767 if (mPaused) {
4768 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4769 if (statusTracker != 0) {
4770 statusTracker->markComponentActive(mStatusId);
4771 }
4772 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004773 mPaused = false;
4774 }
4775}
4776
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004777void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4778 sp<Camera3Device> parent = mParent.promote();
4779 if (parent != NULL) {
4780 va_list args;
4781 va_start(args, fmt);
4782
4783 parent->setErrorStateV(fmt, args);
4784
4785 va_end(args);
4786 }
4787}
4788
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004789status_t Camera3Device::RequestThread::insertTriggers(
4790 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004791 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004792 Mutex::Autolock al(mTriggerMutex);
4793
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004794 sp<Camera3Device> parent = mParent.promote();
4795 if (parent == NULL) {
4796 CLOGE("RequestThread: Parent is gone");
4797 return DEAD_OBJECT;
4798 }
4799
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004800 CameraMetadata &metadata = request->mSettings;
4801 size_t count = mTriggerMap.size();
4802
4803 for (size_t i = 0; i < count; ++i) {
4804 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004805 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004806
4807 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4808 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4809 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004810 if (isAeTrigger) {
4811 request->mResultExtras.precaptureTriggerId = triggerId;
4812 mCurrentPreCaptureTriggerId = triggerId;
4813 } else {
4814 request->mResultExtras.afTriggerId = triggerId;
4815 mCurrentAfTriggerId = triggerId;
4816 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004817 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004818 }
4819
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004820 camera_metadata_entry entry = metadata.find(tag);
4821
4822 if (entry.count > 0) {
4823 /**
4824 * Already has an entry for this trigger in the request.
4825 * Rewrite it with our requested trigger value.
4826 */
4827 RequestTrigger oldTrigger = trigger;
4828
4829 oldTrigger.entryValue = entry.data.u8[0];
4830
4831 mTriggerReplacedMap.add(tag, oldTrigger);
4832 } else {
4833 /**
4834 * More typical, no trigger entry, so we just add it
4835 */
4836 mTriggerRemovedMap.add(tag, trigger);
4837 }
4838
4839 status_t res;
4840
4841 switch (trigger.getTagType()) {
4842 case TYPE_BYTE: {
4843 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4844 res = metadata.update(tag,
4845 &entryValue,
4846 /*count*/1);
4847 break;
4848 }
4849 case TYPE_INT32:
4850 res = metadata.update(tag,
4851 &trigger.entryValue,
4852 /*count*/1);
4853 break;
4854 default:
4855 ALOGE("%s: Type not supported: 0x%x",
4856 __FUNCTION__,
4857 trigger.getTagType());
4858 return INVALID_OPERATION;
4859 }
4860
4861 if (res != OK) {
4862 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4863 ", value %d", __FUNCTION__, trigger.getTagName(),
4864 trigger.entryValue);
4865 return res;
4866 }
4867
4868 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4869 trigger.getTagName(),
4870 trigger.entryValue);
4871 }
4872
4873 mTriggerMap.clear();
4874
4875 return count;
4876}
4877
4878status_t Camera3Device::RequestThread::removeTriggers(
4879 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004880 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004881 Mutex::Autolock al(mTriggerMutex);
4882
4883 CameraMetadata &metadata = request->mSettings;
4884
4885 /**
4886 * Replace all old entries with their old values.
4887 */
4888 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4889 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4890
4891 status_t res;
4892
4893 uint32_t tag = trigger.metadataTag;
4894 switch (trigger.getTagType()) {
4895 case TYPE_BYTE: {
4896 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4897 res = metadata.update(tag,
4898 &entryValue,
4899 /*count*/1);
4900 break;
4901 }
4902 case TYPE_INT32:
4903 res = metadata.update(tag,
4904 &trigger.entryValue,
4905 /*count*/1);
4906 break;
4907 default:
4908 ALOGE("%s: Type not supported: 0x%x",
4909 __FUNCTION__,
4910 trigger.getTagType());
4911 return INVALID_OPERATION;
4912 }
4913
4914 if (res != OK) {
4915 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4916 ", trigger value %d", __FUNCTION__,
4917 trigger.getTagName(), trigger.entryValue);
4918 return res;
4919 }
4920 }
4921 mTriggerReplacedMap.clear();
4922
4923 /**
4924 * Remove all new entries.
4925 */
4926 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4927 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4928 status_t res = metadata.erase(trigger.metadataTag);
4929
4930 if (res != OK) {
4931 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4932 ", trigger value %d", __FUNCTION__,
4933 trigger.getTagName(), trigger.entryValue);
4934 return res;
4935 }
4936 }
4937 mTriggerRemovedMap.clear();
4938
4939 return OK;
4940}
4941
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004942status_t Camera3Device::RequestThread::addDummyTriggerIds(
4943 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004944 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004945 static const int32_t dummyTriggerId = 1;
4946 status_t res;
4947
4948 CameraMetadata &metadata = request->mSettings;
4949
4950 // If AF trigger is active, insert a dummy AF trigger ID if none already
4951 // exists
4952 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4953 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4954 if (afTrigger.count > 0 &&
4955 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4956 afId.count == 0) {
4957 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4958 if (res != OK) return res;
4959 }
4960
4961 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4962 // if none already exists
4963 camera_metadata_entry pcTrigger =
4964 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4965 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4966 if (pcTrigger.count > 0 &&
4967 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4968 pcId.count == 0) {
4969 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4970 &dummyTriggerId, 1);
4971 if (res != OK) return res;
4972 }
4973
4974 return OK;
4975}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004976
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004977/**
4978 * PreparerThread inner class methods
4979 */
4980
4981Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004982 Thread(/*canCallJava*/false), mListener(nullptr),
4983 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004984}
4985
4986Camera3Device::PreparerThread::~PreparerThread() {
4987 Thread::requestExitAndWait();
4988 if (mCurrentStream != nullptr) {
4989 mCurrentStream->cancelPrepare();
4990 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4991 mCurrentStream.clear();
4992 }
4993 clear();
4994}
4995
Ruben Brunkc78ac262015-08-13 17:58:46 -07004996status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004997 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004998 status_t res;
4999
5000 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005001 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005002
Ruben Brunkc78ac262015-08-13 17:58:46 -07005003 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004 if (res == OK) {
5005 // No preparation needed, fire listener right off
5006 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005007 if (listener != NULL) {
5008 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005009 }
5010 return OK;
5011 } else if (res != NOT_ENOUGH_DATA) {
5012 return res;
5013 }
5014
5015 // Need to prepare, start up thread if necessary
5016 if (!mActive) {
5017 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5018 // isn't running
5019 Thread::requestExitAndWait();
5020 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5021 if (res != OK) {
5022 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005023 if (listener != NULL) {
5024 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005025 }
5026 return res;
5027 }
5028 mCancelNow = false;
5029 mActive = true;
5030 ALOGV("%s: Preparer stream started", __FUNCTION__);
5031 }
5032
5033 // queue up the work
5034 mPendingStreams.push_back(stream);
5035 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5036
5037 return OK;
5038}
5039
5040status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005041 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005042 Mutex::Autolock l(mLock);
5043
5044 for (const auto& stream : mPendingStreams) {
5045 stream->cancelPrepare();
5046 }
5047 mPendingStreams.clear();
5048 mCancelNow = true;
5049
5050 return OK;
5051}
5052
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005053void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005054 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005055 Mutex::Autolock l(mLock);
5056 mListener = listener;
5057}
5058
5059bool Camera3Device::PreparerThread::threadLoop() {
5060 status_t res;
5061 {
5062 Mutex::Autolock l(mLock);
5063 if (mCurrentStream == nullptr) {
5064 // End thread if done with work
5065 if (mPendingStreams.empty()) {
5066 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5067 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5068 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5069 mActive = false;
5070 return false;
5071 }
5072
5073 // Get next stream to prepare
5074 auto it = mPendingStreams.begin();
5075 mCurrentStream = *it;
5076 mPendingStreams.erase(it);
5077 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5078 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5079 } else if (mCancelNow) {
5080 mCurrentStream->cancelPrepare();
5081 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5082 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5083 mCurrentStream.clear();
5084 mCancelNow = false;
5085 return true;
5086 }
5087 }
5088
5089 res = mCurrentStream->prepareNextBuffer();
5090 if (res == NOT_ENOUGH_DATA) return true;
5091 if (res != OK) {
5092 // Something bad happened; try to recover by cancelling prepare and
5093 // signalling listener anyway
5094 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5095 mCurrentStream->getId(), res, strerror(-res));
5096 mCurrentStream->cancelPrepare();
5097 }
5098
5099 // This stream has finished, notify listener
5100 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005101 sp<NotificationListener> listener = mListener.promote();
5102 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005103 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5104 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005105 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005106 }
5107
5108 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5109 mCurrentStream.clear();
5110
5111 return true;
5112}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005113
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005114/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005115 * Static callback forwarding methods from HAL to instance
5116 */
5117
5118void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5119 const camera3_capture_result *result) {
5120 Camera3Device *d =
5121 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005122
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005123 d->processCaptureResult(result);
5124}
5125
5126void Camera3Device::sNotify(const camera3_callback_ops *cb,
5127 const camera3_notify_msg *msg) {
5128 Camera3Device *d =
5129 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5130 d->notify(msg);
5131}
5132
5133}; // namespace android