blob: 0fc374084546e567a2cbea04f982067321cfac5a [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000077 mListener(NULL),
78 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080079{
80 ATRACE_CALL();
81 camera3_callback_ops::notify = &sNotify;
82 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080083 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084}
85
86Camera3Device::~Camera3Device()
87{
88 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080089 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080090 disconnect();
91}
92
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080094 return mId;
95}
96
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080097status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
98 ATRACE_CALL();
99 Mutex::Autolock il(mInterfaceLock);
100 Mutex::Autolock l(mLock);
101
102 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
103 if (mStatus != STATUS_UNINITIALIZED) {
104 CLOGE("Already initialized!");
105 return INVALID_OPERATION;
106 }
107 if (manager == nullptr) return INVALID_OPERATION;
108
109 sp<ICameraDeviceSession> session;
110 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800111 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112 /*out*/ &session);
113 ATRACE_END();
114 if (res != OK) {
115 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
116 return res;
117 }
118
Steven Moreland5ff9c912017-03-09 23:13:00 -0800119 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 if (res != OK) {
121 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
122 session->close();
123 return res;
124 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800125
Yifan Hongf79b5542017-04-11 14:44:25 -0700126 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700127 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
128 [&queue](const auto& descriptor) {
129 queue = std::make_shared<RequestMetadataQueue>(descriptor);
130 if (!queue->isValid() || queue->availableToWrite() <= 0) {
131 ALOGE("HAL returns empty request metadata fmq, not use it");
132 queue = nullptr;
133 // don't use the queue onwards.
134 }
135 });
136 if (!requestQueueRet.isOk()) {
137 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
138 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700139 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700140 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700141
142 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700144 [&resQueue](const auto& descriptor) {
145 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
146 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700147 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700148 resQueue = nullptr;
149 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700150 }
151 });
152 if (!resultQueueRet.isOk()) {
153 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
154 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700156 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700157
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700158 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000159 std::string providerType;
160 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800161
162 return initializeCommonLocked();
163}
164
165status_t Camera3Device::initializeCommonLocked() {
166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700167 /** Start up status tracker thread */
168 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800169 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700170 if (res != OK) {
171 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
172 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700174 mStatusTracker.clear();
175 return res;
176 }
177
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700178 /** Register in-flight map to the status tracker */
179 mInFlightStatusId = mStatusTracker->addComponent();
180
Zhijun He125684a2015-12-26 15:07:30 -0800181 /** Create buffer manager */
182 mBufferManager = new Camera3BufferManager();
183
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 mTagMonitor.initialize(mVendorTagId);
185
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700186 /** Start up request queue thread */
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700187 mRequestThread = new RequestThread(this, mStatusTracker, mInterface);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700190 SET_ERR_L("Unable to start request queue thread: %s (%d)",
191 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800192 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800193 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800194 return res;
195 }
196
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700197 mPreparerThread = new PreparerThread();
198
Ruben Brunk183f0562015-08-12 12:55:02 -0700199 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800200 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700201 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700202 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800204
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800205 // Measure the clock domain offset between camera and video/hw_composer
206 camera_metadata_entry timestampSource =
207 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
208 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
209 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
210 mTimestampOffset = getMonoToBoottimeOffset();
211 }
212
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700213 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100214 camera_metadata_entry partialResultsCount =
215 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
216 if (partialResultsCount.count > 0) {
217 mNumPartialResults = partialResultsCount.data.i32[0];
218 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700219 }
220
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700221 camera_metadata_entry configs =
222 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
223 for (uint32_t i = 0; i < configs.count; i += 4) {
224 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
225 configs.data.i32[i + 3] ==
226 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
227 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
228 configs.data.i32[i + 2]));
229 }
230 }
231
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800232 return OK;
233}
234
235status_t Camera3Device::disconnect() {
236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800238
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700239 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800240
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700241 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700242 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700243 {
244 Mutex::Autolock l(mLock);
245 if (mStatus == STATUS_UNINITIALIZED) return res;
246
247 if (mStatus == STATUS_ACTIVE ||
248 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
249 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700254 nsecs_t maxExpectedDuration = getExpectedInFlightDurationLocked();
255 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700257 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
258 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700259 // Continue to close device even in case of error
260 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700261 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800262 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800263
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 if (mStatus == STATUS_ERROR) {
265 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700266 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267
268 if (mStatusTracker != NULL) {
269 mStatusTracker->requestExit();
270 }
271
272 if (mRequestThread != NULL) {
273 mRequestThread->requestExit();
274 }
275
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700276 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
277 for (size_t i = 0; i < mOutputStreams.size(); i++) {
278 streams.push_back(mOutputStreams[i]);
279 }
280 if (mInputStream != nullptr) {
281 streams.push_back(mInputStream);
282 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700283 }
284
285 // Joining done without holding mLock, otherwise deadlocks may ensue
286 // as the threads try to access parent state
287 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
288 // HAL may be in a bad state, so waiting for request thread
289 // (which may be stuck in the HAL processCaptureRequest call)
290 // could be dangerous.
291 mRequestThread->join();
292 }
293
294 if (mStatusTracker != NULL) {
295 mStatusTracker->join();
296 }
297
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800298 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299 {
300 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800301 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800303 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700306 // Call close without internal mutex held, as the HAL close may need to
307 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800308 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700309
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700310 flushInflightRequests();
311
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700312 {
313 Mutex::Autolock l(mLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700314 mExpectedInflightDuration = 0;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800315 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700316 mOutputStreams.clear();
317 mInputStream.clear();
318 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700319 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800321
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700322 for (auto& weakStream : streams) {
323 sp<Camera3StreamInterface> stream = weakStream.promote();
324 if (stream != nullptr) {
325 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
326 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
327 }
328 }
329
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700330 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700331 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800332}
333
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700334// For dumping/debugging only -
335// try to acquire a lock a few times, eventually give up to proceed with
336// debug/dump operations
337bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
338 bool gotLock = false;
339 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
340 if (lock.tryLock() == NO_ERROR) {
341 gotLock = true;
342 break;
343 } else {
344 usleep(kDumpSleepDuration);
345 }
346 }
347 return gotLock;
348}
349
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700350Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
351 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100352 const int STREAM_CONFIGURATION_SIZE = 4;
353 const int STREAM_FORMAT_OFFSET = 0;
354 const int STREAM_WIDTH_OFFSET = 1;
355 const int STREAM_HEIGHT_OFFSET = 2;
356 const int STREAM_IS_INPUT_OFFSET = 3;
357 camera_metadata_ro_entry_t availableStreamConfigs =
358 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
359 if (availableStreamConfigs.count == 0 ||
360 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
361 return Size(0, 0);
362 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700363
Emilian Peev08dd2452017-04-06 16:55:14 +0100364 // Get max jpeg size (area-wise).
365 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
366 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
367 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
368 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
369 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
370 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
371 && format == HAL_PIXEL_FORMAT_BLOB &&
372 (width * height > maxJpegWidth * maxJpegHeight)) {
373 maxJpegWidth = width;
374 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700375 }
376 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100377
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700378 return Size(maxJpegWidth, maxJpegHeight);
379}
380
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800381nsecs_t Camera3Device::getMonoToBoottimeOffset() {
382 // try three times to get the clock offset, choose the one
383 // with the minimum gap in measurements.
384 const int tries = 3;
385 nsecs_t bestGap, measured;
386 for (int i = 0; i < tries; ++i) {
387 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
388 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
389 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
390 const nsecs_t gap = tmono2 - tmono;
391 if (i == 0 || gap < bestGap) {
392 bestGap = gap;
393 measured = tbase - ((tmono + tmono2) >> 1);
394 }
395 }
396 return measured;
397}
398
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800399hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
400 int frameworkFormat) {
401 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
402}
403
404DataspaceFlags Camera3Device::mapToHidlDataspace(
405 android_dataspace dataSpace) {
406 return dataSpace;
407}
408
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700409BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700410 uint32_t usage) {
411 return usage;
412}
413
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800414StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
415 switch (rotation) {
416 case CAMERA3_STREAM_ROTATION_0:
417 return StreamRotation::ROTATION_0;
418 case CAMERA3_STREAM_ROTATION_90:
419 return StreamRotation::ROTATION_90;
420 case CAMERA3_STREAM_ROTATION_180:
421 return StreamRotation::ROTATION_180;
422 case CAMERA3_STREAM_ROTATION_270:
423 return StreamRotation::ROTATION_270;
424 }
425 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
426 return StreamRotation::ROTATION_0;
427}
428
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800429status_t Camera3Device::mapToStreamConfigurationMode(
430 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
431 if (mode == nullptr) return BAD_VALUE;
432 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
433 switch(operationMode) {
434 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
435 *mode = StreamConfigurationMode::NORMAL_MODE;
436 break;
437 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
438 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
439 break;
440 default:
441 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
442 return BAD_VALUE;
443 }
444 } else {
445 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800446 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800447 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800448}
449
450camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
451 switch (status) {
452 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
453 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
454 }
455 return CAMERA3_BUFFER_STATUS_ERROR;
456}
457
458int Camera3Device::mapToFrameworkFormat(
459 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
460 return static_cast<uint32_t>(pixelFormat);
461}
462
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700463uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700464 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700465 return usage;
466}
467
468uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700469 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700470 return usage;
471}
472
Zhijun Hef7da0962014-04-24 13:27:56 -0700473ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700474 // Get max jpeg size (area-wise).
475 Size maxJpegResolution = getMaxJpegResolution();
476 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800477 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
478 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700479 return BAD_VALUE;
480 }
481
Zhijun Hef7da0962014-04-24 13:27:56 -0700482 // Get max jpeg buffer size
483 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
485 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800486 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
487 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700488 return BAD_VALUE;
489 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700490 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800491 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700492
493 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700494 float scaleFactor = ((float) (width * height)) /
495 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800496 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
497 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700498 if (jpegBufferSize > maxJpegBufferSize) {
499 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700500 }
501
502 return jpegBufferSize;
503}
504
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700505ssize_t Camera3Device::getPointCloudBufferSize() const {
506 const int FLOATS_PER_POINT=4;
507 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
508 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800509 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
510 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700511 return BAD_VALUE;
512 }
513 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
514 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
515 return maxBytesForPointCloud;
516}
517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800518ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800519 const int PER_CONFIGURATION_SIZE = 3;
520 const int WIDTH_OFFSET = 0;
521 const int HEIGHT_OFFSET = 1;
522 const int SIZE_OFFSET = 2;
523 camera_metadata_ro_entry rawOpaqueSizes =
524 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800525 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800526 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800527 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
528 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800529 return BAD_VALUE;
530 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700531
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800532 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
533 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
534 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
535 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
536 }
537 }
538
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800539 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
540 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800541 return BAD_VALUE;
542}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700543
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800544status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
545 ATRACE_CALL();
546 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700547
548 // Try to lock, but continue in case of failure (to avoid blocking in
549 // deadlocks)
550 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
551 bool gotLock = tryLockSpinRightRound(mLock);
552
553 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
555 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700556 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
558 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700559
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800560 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700561
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800562 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700563 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800564 int n = args.size();
565 for (int i = 0; i < n; i++) {
566 if (args[i] == templatesOption) {
567 dumpTemplates = true;
568 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700569 if (args[i] == monitorOption) {
570 if (i + 1 < n) {
571 String8 monitorTags = String8(args[i + 1]);
572 if (monitorTags == "off") {
573 mTagMonitor.disableMonitoring();
574 } else {
575 mTagMonitor.parseTagsToMonitor(monitorTags);
576 }
577 } else {
578 mTagMonitor.disableMonitoring();
579 }
580 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800581 }
582
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800583 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800584
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800585 const char *status =
586 mStatus == STATUS_ERROR ? "ERROR" :
587 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700588 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
589 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800590 mStatus == STATUS_ACTIVE ? "ACTIVE" :
591 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800593 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700594 if (mStatus == STATUS_ERROR) {
595 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
596 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800597 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800598 const char *mode =
599 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
600 mOperatingMode == static_cast<int>(
601 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
602 "CUSTOM";
603 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800604
605 if (mInputStream != NULL) {
606 write(fd, lines.string(), lines.size());
607 mInputStream->dump(fd, args);
608 } else {
609 lines.appendFormat(" No input stream.\n");
610 write(fd, lines.string(), lines.size());
611 }
612 for (size_t i = 0; i < mOutputStreams.size(); i++) {
613 mOutputStreams[i]->dump(fd,args);
614 }
615
Zhijun He431503c2016-03-07 17:30:16 -0800616 if (mBufferManager != NULL) {
617 lines = String8(" Camera3 Buffer Manager:\n");
618 write(fd, lines.string(), lines.size());
619 mBufferManager->dump(fd, args);
620 }
Zhijun He125684a2015-12-26 15:07:30 -0800621
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700622 lines = String8(" In-flight requests:\n");
623 if (mInFlightMap.size() == 0) {
624 lines.append(" None\n");
625 } else {
626 for (size_t i = 0; i < mInFlightMap.size(); i++) {
627 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700628 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700629 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800630 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700631 r.numBuffersLeft);
632 }
633 }
634 write(fd, lines.string(), lines.size());
635
Shuzhen Wang686f6442017-06-20 16:16:04 -0700636 if (mRequestThread != NULL) {
637 mRequestThread->dumpCaptureRequestLatency(fd,
638 " ProcessCaptureRequest latency histogram:");
639 }
640
Igor Murashkin1e479c02013-09-06 16:55:14 -0700641 {
642 lines = String8(" Last request sent:\n");
643 write(fd, lines.string(), lines.size());
644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700646 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
647 }
648
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800649 if (dumpTemplates) {
650 const char *templateNames[] = {
651 "TEMPLATE_PREVIEW",
652 "TEMPLATE_STILL_CAPTURE",
653 "TEMPLATE_VIDEO_RECORD",
654 "TEMPLATE_VIDEO_SNAPSHOT",
655 "TEMPLATE_ZERO_SHUTTER_LAG",
656 "TEMPLATE_MANUAL"
657 };
658
659 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800660 camera_metadata_t *templateRequest = nullptr;
661 mInterface->constructDefaultRequestSettings(
662 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800663 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800664 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800665 lines.append(" Not supported\n");
666 write(fd, lines.string(), lines.size());
667 } else {
668 write(fd, lines.string(), lines.size());
669 dump_indented_camera_metadata(templateRequest,
670 fd, /*verbosity*/2, /*indentation*/8);
671 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 }
674 }
675
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700676 mTagMonitor.dumpMonitoredMetadata(fd);
677
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800678 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800679 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800681 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800683
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700684 if (gotLock) mLock.unlock();
685 if (gotInterfaceLock) mInterfaceLock.unlock();
686
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800687 return OK;
688}
689
690const CameraMetadata& Camera3Device::info() const {
691 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800692 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
693 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700694 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800695 mStatus == STATUS_ERROR ?
696 "when in error state" : "before init");
697 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800698 return mDeviceInfo;
699}
700
Jianing Wei90e59c92014-03-12 18:29:36 -0700701status_t Camera3Device::checkStatusOkToCaptureLocked() {
702 switch (mStatus) {
703 case STATUS_ERROR:
704 CLOGE("Device has encountered a serious error");
705 return INVALID_OPERATION;
706 case STATUS_UNINITIALIZED:
707 CLOGE("Device not initialized");
708 return INVALID_OPERATION;
709 case STATUS_UNCONFIGURED:
710 case STATUS_CONFIGURED:
711 case STATUS_ACTIVE:
712 // OK
713 break;
714 default:
715 SET_ERR_L("Unexpected status: %d", mStatus);
716 return INVALID_OPERATION;
717 }
718 return OK;
719}
720
721status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700722 const List<const CameraMetadata> &metadataList,
723 const std::list<const SurfaceMap> &surfaceMaps,
724 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700725 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700726 if (requestList == NULL) {
727 CLOGE("requestList cannot be NULL.");
728 return BAD_VALUE;
729 }
730
Jianing Weicb0652e2014-03-12 18:29:36 -0700731 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700732 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
733 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
734 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
735 ++metadataIt, ++surfaceMapIt) {
736 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700737 if (newRequest == 0) {
738 CLOGE("Can't create capture request");
739 return BAD_VALUE;
740 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700741
Shuzhen Wang9d066012016-09-30 11:30:20 -0700742 newRequest->mRepeating = repeating;
743
Jianing Weicb0652e2014-03-12 18:29:36 -0700744 // Setup burst Id and request Id
745 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
747 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700748 CLOGE("RequestID entry exists; but must not be empty in metadata");
749 return BAD_VALUE;
750 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700752 } else {
753 CLOGE("RequestID does not exist in metadata");
754 return BAD_VALUE;
755 }
756
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700758
759 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700760 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
762 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
763 return BAD_VALUE;
764 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700765
766 // Setup batch size if this is a high speed video recording request.
767 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
768 auto firstRequest = requestList->begin();
769 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
770 if (outputStream->isVideoStream()) {
771 (*firstRequest)->mBatchSize = requestList->size();
772 break;
773 }
774 }
775 }
776
Jianing Wei90e59c92014-03-12 18:29:36 -0700777 return OK;
778}
779
Jianing Weicb0652e2014-03-12 18:29:36 -0700780status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800781 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800782
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700783 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 std::list<const SurfaceMap> surfaceMaps;
785 convertToRequestList(requests, surfaceMaps, request);
786
787 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
788}
789
790void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
791 std::list<const SurfaceMap>& surfaceMaps,
792 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700793 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794
795 SurfaceMap surfaceMap;
796 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
797 // With no surface list passed in, stream and surface will have 1-to-1
798 // mapping. So the surface index is 0 for each stream in the surfaceMap.
799 for (size_t i = 0; i < streams.count; i++) {
800 surfaceMap[streams.data.i32[i]].push_back(0);
801 }
802 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800803}
804
Jianing Wei90e59c92014-03-12 18:29:36 -0700805status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 const List<const CameraMetadata> &requests,
807 const std::list<const SurfaceMap> &surfaceMaps,
808 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700809 /*out*/
810 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 ATRACE_CALL();
812 Mutex::Autolock il(mInterfaceLock);
813 Mutex::Autolock l(mLock);
814
815 status_t res = checkStatusOkToCaptureLocked();
816 if (res != OK) {
817 // error logged by previous call
818 return res;
819 }
820
821 RequestList requestList;
822
Shuzhen Wang0129d522016-10-30 22:43:41 -0700823 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
824 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 if (res != OK) {
826 // error logged by previous call
827 return res;
828 }
829
830 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700831 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700832 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700833 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
835
836 if (res == OK) {
837 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
838 if (res != OK) {
839 SET_ERR_L("Can't transition to active in %f seconds!",
840 kActiveTimeout/1e9);
841 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800842 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700843 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 } else {
845 CLOGE("Cannot queue request. Impossible.");
846 return BAD_VALUE;
847 }
848
849 return res;
850}
851
Yifan Honga640c5a2017-04-12 16:30:31 -0700852// Only one processCaptureResult should be called at a time, so
853// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800854hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800855 const hardware::hidl_vec<
856 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700857 // Ideally we should grab mLock, but that can lead to deadlock, and
858 // it's not super important to get up to date value of mStatus for this
859 // warning print, hence skipping the lock here
860 if (mStatus == STATUS_ERROR) {
861 // Per API contract, HAL should act as closed after device error
862 // But mStatus can be set to error by framework as well, so just log
863 // a warning here.
864 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700865 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700866
867 if (mProcessCaptureResultLock.tryLock() != OK) {
868 // This should never happen; it indicates a wrong client implementation
869 // that doesn't follow the contract. But, we can be tolerant here.
870 ALOGE("%s: callback overlapped! waiting 1s...",
871 __FUNCTION__);
872 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
873 ALOGE("%s: cannot acquire lock in 1s, dropping results",
874 __FUNCTION__);
875 // really don't know what to do, so bail out.
876 return hardware::Void();
877 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800878 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700879 for (const auto& result : results) {
880 processOneCaptureResultLocked(result);
881 }
882 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800883 return hardware::Void();
884}
885
Yifan Honga640c5a2017-04-12 16:30:31 -0700886void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800887 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800888 camera3_capture_result r;
889 status_t res;
890 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700891
892 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
893 if (result.fmqResultSize > 0) {
894 resultMetadata.resize(result.fmqResultSize);
895 if (mResultMetadataQueue == nullptr) {
896 return; // logged in initialize()
897 }
898 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
899 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
900 __FUNCTION__, result.frameNumber, result.fmqResultSize);
901 return;
902 }
903 } else {
904 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
905 result.result.size());
906 }
907
908 if (resultMetadata.size() != 0) {
909 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
910 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800911 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
912 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
913 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800914 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800915 }
916 } else {
917 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 }
919
920 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
921 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
922 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
923 auto& bDst = outputBuffers[i];
924 const StreamBuffer &bSrc = result.outputBuffers[i];
925
926 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100927 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800928 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
929 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800930 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 }
932 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
933
934 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800935 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 if (res != OK) {
937 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
938 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800939 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 }
941 bDst.buffer = buffer;
942 bDst.status = mapHidlBufferStatus(bSrc.status);
943 bDst.acquire_fence = -1;
944 if (bSrc.releaseFence == nullptr) {
945 bDst.release_fence = -1;
946 } else if (bSrc.releaseFence->numFds == 1) {
947 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
948 } else {
949 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
950 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800951 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 }
953 }
954 r.num_output_buffers = outputBuffers.size();
955 r.output_buffers = outputBuffers.data();
956
957 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800958 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800959 r.input_buffer = nullptr;
960 } else {
961 if (mInputStream->getId() != result.inputBuffer.streamId) {
962 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
963 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800964 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800965 }
966 inputBuffer.stream = mInputStream->asHalStream();
967 buffer_handle_t *buffer;
968 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
969 &buffer);
970 if (res != OK) {
971 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
972 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800973 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800974 }
975 inputBuffer.buffer = buffer;
976 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
977 inputBuffer.acquire_fence = -1;
978 if (result.inputBuffer.releaseFence == nullptr) {
979 inputBuffer.release_fence = -1;
980 } else if (result.inputBuffer.releaseFence->numFds == 1) {
981 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
982 } else {
983 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
984 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800985 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 }
987 r.input_buffer = &inputBuffer;
988 }
989
990 r.partial_result = result.partialResult;
991
992 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800993}
994
995hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800996 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700997 // Ideally we should grab mLock, but that can lead to deadlock, and
998 // it's not super important to get up to date value of mStatus for this
999 // warning print, hence skipping the lock here
1000 if (mStatus == STATUS_ERROR) {
1001 // Per API contract, HAL should act as closed after device error
1002 // But mStatus can be set to error by framework as well, so just log
1003 // a warning here.
1004 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001005 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001006
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001007 for (const auto& msg : msgs) {
1008 notify(msg);
1009 }
1010 return hardware::Void();
1011}
1012
1013void Camera3Device::notify(
1014 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1015
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 camera3_notify_msg m;
1017 switch (msg.type) {
1018 case MsgType::ERROR:
1019 m.type = CAMERA3_MSG_ERROR;
1020 m.message.error.frame_number = msg.msg.error.frameNumber;
1021 if (msg.msg.error.errorStreamId >= 0) {
1022 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001023 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001024 ALOGE("%s: Frame %d: Invalid error stream id %d",
1025 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001026 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001027 }
1028 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1029 } else {
1030 m.message.error.error_stream = nullptr;
1031 }
1032 switch (msg.msg.error.errorCode) {
1033 case ErrorCode::ERROR_DEVICE:
1034 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1035 break;
1036 case ErrorCode::ERROR_REQUEST:
1037 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1038 break;
1039 case ErrorCode::ERROR_RESULT:
1040 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1041 break;
1042 case ErrorCode::ERROR_BUFFER:
1043 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1044 break;
1045 }
1046 break;
1047 case MsgType::SHUTTER:
1048 m.type = CAMERA3_MSG_SHUTTER;
1049 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1050 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1051 break;
1052 }
1053 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001054}
1055
Jianing Weicb0652e2014-03-12 18:29:36 -07001056status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001057 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001058 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001059 ATRACE_CALL();
1060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001062}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001063
Jianing Weicb0652e2014-03-12 18:29:36 -07001064status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1065 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001066 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001067
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001068 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001069 std::list<const SurfaceMap> surfaceMaps;
1070 convertToRequestList(requests, surfaceMaps, request);
1071
1072 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1073 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074}
1075
Jianing Weicb0652e2014-03-12 18:29:36 -07001076status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001078 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001079 ATRACE_CALL();
1080
Shuzhen Wang0129d522016-10-30 22:43:41 -07001081 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001082}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083
1084sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001085 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001086 status_t res;
1087
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001088 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001089 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1090 // so unilaterally select normal operating mode.
1091 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001092 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001094 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001095 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001096 } else if (mStatus == STATUS_UNCONFIGURED) {
1097 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001098 CLOGE("No streams configured");
1099 return NULL;
1100 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001101 }
1102
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105}
1106
Jianing Weicb0652e2014-03-12 18:29:36 -07001107status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001108 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001109 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001110 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001111
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001112 switch (mStatus) {
1113 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001114 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 return INVALID_OPERATION;
1116 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001117 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001119 case STATUS_UNCONFIGURED:
1120 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 case STATUS_ACTIVE:
1122 // OK
1123 break;
1124 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001125 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 return INVALID_OPERATION;
1127 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001128 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001129
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001130 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001131}
1132
1133status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1134 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001136
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001137 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001138}
1139
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001140status_t Camera3Device::createInputStream(
1141 uint32_t width, uint32_t height, int format, int *id) {
1142 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001143 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001144 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001145 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1146 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001147
1148 status_t res;
1149 bool wasActive = false;
1150
1151 switch (mStatus) {
1152 case STATUS_ERROR:
1153 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1154 return INVALID_OPERATION;
1155 case STATUS_UNINITIALIZED:
1156 ALOGE("%s: Device not initialized", __FUNCTION__);
1157 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001158 case STATUS_UNCONFIGURED:
1159 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001160 // OK
1161 break;
1162 case STATUS_ACTIVE:
1163 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001164 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001165 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001166 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001167 return res;
1168 }
1169 wasActive = true;
1170 break;
1171 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001173 return INVALID_OPERATION;
1174 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001175 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001176
1177 if (mInputStream != 0) {
1178 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1179 return INVALID_OPERATION;
1180 }
1181
1182 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1183 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001185
1186 mInputStream = newStream;
1187
1188 *id = mNextStreamId++;
1189
1190 // Continue captures if active at start
1191 if (wasActive) {
1192 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001193 // Reuse current operating mode for new stream config
1194 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001195 if (res != OK) {
1196 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1197 __FUNCTION__, mNextStreamId, strerror(-res), res);
1198 return res;
1199 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001201 }
1202
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001203 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001204 return OK;
1205}
1206
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001207status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001208 uint32_t width, uint32_t height, int format,
1209 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001210 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 ATRACE_CALL();
1212
1213 if (consumer == nullptr) {
1214 ALOGE("%s: consumer must not be null", __FUNCTION__);
1215 return BAD_VALUE;
1216 }
1217
1218 std::vector<sp<Surface>> consumers;
1219 consumers.push_back(consumer);
1220
1221 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001222 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001223}
1224
1225status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1226 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1227 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001228 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001229 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001230 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001232 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001233 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1234 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001235
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 status_t res;
1237 bool wasActive = false;
1238
1239 switch (mStatus) {
1240 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001244 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 case STATUS_UNCONFIGURED:
1247 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 // OK
1249 break;
1250 case STATUS_ACTIVE:
1251 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 return res;
1256 }
1257 wasActive = true;
1258 break;
1259 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
1262 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264
1265 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001266
Shuzhen Wang0129d522016-10-30 22:43:41 -07001267 if (consumers.size() == 0 && !hasDeferredConsumer) {
1268 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1269 return BAD_VALUE;
1270 }
Zhijun He5d677d12016-05-29 16:52:39 -07001271
Shuzhen Wang0129d522016-10-30 22:43:41 -07001272 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001273 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1274 return BAD_VALUE;
1275 }
1276
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001278 ssize_t blobBufferSize;
1279 if (dataSpace != HAL_DATASPACE_DEPTH) {
1280 blobBufferSize = getJpegBufferSize(width, height);
1281 if (blobBufferSize <= 0) {
1282 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1283 return BAD_VALUE;
1284 }
1285 } else {
1286 blobBufferSize = getPointCloudBufferSize();
1287 if (blobBufferSize <= 0) {
1288 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1289 return BAD_VALUE;
1290 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001291 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001292 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001293 width, height, blobBufferSize, format, dataSpace, rotation,
1294 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001295 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1296 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1297 if (rawOpaqueBufferSize <= 0) {
1298 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1299 return BAD_VALUE;
1300 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001301 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001302 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1303 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001304 } else if (isShared) {
1305 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1306 width, height, format, consumerUsage, dataSpace, rotation,
1307 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001308 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001309 newStream = new Camera3OutputStream(mNextStreamId,
1310 width, height, format, consumerUsage, dataSpace, rotation,
1311 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001313 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001314 width, height, format, dataSpace, rotation,
1315 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318
Emilian Peev08dd2452017-04-06 16:55:14 +01001319 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001320
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001321 res = mOutputStreams.add(mNextStreamId, newStream);
1322 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001323 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001324 return res;
1325 }
1326
1327 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001328 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329
1330 // Continue captures if active at start
1331 if (wasActive) {
1332 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001333 // Reuse current operating mode for new stream config
1334 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001336 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1337 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 return res;
1339 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001340 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001342 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344}
1345
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001347 uint32_t *width, uint32_t *height,
1348 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001349 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001352
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 switch (mStatus) {
1354 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return INVALID_OPERATION;
1357 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001358 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001360 case STATUS_UNCONFIGURED:
1361 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 case STATUS_ACTIVE:
1363 // OK
1364 break;
1365 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return INVALID_OPERATION;
1368 }
1369
1370 ssize_t idx = mOutputStreams.indexOfKey(id);
1371 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001372 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 return idx;
1374 }
1375
1376 if (width) *width = mOutputStreams[idx]->getWidth();
1377 if (height) *height = mOutputStreams[idx]->getHeight();
1378 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001379 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001381}
1382
1383status_t Camera3Device::setStreamTransform(int id,
1384 int transform) {
1385 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001388
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 switch (mStatus) {
1390 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
1393 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001394 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001396 case STATUS_UNCONFIGURED:
1397 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 case STATUS_ACTIVE:
1399 // OK
1400 break;
1401 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001402 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 return INVALID_OPERATION;
1404 }
1405
1406 ssize_t idx = mOutputStreams.indexOfKey(id);
1407 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001408 CLOGE("Stream %d does not exist",
1409 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 return BAD_VALUE;
1411 }
1412
1413 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001414}
1415
1416status_t Camera3Device::deleteStream(int id) {
1417 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001418 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 Mutex::Autolock l(mLock);
1420 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001422 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 // CameraDevice semantics require device to already be idle before
1425 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001426 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001427 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001428 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 }
1430
Igor Murashkin2fba5842013-04-22 14:03:54 -07001431 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001432 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 if (mInputStream != NULL && id == mInputStream->getId()) {
1434 deletedStream = mInputStream;
1435 mInputStream.clear();
1436 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001437 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001438 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 return BAD_VALUE;
1440 }
Zhijun He5f446352014-01-22 09:49:33 -08001441 }
1442
1443 // Delete output stream or the output part of a bi-directional stream.
1444 if (outputStreamIdx != NAME_NOT_FOUND) {
1445 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 mOutputStreams.removeItem(id);
1447 }
1448
1449 // Free up the stream endpoint so that it can be used by some other stream
1450 res = deletedStream->disconnect();
1451 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001452 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 // fall through since we want to still list the stream as deleted.
1454 }
1455 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001456 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457
1458 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001459}
1460
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001461status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001462 ATRACE_CALL();
1463 ALOGV("%s: E", __FUNCTION__);
1464
1465 Mutex::Autolock il(mInterfaceLock);
1466 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001467
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001468 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001469}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001470
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001471status_t Camera3Device::getInputBufferProducer(
1472 sp<IGraphicBufferProducer> *producer) {
1473 Mutex::Autolock il(mInterfaceLock);
1474 Mutex::Autolock l(mLock);
1475
1476 if (producer == NULL) {
1477 return BAD_VALUE;
1478 } else if (mInputStream == NULL) {
1479 return INVALID_OPERATION;
1480 }
1481
1482 return mInputStream->getInputBufferProducer(producer);
1483}
1484
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001485status_t Camera3Device::createDefaultRequest(int templateId,
1486 CameraMetadata *request) {
1487 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001488 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001489
1490 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1491 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1492 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1493 return BAD_VALUE;
1494 }
1495
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 Mutex::Autolock l(mLock);
1498
1499 switch (mStatus) {
1500 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001501 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 return INVALID_OPERATION;
1503 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506 case STATUS_UNCONFIGURED:
1507 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 case STATUS_ACTIVE:
1509 // OK
1510 break;
1511 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001512 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 return INVALID_OPERATION;
1514 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001515
Zhijun Hea1530f12014-09-14 12:44:20 -07001516 if (!mRequestTemplateCache[templateId].isEmpty()) {
1517 *request = mRequestTemplateCache[templateId];
1518 return OK;
1519 }
1520
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001521 camera_metadata_t *rawRequest;
1522 status_t res = mInterface->constructDefaultRequestSettings(
1523 (camera3_request_template_t) templateId, &rawRequest);
1524 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001525 ALOGI("%s: template %d is not supported on this camera device",
1526 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001527 return res;
1528 } else if (res != OK) {
1529 CLOGE("Unable to construct request template %d: %s (%d)",
1530 templateId, strerror(-res), res);
1531 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001532 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001533
Emilian Peev71c73a22017-03-21 16:35:51 +00001534 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001535 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001536
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001537 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001538 return OK;
1539}
1540
1541status_t Camera3Device::waitUntilDrained() {
1542 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545
Zhijun He69a37482014-03-23 18:44:49 -07001546 return waitUntilDrainedLocked();
1547}
1548
1549status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 switch (mStatus) {
1551 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 ALOGV("%s: Already idle", __FUNCTION__);
1554 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 case STATUS_CONFIGURED:
1556 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 case STATUS_ERROR:
1558 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 break;
1561 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001562 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 return INVALID_OPERATION;
1564 }
1565
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001566 nsecs_t maxExpectedDuration = getExpectedInFlightDurationLocked();
1567
1568 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1569 maxExpectedDuration);
1570 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001571 if (res != OK) {
1572 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1573 res);
1574 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 return res;
1576}
1577
Ruben Brunk183f0562015-08-12 12:55:02 -07001578
1579void Camera3Device::internalUpdateStatusLocked(Status status) {
1580 mStatus = status;
1581 mRecentStatusUpdates.add(mStatus);
1582 mStatusChanged.broadcast();
1583}
1584
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585// Pause to reconfigure
1586status_t Camera3Device::internalPauseAndWaitLocked() {
1587 mRequestThread->setPaused(true);
1588 mPauseStateNotify = true;
1589
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001590 nsecs_t maxExpectedDuration = getExpectedInFlightDurationLocked();
1591 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1592 maxExpectedDuration);
1593 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594 if (res != OK) {
1595 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001596 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 }
1598
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001599 return res;
1600}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602// Resume after internalPauseAndWaitLocked
1603status_t Camera3Device::internalResumeLocked() {
1604 status_t res;
1605
1606 mRequestThread->setPaused(false);
1607
1608 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1609 if (res != OK) {
1610 SET_ERR_L("Can't transition to active in %f seconds!",
1611 kActiveTimeout/1e9);
1612 }
1613 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615}
1616
Ruben Brunk183f0562015-08-12 12:55:02 -07001617status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001618 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001619
1620 size_t startIndex = 0;
1621 if (mStatusWaiters == 0) {
1622 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1623 // this status list
1624 mRecentStatusUpdates.clear();
1625 } else {
1626 // If other threads are waiting on updates to this status list, set the position of the
1627 // first element that this list will check rather than clearing the list.
1628 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 }
1630
Ruben Brunk183f0562015-08-12 12:55:02 -07001631 mStatusWaiters++;
1632
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 bool stateSeen = false;
1634 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001635 if (active == (mStatus == STATUS_ACTIVE)) {
1636 // Desired state is current
1637 break;
1638 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639
1640 res = mStatusChanged.waitRelative(mLock, timeout);
1641 if (res != OK) break;
1642
Ruben Brunk183f0562015-08-12 12:55:02 -07001643 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1644 // transitions.
1645 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1646 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1647 __FUNCTION__);
1648
1649 // Encountered desired state since we began waiting
1650 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1652 stateSeen = true;
1653 break;
1654 }
1655 }
1656 } while (!stateSeen);
1657
Ruben Brunk183f0562015-08-12 12:55:02 -07001658 mStatusWaiters--;
1659
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001660 return res;
1661}
1662
1663
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001664status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001665 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001666 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001667
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001668 if (listener != NULL && mListener != NULL) {
1669 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1670 }
1671 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001672 mRequestThread->setNotificationListener(listener);
1673 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001674
1675 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676}
1677
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001678bool Camera3Device::willNotify3A() {
1679 return false;
1680}
1681
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001682status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001683 status_t res;
1684 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001686 while (mResultQueue.empty()) {
1687 res = mResultSignal.waitRelative(mOutputLock, timeout);
1688 if (res == TIMED_OUT) {
1689 return res;
1690 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001691 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1692 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001693 return res;
1694 }
1695 }
1696 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697}
1698
Jianing Weicb0652e2014-03-12 18:29:36 -07001699status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001701 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001702
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001703 if (mResultQueue.empty()) {
1704 return NOT_ENOUGH_DATA;
1705 }
1706
Jianing Weicb0652e2014-03-12 18:29:36 -07001707 if (frame == NULL) {
1708 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1709 return BAD_VALUE;
1710 }
1711
1712 CaptureResult &result = *(mResultQueue.begin());
1713 frame->mResultExtras = result.mResultExtras;
1714 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001715 mResultQueue.erase(mResultQueue.begin());
1716
1717 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718}
1719
1720status_t Camera3Device::triggerAutofocus(uint32_t id) {
1721 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001724 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1725 // Mix-in this trigger into the next request and only the next request.
1726 RequestTrigger trigger[] = {
1727 {
1728 ANDROID_CONTROL_AF_TRIGGER,
1729 ANDROID_CONTROL_AF_TRIGGER_START
1730 },
1731 {
1732 ANDROID_CONTROL_AF_TRIGGER_ID,
1733 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001734 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001735 };
1736
1737 return mRequestThread->queueTrigger(trigger,
1738 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001739}
1740
1741status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1742 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001743 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001745 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1746 // Mix-in this trigger into the next request and only the next request.
1747 RequestTrigger trigger[] = {
1748 {
1749 ANDROID_CONTROL_AF_TRIGGER,
1750 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1751 },
1752 {
1753 ANDROID_CONTROL_AF_TRIGGER_ID,
1754 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001755 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001756 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001758 return mRequestThread->queueTrigger(trigger,
1759 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001760}
1761
1762status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1763 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001764 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001766 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1767 // Mix-in this trigger into the next request and only the next request.
1768 RequestTrigger trigger[] = {
1769 {
1770 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1771 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1772 },
1773 {
1774 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1775 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001776 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001777 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001778
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001779 return mRequestThread->queueTrigger(trigger,
1780 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001781}
1782
Jianing Weicb0652e2014-03-12 18:29:36 -07001783status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001784 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001785 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001786 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001787
Zhijun He7ef20392014-04-21 16:04:17 -07001788 {
1789 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001790 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001791 }
1792
Emilian Peev08dd2452017-04-06 16:55:14 +01001793 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001794}
1795
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001796status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001797 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1798}
1799
1800status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001801 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001802 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001803 Mutex::Autolock il(mInterfaceLock);
1804 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001805
1806 sp<Camera3StreamInterface> stream;
1807 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1808 if (outputStreamIdx == NAME_NOT_FOUND) {
1809 CLOGE("Stream %d does not exist", streamId);
1810 return BAD_VALUE;
1811 }
1812
1813 stream = mOutputStreams.editValueAt(outputStreamIdx);
1814
1815 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001816 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001817 return BAD_VALUE;
1818 }
1819
1820 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001821 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001822 return BAD_VALUE;
1823 }
1824
Ruben Brunkc78ac262015-08-13 17:58:46 -07001825 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001826}
1827
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001828status_t Camera3Device::tearDown(int streamId) {
1829 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001830 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001831 Mutex::Autolock il(mInterfaceLock);
1832 Mutex::Autolock l(mLock);
1833
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001834 sp<Camera3StreamInterface> stream;
1835 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1836 if (outputStreamIdx == NAME_NOT_FOUND) {
1837 CLOGE("Stream %d does not exist", streamId);
1838 return BAD_VALUE;
1839 }
1840
1841 stream = mOutputStreams.editValueAt(outputStreamIdx);
1842
1843 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1844 CLOGE("Stream %d is a target of a in-progress request", streamId);
1845 return BAD_VALUE;
1846 }
1847
1848 return stream->tearDown();
1849}
1850
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001851status_t Camera3Device::addBufferListenerForStream(int streamId,
1852 wp<Camera3StreamBufferListener> listener) {
1853 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001854 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001855 Mutex::Autolock il(mInterfaceLock);
1856 Mutex::Autolock l(mLock);
1857
1858 sp<Camera3StreamInterface> stream;
1859 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1860 if (outputStreamIdx == NAME_NOT_FOUND) {
1861 CLOGE("Stream %d does not exist", streamId);
1862 return BAD_VALUE;
1863 }
1864
1865 stream = mOutputStreams.editValueAt(outputStreamIdx);
1866 stream->addBufferListener(listener);
1867
1868 return OK;
1869}
1870
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 * Methods called by subclasses
1873 */
1874
1875void Camera3Device::notifyStatus(bool idle) {
1876 {
1877 // Need mLock to safely update state and synchronize to current
1878 // state of methods in flight.
1879 Mutex::Autolock l(mLock);
1880 // We can get various system-idle notices from the status tracker
1881 // while starting up. Only care about them if we've actually sent
1882 // in some requests recently.
1883 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1884 return;
1885 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001886 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001887 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001888 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001889
1890 // Skip notifying listener if we're doing some user-transparent
1891 // state changes
1892 if (mPauseStateNotify) return;
1893 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001894
1895 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001896 {
1897 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001898 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 }
1900 if (idle && listener != NULL) {
1901 listener->notifyIdle();
1902 }
1903}
1904
Shuzhen Wang758c2152017-01-10 18:26:18 -08001905status_t Camera3Device::setConsumerSurfaces(int streamId,
1906 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001907 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001908 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1909 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001910 Mutex::Autolock il(mInterfaceLock);
1911 Mutex::Autolock l(mLock);
1912
Shuzhen Wang758c2152017-01-10 18:26:18 -08001913 if (consumers.size() == 0) {
1914 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001915 return BAD_VALUE;
1916 }
1917
1918 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1919 if (idx == NAME_NOT_FOUND) {
1920 CLOGE("Stream %d is unknown", streamId);
1921 return idx;
1922 }
1923 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001924 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001925 if (res != OK) {
1926 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1927 return res;
1928 }
1929
Shuzhen Wang0129d522016-10-30 22:43:41 -07001930 if (stream->isConsumerConfigurationDeferred()) {
1931 if (!stream->isConfiguring()) {
1932 CLOGE("Stream %d was already fully configured.", streamId);
1933 return INVALID_OPERATION;
1934 }
Zhijun He5d677d12016-05-29 16:52:39 -07001935
Shuzhen Wang0129d522016-10-30 22:43:41 -07001936 res = stream->finishConfiguration();
1937 if (res != OK) {
1938 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1939 stream->getId(), strerror(-res), res);
1940 return res;
1941 }
Zhijun He5d677d12016-05-29 16:52:39 -07001942 }
1943
1944 return OK;
1945}
1946
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001948 * Camera3Device private methods
1949 */
1950
1951sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001952 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001953 ATRACE_CALL();
1954 status_t res;
1955
1956 sp<CaptureRequest> newRequest = new CaptureRequest;
1957 newRequest->mSettings = request;
1958
1959 camera_metadata_entry_t inputStreams =
1960 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1961 if (inputStreams.count > 0) {
1962 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001963 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001964 CLOGE("Request references unknown input stream %d",
1965 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001966 return NULL;
1967 }
1968 // Lazy completion of stream configuration (allocation/registration)
1969 // on first use
1970 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001971 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001972 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001973 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001974 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001975 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976 return NULL;
1977 }
1978 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001979 // Check if stream is being prepared
1980 if (mInputStream->isPreparing()) {
1981 CLOGE("Request references an input stream that's being prepared!");
1982 return NULL;
1983 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001984
1985 newRequest->mInputStream = mInputStream;
1986 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1987 }
1988
1989 camera_metadata_entry_t streams =
1990 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1991 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001992 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 return NULL;
1994 }
1995
1996 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001997 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001999 CLOGE("Request references unknown stream %d",
2000 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002001 return NULL;
2002 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002003 sp<Camera3OutputStreamInterface> stream =
2004 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002005
Zhijun He5d677d12016-05-29 16:52:39 -07002006 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002007 auto iter = surfaceMap.find(streams.data.i32[i]);
2008 if (iter != surfaceMap.end()) {
2009 const std::vector<size_t>& surfaces = iter->second;
2010 for (const auto& surface : surfaces) {
2011 if (stream->isConsumerConfigurationDeferred(surface)) {
2012 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2013 "due to deferred consumer", stream->getId(), surface);
2014 return NULL;
2015 }
2016 }
2017 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002018 }
2019
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002020 // Lazy completion of stream configuration (allocation/registration)
2021 // on first use
2022 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002023 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002024 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002025 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2026 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027 return NULL;
2028 }
2029 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030 // Check if stream is being prepared
2031 if (stream->isPreparing()) {
2032 CLOGE("Request references an output stream that's being prepared!");
2033 return NULL;
2034 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035
2036 newRequest->mOutputStreams.push(stream);
2037 }
2038 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002039 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040
2041 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002042}
2043
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002044bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2045 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2046 Size size = mSupportedOpaqueInputSizes[i];
2047 if (size.width == width && size.height == height) {
2048 return true;
2049 }
2050 }
2051
2052 return false;
2053}
2054
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002055void Camera3Device::cancelStreamsConfigurationLocked() {
2056 int res = OK;
2057 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2058 res = mInputStream->cancelConfiguration();
2059 if (res != OK) {
2060 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2061 mInputStream->getId(), strerror(-res), res);
2062 }
2063 }
2064
2065 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2066 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2067 if (outputStream->isConfiguring()) {
2068 res = outputStream->cancelConfiguration();
2069 if (res != OK) {
2070 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2071 outputStream->getId(), strerror(-res), res);
2072 }
2073 }
2074 }
2075
2076 // Return state to that at start of call, so that future configures
2077 // properly clean things up
2078 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2079 mNeedConfig = true;
2080}
2081
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002082status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 ATRACE_CALL();
2084 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002085
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002086 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002087 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 return INVALID_OPERATION;
2089 }
2090
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002091 if (operatingMode < 0) {
2092 CLOGE("Invalid operating mode: %d", operatingMode);
2093 return BAD_VALUE;
2094 }
2095
2096 bool isConstrainedHighSpeed =
2097 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2098 operatingMode;
2099
2100 if (mOperatingMode != operatingMode) {
2101 mNeedConfig = true;
2102 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2103 mOperatingMode = operatingMode;
2104 }
2105
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002106 if (!mNeedConfig) {
2107 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2108 return OK;
2109 }
2110
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002111 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2112 // adding a dummy stream instead.
2113 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2114 if (mOutputStreams.size() == 0) {
2115 addDummyStreamLocked();
2116 } else {
2117 tryRemoveDummyStreamLocked();
2118 }
2119
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002121 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122
2123 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002124 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2126
2127 Vector<camera3_stream_t*> streams;
2128 streams.setCapacity(config.num_streams);
2129
2130 if (mInputStream != NULL) {
2131 camera3_stream_t *inputStream;
2132 inputStream = mInputStream->startConfiguration();
2133 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002134 CLOGE("Can't start input stream configuration");
2135 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 return INVALID_OPERATION;
2137 }
2138 streams.add(inputStream);
2139 }
2140
2141 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002142
2143 // Don't configure bidi streams twice, nor add them twice to the list
2144 if (mOutputStreams[i].get() ==
2145 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2146
2147 config.num_streams--;
2148 continue;
2149 }
2150
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 camera3_stream_t *outputStream;
2152 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2153 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002154 CLOGE("Can't start output stream configuration");
2155 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156 return INVALID_OPERATION;
2157 }
2158 streams.add(outputStream);
2159 }
2160
2161 config.streams = streams.editArray();
2162
2163 // Do the HAL configuration; will potentially touch stream
2164 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002165
2166 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002167
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002168 if (res == BAD_VALUE) {
2169 // HAL rejected this set of streams as unsupported, clean up config
2170 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002171 CLOGE("Set of requested inputs/outputs not supported by HAL");
2172 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002173 return BAD_VALUE;
2174 } else if (res != OK) {
2175 // Some other kind of error from configure_streams - this is not
2176 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002177 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2178 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002179 return res;
2180 }
2181
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002182 // Finish all stream configuration immediately.
2183 // TODO: Try to relax this later back to lazy completion, which should be
2184 // faster
2185
Igor Murashkin073f8572013-05-02 14:59:28 -07002186 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002187 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002188 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002189 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002190 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002191 cancelStreamsConfigurationLocked();
2192 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002193 }
2194 }
2195
2196 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002197 sp<Camera3OutputStreamInterface> outputStream =
2198 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002199 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002200 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002201 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002202 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002203 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002204 cancelStreamsConfigurationLocked();
2205 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002206 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002207 }
2208 }
2209
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 // Request thread needs to know to avoid using repeat-last-settings protocol
2211 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002212 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002213
Zhijun He90f7c372016-08-16 16:19:43 -07002214 char value[PROPERTY_VALUE_MAX];
2215 property_get("camera.fifo.disable", value, "0");
2216 int32_t disableFifo = atoi(value);
2217 if (disableFifo != 1) {
2218 // Boost priority of request thread to SCHED_FIFO.
2219 pid_t requestThreadTid = mRequestThread->getTid();
2220 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002221 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002222 if (res != OK) {
2223 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2224 strerror(-res), res);
2225 } else {
2226 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2227 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002228 }
2229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002232 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002233
Ruben Brunk183f0562015-08-12 12:55:02 -07002234 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2235 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002236
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002237 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002238
Zhijun He0a210512014-07-24 13:45:15 -07002239 // tear down the deleted streams after configure streams.
2240 mDeletedStreams.clear();
2241
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002242 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002243}
2244
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002245status_t Camera3Device::addDummyStreamLocked() {
2246 ATRACE_CALL();
2247 status_t res;
2248
2249 if (mDummyStreamId != NO_STREAM) {
2250 // Should never be adding a second dummy stream when one is already
2251 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002252 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2253 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002254 return INVALID_OPERATION;
2255 }
2256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002257 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002258
2259 sp<Camera3OutputStreamInterface> dummyStream =
2260 new Camera3DummyStream(mNextStreamId);
2261
2262 res = mOutputStreams.add(mNextStreamId, dummyStream);
2263 if (res < 0) {
2264 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2265 return res;
2266 }
2267
2268 mDummyStreamId = mNextStreamId;
2269 mNextStreamId++;
2270
2271 return OK;
2272}
2273
2274status_t Camera3Device::tryRemoveDummyStreamLocked() {
2275 ATRACE_CALL();
2276 status_t res;
2277
2278 if (mDummyStreamId == NO_STREAM) return OK;
2279 if (mOutputStreams.size() == 1) return OK;
2280
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002281 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002282
2283 // Ok, have a dummy stream and there's at least one other output stream,
2284 // so remove the dummy
2285
2286 sp<Camera3StreamInterface> deletedStream;
2287 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2288 if (outputStreamIdx == NAME_NOT_FOUND) {
2289 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2290 return INVALID_OPERATION;
2291 }
2292
2293 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2294 mOutputStreams.removeItemsAt(outputStreamIdx);
2295
2296 // Free up the stream endpoint so that it can be used by some other stream
2297 res = deletedStream->disconnect();
2298 if (res != OK) {
2299 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2300 // fall through since we want to still list the stream as deleted.
2301 }
2302 mDeletedStreams.add(deletedStream);
2303 mDummyStreamId = NO_STREAM;
2304
2305 return res;
2306}
2307
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002308void Camera3Device::setErrorState(const char *fmt, ...) {
2309 Mutex::Autolock l(mLock);
2310 va_list args;
2311 va_start(args, fmt);
2312
2313 setErrorStateLockedV(fmt, args);
2314
2315 va_end(args);
2316}
2317
2318void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2319 Mutex::Autolock l(mLock);
2320 setErrorStateLockedV(fmt, args);
2321}
2322
2323void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2324 va_list args;
2325 va_start(args, fmt);
2326
2327 setErrorStateLockedV(fmt, args);
2328
2329 va_end(args);
2330}
2331
2332void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002333 // Print out all error messages to log
2334 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002335 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002336
2337 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002338 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002339
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002340 mErrorCause = errorCause;
2341
2342 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002343 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002344
2345 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002346 sp<NotificationListener> listener = mListener.promote();
2347 if (listener != NULL) {
2348 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002349 CaptureResultExtras());
2350 }
2351
2352 // Save stack trace. View by dumping it later.
2353 CameraTraces::saveTrace();
2354 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002355}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356
2357/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002358 * In-flight request management
2359 */
2360
Jianing Weicb0652e2014-03-12 18:29:36 -07002361status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002362 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002363 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002364 ATRACE_CALL();
2365 Mutex::Autolock l(mInFlightLock);
2366
2367 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002368 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002369 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002370 if (res < 0) return res;
2371
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002372 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002373 // hold mLock to prevent race with disconnect
2374 Mutex::Autolock l(mLock);
2375 if (mStatusTracker != nullptr) {
2376 mStatusTracker->markComponentActive(mInFlightStatusId);
2377 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002378 }
2379
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002380 Mutex::Autolock ml(mLock);
2381 mExpectedInflightDuration += maxExpectedDuration;
2382
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002383 return OK;
2384}
2385
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002386void Camera3Device::returnOutputBuffers(
2387 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2388 nsecs_t timestamp) {
2389 for (size_t i = 0; i < numBuffers; i++)
2390 {
2391 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2392 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2393 // Note: stream may be deallocated at this point, if this buffer was
2394 // the last reference to it.
2395 if (res != OK) {
2396 ALOGE("Can't return buffer to its stream: %s (%d)",
2397 strerror(-res), res);
2398 }
2399 }
2400}
2401
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002402void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002403 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002404 mInFlightMap.removeItemsAt(idx, 1);
2405
2406 // Indicate idle inFlightMap to the status tracker
2407 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002408 // hold mLock to prevent race with disconnect
2409 Mutex::Autolock l(mLock);
2410 if (mStatusTracker != nullptr) {
2411 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2412 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002413 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002414 Mutex::Autolock l(mLock);
2415 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002416}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002417
2418void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2419
2420 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2421 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2422
2423 nsecs_t sensorTimestamp = request.sensorTimestamp;
2424 nsecs_t shutterTimestamp = request.shutterTimestamp;
2425
Emilian Peevc6747862017-06-12 15:57:26 +01002426 bool skipResultMetadata = false;
2427 if (request.requestStatus != OK) {
2428 switch (request.requestStatus) {
2429 case CAMERA3_MSG_ERROR_DEVICE:
2430 case CAMERA3_MSG_ERROR_REQUEST:
2431 case CAMERA3_MSG_ERROR_RESULT:
2432 skipResultMetadata = true;
2433 break;
2434 case CAMERA3_MSG_ERROR_BUFFER:
2435 //Result metadata should return in this case.
2436 skipResultMetadata = false;
2437 break;
2438 default:
2439 SET_ERR("Unknown error message: %d", request.requestStatus);
2440 skipResultMetadata = false;
2441 break;
2442 }
2443 }
2444
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002445 // Check if it's okay to remove the request from InFlightMap:
2446 // In the case of a successful request:
2447 // all input and output buffers, all result metadata, shutter callback
2448 // arrived.
2449 // In the case of a unsuccessful request:
2450 // all input and output buffers arrived.
2451 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002452 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002453 (request.haveResultMetadata && shutterTimestamp != 0))) {
2454 ATRACE_ASYNC_END("frame capture", frameNumber);
2455
Shuzhen Wang403044a2017-02-26 23:29:04 -08002456 // Sanity check - if sensor timestamp matches shutter timestamp in the
2457 // case of request having callback.
2458 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002459 sensorTimestamp != shutterTimestamp) {
2460 SET_ERR("sensor timestamp (%" PRId64
2461 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2462 sensorTimestamp, frameNumber, shutterTimestamp);
2463 }
2464
2465 // for an unsuccessful request, it may have pending output buffers to
2466 // return.
2467 assert(request.requestStatus != OK ||
2468 request.pendingOutputBuffers.size() == 0);
2469 returnOutputBuffers(request.pendingOutputBuffers.array(),
2470 request.pendingOutputBuffers.size(), 0);
2471
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002472 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002473 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2474 }
2475
2476 // Sanity check - if we have too many in-flight frames, something has
2477 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002478 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002479 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002480 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2481 kInFlightWarnLimitHighSpeed) {
2482 CLOGE("In-flight list too large for high speed configuration: %zu",
2483 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002484 }
2485}
2486
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002487void Camera3Device::flushInflightRequests() {
2488 { // First return buffers cached in mInFlightMap
2489 Mutex::Autolock l(mInFlightLock);
2490 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2491 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2492 returnOutputBuffers(request.pendingOutputBuffers.array(),
2493 request.pendingOutputBuffers.size(), 0);
2494 }
2495 mInFlightMap.clear();
2496 }
2497
2498 // Then return all inflight buffers not returned by HAL
2499 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2500 mInterface->getInflightBufferKeys(&inflightKeys);
2501
2502 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2503 for (auto& pair : inflightKeys) {
2504 int32_t frameNumber = pair.first;
2505 int32_t streamId = pair.second;
2506 buffer_handle_t* buffer;
2507 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2508 if (res != OK) {
2509 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2510 __FUNCTION__, frameNumber, streamId);
2511 continue;
2512 }
2513
2514 camera3_stream_buffer_t streamBuffer;
2515 streamBuffer.buffer = buffer;
2516 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2517 streamBuffer.acquire_fence = -1;
2518 streamBuffer.release_fence = -1;
2519 if (streamId == inputStreamId) {
2520 streamBuffer.stream = mInputStream->asHalStream();
2521 res = mInputStream->returnInputBuffer(streamBuffer);
2522 if (res != OK) {
2523 ALOGE("%s: Can't return input buffer for frame %d to"
2524 " its stream:%s (%d)", __FUNCTION__,
2525 frameNumber, strerror(-res), res);
2526 }
2527 } else {
2528 streamBuffer.stream = mOutputStreams.valueFor(streamId)->asHalStream();
2529 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2530 }
2531 }
2532}
2533
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002534void Camera3Device::insertResultLocked(CaptureResult *result,
2535 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002536 if (result == nullptr) return;
2537
Emilian Peev71c73a22017-03-21 16:35:51 +00002538 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2539 result->mMetadata.getAndLock());
2540 set_camera_metadata_vendor_id(meta, mVendorTagId);
2541 result->mMetadata.unlock(meta);
2542
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002543 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2544 (int32_t*)&frameNumber, 1) != OK) {
2545 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2546 return;
2547 }
2548
2549 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2550 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2551 return;
2552 }
2553
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002554 // Valid result, insert into queue
2555 List<CaptureResult>::iterator queuedResult =
2556 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2557 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2558 ", burstId = %" PRId32, __FUNCTION__,
2559 queuedResult->mResultExtras.requestId,
2560 queuedResult->mResultExtras.frameNumber,
2561 queuedResult->mResultExtras.burstId);
2562
2563 mResultSignal.signal();
2564}
2565
2566
2567void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002568 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002569 Mutex::Autolock l(mOutputLock);
2570
2571 CaptureResult captureResult;
2572 captureResult.mResultExtras = resultExtras;
2573 captureResult.mMetadata = partialResult;
2574
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002575 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002576}
2577
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002578
2579void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2580 CaptureResultExtras &resultExtras,
2581 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002582 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002583 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002584 if (pendingMetadata.isEmpty())
2585 return;
2586
2587 Mutex::Autolock l(mOutputLock);
2588
2589 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002590 if (reprocess) {
2591 if (frameNumber < mNextReprocessResultFrameNumber) {
2592 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002593 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002594 frameNumber, mNextReprocessResultFrameNumber);
2595 return;
2596 }
2597 mNextReprocessResultFrameNumber = frameNumber + 1;
2598 } else {
2599 if (frameNumber < mNextResultFrameNumber) {
2600 SET_ERR("Out-of-order capture result metadata submitted! "
2601 "(got frame number %d, expecting %d)",
2602 frameNumber, mNextResultFrameNumber);
2603 return;
2604 }
2605 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002606 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002607
2608 CaptureResult captureResult;
2609 captureResult.mResultExtras = resultExtras;
2610 captureResult.mMetadata = pendingMetadata;
2611
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002612 // Append any previous partials to form a complete result
2613 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2614 captureResult.mMetadata.append(collectedPartialResult);
2615 }
2616
2617 captureResult.mMetadata.sort();
2618
2619 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002620 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2621 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002622 SET_ERR("No timestamp provided by HAL for frame %d!",
2623 frameNumber);
2624 return;
2625 }
2626
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002627 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2628 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2629
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002630 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002631}
2632
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002633/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634 * Camera HAL device callback methods
2635 */
2636
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002637void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002638 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002639
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002640 status_t res;
2641
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002642 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002643 if (result->result == NULL && result->num_output_buffers == 0 &&
2644 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002645 SET_ERR("No result data provided by HAL for frame %d",
2646 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002647 return;
2648 }
Zhijun He204e3292014-07-14 17:09:23 -07002649
Zhijun He204e3292014-07-14 17:09:23 -07002650 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002651 result->result != NULL &&
2652 result->partial_result != 1) {
2653 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2654 " if partial result is not supported",
2655 frameNumber, result->partial_result);
2656 return;
2657 }
2658
2659 bool isPartialResult = false;
2660 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002661 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002662 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002663
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002664 // Get shutter timestamp and resultExtras from list of in-flight requests,
2665 // where it was added by the shutter notification for this frame. If the
2666 // shutter timestamp isn't received yet, append the output buffers to the
2667 // in-flight request and they will be returned when the shutter timestamp
2668 // arrives. Update the in-flight status and remove the in-flight entry if
2669 // all result data and shutter timestamp have been received.
2670 nsecs_t shutterTimestamp = 0;
2671
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002672 {
2673 Mutex::Autolock l(mInFlightLock);
2674 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2675 if (idx == NAME_NOT_FOUND) {
2676 SET_ERR("Unknown frame number for capture result: %d",
2677 frameNumber);
2678 return;
2679 }
2680 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002681 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2682 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002683 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002684 __FUNCTION__, request.resultExtras.requestId,
2685 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002686 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002687 // Always update the partial count to the latest one if it's not 0
2688 // (buffers only). When framework aggregates adjacent partial results
2689 // into one, the latest partial count will be used.
2690 if (result->partial_result != 0)
2691 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002692
2693 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002694 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002695 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2696 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2697 " the range of [1, %d] when metadata is included in the result",
2698 frameNumber, result->partial_result, mNumPartialResults);
2699 return;
2700 }
2701 isPartialResult = (result->partial_result < mNumPartialResults);
2702 if (isPartialResult) {
2703 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002704 }
2705
Shuzhen Wang4a472662017-02-26 23:29:04 -08002706 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002707 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002708 sendPartialCaptureResult(result->result, request.resultExtras,
2709 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002710 }
2711 }
2712
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002713 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002714 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002715
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002716 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002717 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002718 if (request.haveResultMetadata) {
2719 SET_ERR("Called multiple times with metadata for frame %d",
2720 frameNumber);
2721 return;
2722 }
Zhijun He204e3292014-07-14 17:09:23 -07002723 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002724 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002725 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002726 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002727 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002728 request.haveResultMetadata = true;
2729 }
2730
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002731 uint32_t numBuffersReturned = result->num_output_buffers;
2732 if (result->input_buffer != NULL) {
2733 if (hasInputBufferInRequest) {
2734 numBuffersReturned += 1;
2735 } else {
2736 ALOGW("%s: Input buffer should be NULL if there is no input"
2737 " buffer sent in the request",
2738 __FUNCTION__);
2739 }
2740 }
2741 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002742 if (request.numBuffersLeft < 0) {
2743 SET_ERR("Too many buffers returned for frame %d",
2744 frameNumber);
2745 return;
2746 }
2747
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002748 camera_metadata_ro_entry_t entry;
2749 res = find_camera_metadata_ro_entry(result->result,
2750 ANDROID_SENSOR_TIMESTAMP, &entry);
2751 if (res == OK && entry.count == 1) {
2752 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002753 }
2754
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002755 // If shutter event isn't received yet, append the output buffers to
2756 // the in-flight request. Otherwise, return the output buffers to
2757 // streams.
2758 if (shutterTimestamp == 0) {
2759 request.pendingOutputBuffers.appendArray(result->output_buffers,
2760 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002761 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002762 returnOutputBuffers(result->output_buffers,
2763 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002764 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002765
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002766 if (result->result != NULL && !isPartialResult) {
2767 if (shutterTimestamp == 0) {
2768 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002769 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002770 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771 CameraMetadata metadata;
2772 metadata = result->result;
2773 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002774 collectedPartialResult, frameNumber,
2775 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002776 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002777 }
2778
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002779 removeInFlightRequestIfReadyLocked(idx);
2780 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002781
Zhijun Hef0d962a2014-06-30 10:24:11 -07002782 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002783 if (hasInputBufferInRequest) {
2784 Camera3Stream *stream =
2785 Camera3Stream::cast(result->input_buffer->stream);
2786 res = stream->returnInputBuffer(*(result->input_buffer));
2787 // Note: stream may be deallocated at this point, if this buffer was the
2788 // last reference to it.
2789 if (res != OK) {
2790 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2791 " its stream:%s (%d)", __FUNCTION__,
2792 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002793 }
2794 } else {
2795 ALOGW("%s: Input buffer should be NULL if there is no input"
2796 " buffer sent in the request, skipping input buffer return.",
2797 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002798 }
2799 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002800}
2801
2802void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002803 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002804 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002805 {
2806 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002807 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002808 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002809
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002810 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002811 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002812 return;
2813 }
2814
2815 switch (msg->type) {
2816 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002817 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002818 break;
2819 }
2820 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002821 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002822 break;
2823 }
2824 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002825 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002826 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002827 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002828}
2829
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002830void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002831 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002832
2833 // Map camera HAL error codes to ICameraDeviceCallback error codes
2834 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002835 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002836 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002837 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002838 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002839 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002841 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002842 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002843 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002844 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002845 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002846 };
2847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002848 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002849 ((msg.error_code >= 0) &&
2850 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2851 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002852 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002853
2854 int streamId = 0;
2855 if (msg.error_stream != NULL) {
2856 Camera3Stream *stream =
2857 Camera3Stream::cast(msg.error_stream);
2858 streamId = stream->getId();
2859 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002860 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2861 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002862 streamId, msg.error_code);
2863
2864 CaptureResultExtras resultExtras;
2865 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002866 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002867 // SET_ERR calls notifyError
2868 SET_ERR("Camera HAL reported serious device error");
2869 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002870 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2871 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2872 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002873 {
2874 Mutex::Autolock l(mInFlightLock);
2875 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2876 if (idx >= 0) {
2877 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2878 r.requestStatus = msg.error_code;
2879 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002880 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2881 errorCode) {
2882 // In case of missing result check whether the buffers
2883 // returned. If they returned, then remove inflight
2884 // request.
2885 removeInFlightRequestIfReadyLocked(idx);
2886 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002887 } else {
2888 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002889 ALOGE("Camera %s: %s: cannot find in-flight request on "
2890 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002891 resultExtras.frameNumber);
2892 }
2893 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002894 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002895 if (listener != NULL) {
2896 listener->notifyError(errorCode, resultExtras);
2897 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002898 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002899 }
2900 break;
2901 default:
2902 // SET_ERR calls notifyError
2903 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2904 break;
2905 }
2906}
2907
2908void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002909 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002910 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002911
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002912 // Set timestamp for the request in the in-flight tracking
2913 // and get the request ID to send upstream
2914 {
2915 Mutex::Autolock l(mInFlightLock);
2916 idx = mInFlightMap.indexOfKey(msg.frame_number);
2917 if (idx >= 0) {
2918 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002919
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002920 // Verify ordering of shutter notifications
2921 {
2922 Mutex::Autolock l(mOutputLock);
2923 // TODO: need to track errors for tighter bounds on expected frame number.
2924 if (r.hasInputBuffer) {
2925 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2926 SET_ERR("Shutter notification out-of-order. Expected "
2927 "notification for frame %d, got frame %d",
2928 mNextReprocessShutterFrameNumber, msg.frame_number);
2929 return;
2930 }
2931 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2932 } else {
2933 if (msg.frame_number < mNextShutterFrameNumber) {
2934 SET_ERR("Shutter notification out-of-order. Expected "
2935 "notification for frame %d, got frame %d",
2936 mNextShutterFrameNumber, msg.frame_number);
2937 return;
2938 }
2939 mNextShutterFrameNumber = msg.frame_number + 1;
2940 }
2941 }
2942
Shuzhen Wang4a472662017-02-26 23:29:04 -08002943 r.shutterTimestamp = msg.timestamp;
2944 if (r.hasCallback) {
2945 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002946 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002947 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002948 // Call listener, if any
2949 if (listener != NULL) {
2950 listener->notifyShutter(r.resultExtras, msg.timestamp);
2951 }
2952 // send pending result and buffers
2953 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2954 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002955 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002956 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002957 returnOutputBuffers(r.pendingOutputBuffers.array(),
2958 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2959 r.pendingOutputBuffers.clear();
2960
2961 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962 }
2963 }
2964 if (idx < 0) {
2965 SET_ERR("Shutter notification for non-existent frame number %d",
2966 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002967 }
2968}
2969
2970
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002971CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002972 ALOGV("%s", __FUNCTION__);
2973
Igor Murashkin1e479c02013-09-06 16:55:14 -07002974 CameraMetadata retVal;
2975
2976 if (mRequestThread != NULL) {
2977 retVal = mRequestThread->getLatestRequest();
2978 }
2979
Igor Murashkin1e479c02013-09-06 16:55:14 -07002980 return retVal;
2981}
2982
Jianing Weicb0652e2014-03-12 18:29:36 -07002983
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002984void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2985 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2986 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2987}
2988
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002989/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 * HalInterface inner class methods
2991 */
2992
Yifan Hongf79b5542017-04-11 14:44:25 -07002993Camera3Device::HalInterface::HalInterface(
2994 sp<ICameraDeviceSession> &session,
2995 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002996 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002997 mHidlSession(session),
2998 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002999
3000Camera3Device::HalInterface::HalInterface() :
3001 mHal3Device(nullptr) {}
3002
3003Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003004 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07003005 mHidlSession(other.mHidlSession),
3006 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003007
3008bool Camera3Device::HalInterface::valid() {
3009 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3010}
3011
3012void Camera3Device::HalInterface::clear() {
3013 mHal3Device = nullptr;
3014 mHidlSession.clear();
3015}
3016
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003017bool Camera3Device::HalInterface::supportBatchRequest() {
3018 return mHidlSession != nullptr;
3019}
3020
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003021status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3022 camera3_request_template_t templateId,
3023 /*out*/ camera_metadata_t **requestTemplate) {
3024 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3025 if (!valid()) return INVALID_OPERATION;
3026 status_t res = OK;
3027
3028 if (mHal3Device != nullptr) {
3029 const camera_metadata *r;
3030 r = mHal3Device->ops->construct_default_request_settings(
3031 mHal3Device, templateId);
3032 if (r == nullptr) return BAD_VALUE;
3033 *requestTemplate = clone_camera_metadata(r);
3034 if (requestTemplate == nullptr) {
3035 ALOGE("%s: Unable to clone camera metadata received from HAL",
3036 __FUNCTION__);
3037 return INVALID_OPERATION;
3038 }
3039 } else {
3040 common::V1_0::Status status;
3041 RequestTemplate id;
3042 switch (templateId) {
3043 case CAMERA3_TEMPLATE_PREVIEW:
3044 id = RequestTemplate::PREVIEW;
3045 break;
3046 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3047 id = RequestTemplate::STILL_CAPTURE;
3048 break;
3049 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3050 id = RequestTemplate::VIDEO_RECORD;
3051 break;
3052 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3053 id = RequestTemplate::VIDEO_SNAPSHOT;
3054 break;
3055 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3056 id = RequestTemplate::ZERO_SHUTTER_LAG;
3057 break;
3058 case CAMERA3_TEMPLATE_MANUAL:
3059 id = RequestTemplate::MANUAL;
3060 break;
3061 default:
3062 // Unknown template ID
3063 return BAD_VALUE;
3064 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003065 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003066 [&status, &requestTemplate]
3067 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3068 status = s;
3069 if (status == common::V1_0::Status::OK) {
3070 const camera_metadata *r =
3071 reinterpret_cast<const camera_metadata_t*>(request.data());
3072 size_t expectedSize = request.size();
3073 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003074 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003075 *requestTemplate = clone_camera_metadata(r);
3076 if (*requestTemplate == nullptr) {
3077 ALOGE("%s: Unable to clone camera metadata received from HAL",
3078 __FUNCTION__);
3079 status = common::V1_0::Status::INTERNAL_ERROR;
3080 }
3081 } else {
3082 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3083 status = common::V1_0::Status::INTERNAL_ERROR;
3084 }
3085 }
3086 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003087 if (!err.isOk()) {
3088 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3089 res = DEAD_OBJECT;
3090 } else {
3091 res = CameraProviderManager::mapToStatusT(status);
3092 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003093 }
3094 return res;
3095}
3096
3097status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3098 ATRACE_NAME("CameraHal::configureStreams");
3099 if (!valid()) return INVALID_OPERATION;
3100 status_t res = OK;
3101
3102 if (mHal3Device != nullptr) {
3103 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3104 } else {
3105 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003106 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003107 StreamConfiguration requestedConfiguration;
3108 requestedConfiguration.streams.resize(config->num_streams);
3109 for (size_t i = 0; i < config->num_streams; i++) {
3110 Stream &dst = requestedConfiguration.streams[i];
3111 camera3_stream_t *src = config->streams[i];
3112
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003113 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3114 cam3stream->setBufferFreedListener(this);
3115 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116 StreamType streamType;
3117 switch (src->stream_type) {
3118 case CAMERA3_STREAM_OUTPUT:
3119 streamType = StreamType::OUTPUT;
3120 break;
3121 case CAMERA3_STREAM_INPUT:
3122 streamType = StreamType::INPUT;
3123 break;
3124 default:
3125 ALOGE("%s: Stream %d: Unsupported stream type %d",
3126 __FUNCTION__, streamId, config->streams[i]->stream_type);
3127 return BAD_VALUE;
3128 }
3129 dst.id = streamId;
3130 dst.streamType = streamType;
3131 dst.width = src->width;
3132 dst.height = src->height;
3133 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003134 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003135 dst.dataSpace = mapToHidlDataspace(src->data_space);
3136 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003137
3138 activeStreams.insert(streamId);
3139 // Create Buffer ID map if necessary
3140 if (mBufferIdMaps.count(streamId) == 0) {
3141 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3142 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003144 // remove BufferIdMap for deleted streams
3145 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3146 int streamId = it->first;
3147 bool active = activeStreams.count(streamId) > 0;
3148 if (!active) {
3149 it = mBufferIdMaps.erase(it);
3150 } else {
3151 ++it;
3152 }
3153 }
3154
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003155 res = mapToStreamConfigurationMode(
3156 (camera3_stream_configuration_mode_t) config->operation_mode,
3157 /*out*/ &requestedConfiguration.operationMode);
3158 if (res != OK) {
3159 return res;
3160 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003161
3162 // Invoke configureStreams
3163
3164 HalStreamConfiguration finalConfiguration;
3165 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003166 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003167 [&status, &finalConfiguration]
3168 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3169 finalConfiguration = halConfiguration;
3170 status = s;
3171 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003172 if (!err.isOk()) {
3173 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3174 return DEAD_OBJECT;
3175 }
3176
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003177 if (status != common::V1_0::Status::OK ) {
3178 return CameraProviderManager::mapToStatusT(status);
3179 }
3180
3181 // And convert output stream configuration from HIDL
3182
3183 for (size_t i = 0; i < config->num_streams; i++) {
3184 camera3_stream_t *dst = config->streams[i];
3185 int streamId = Camera3Stream::cast(dst)->getId();
3186
3187 // Start scan at i, with the assumption that the stream order matches
3188 size_t realIdx = i;
3189 bool found = false;
3190 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3191 if (finalConfiguration.streams[realIdx].id == streamId) {
3192 found = true;
3193 break;
3194 }
3195 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3196 }
3197 if (!found) {
3198 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3199 __FUNCTION__, streamId);
3200 return INVALID_OPERATION;
3201 }
3202 HalStream &src = finalConfiguration.streams[realIdx];
3203
3204 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3205 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3206 if (dst->format != overrideFormat) {
3207 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3208 streamId, dst->format);
3209 }
3210 } else {
3211 // Override allowed with IMPLEMENTATION_DEFINED
3212 dst->format = overrideFormat;
3213 }
3214
3215 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3216 if (src.producerUsage != 0) {
3217 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3218 __FUNCTION__, streamId);
3219 return INVALID_OPERATION;
3220 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003221 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003222 } else {
3223 // OUTPUT
3224 if (src.consumerUsage != 0) {
3225 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3226 __FUNCTION__, streamId);
3227 return INVALID_OPERATION;
3228 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003229 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003230 }
3231 dst->max_buffers = src.maxBuffers;
3232 }
3233 }
3234 return res;
3235}
3236
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003237void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3238 /*out*/device::V3_2::CaptureRequest* captureRequest,
3239 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3240
3241 if (captureRequest == nullptr || handlesCreated == nullptr) {
3242 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3243 __FUNCTION__, captureRequest, handlesCreated);
3244 return;
3245 }
3246
3247 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003248
3249 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003250
3251 {
3252 std::lock_guard<std::mutex> lock(mInflightLock);
3253 if (request->input_buffer != nullptr) {
3254 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3255 buffer_handle_t buf = *(request->input_buffer->buffer);
3256 auto pair = getBufferId(buf, streamId);
3257 bool isNewBuffer = pair.first;
3258 uint64_t bufferId = pair.second;
3259 captureRequest->inputBuffer.streamId = streamId;
3260 captureRequest->inputBuffer.bufferId = bufferId;
3261 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3262 captureRequest->inputBuffer.status = BufferStatus::OK;
3263 native_handle_t *acquireFence = nullptr;
3264 if (request->input_buffer->acquire_fence != -1) {
3265 acquireFence = native_handle_create(1,0);
3266 acquireFence->data[0] = request->input_buffer->acquire_fence;
3267 handlesCreated->push_back(acquireFence);
3268 }
3269 captureRequest->inputBuffer.acquireFence = acquireFence;
3270 captureRequest->inputBuffer.releaseFence = nullptr;
3271
3272 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3273 request->input_buffer->buffer,
3274 request->input_buffer->acquire_fence);
3275 } else {
3276 captureRequest->inputBuffer.streamId = -1;
3277 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3278 }
3279
3280 captureRequest->outputBuffers.resize(request->num_output_buffers);
3281 for (size_t i = 0; i < request->num_output_buffers; i++) {
3282 const camera3_stream_buffer_t *src = request->output_buffers + i;
3283 StreamBuffer &dst = captureRequest->outputBuffers[i];
3284 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3285 buffer_handle_t buf = *(src->buffer);
3286 auto pair = getBufferId(buf, streamId);
3287 bool isNewBuffer = pair.first;
3288 dst.streamId = streamId;
3289 dst.bufferId = pair.second;
3290 dst.buffer = isNewBuffer ? buf : nullptr;
3291 dst.status = BufferStatus::OK;
3292 native_handle_t *acquireFence = nullptr;
3293 if (src->acquire_fence != -1) {
3294 acquireFence = native_handle_create(1,0);
3295 acquireFence->data[0] = src->acquire_fence;
3296 handlesCreated->push_back(acquireFence);
3297 }
3298 dst.acquireFence = acquireFence;
3299 dst.releaseFence = nullptr;
3300
3301 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3302 src->buffer, src->acquire_fence);
3303 }
3304 }
3305}
3306
3307status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3308 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3309 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3310 if (!valid()) return INVALID_OPERATION;
3311
3312 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3313 size_t batchSize = requests.size();
3314 captureRequests.resize(batchSize);
3315 std::vector<native_handle_t*> handlesCreated;
3316
3317 for (size_t i = 0; i < batchSize; i++) {
3318 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3319 }
3320
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003321 std::vector<device::V3_2::BufferCache> cachesToRemove;
3322 {
3323 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3324 for (auto& pair : mFreedBuffers) {
3325 // The stream might have been removed since onBufferFreed
3326 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3327 cachesToRemove.push_back({pair.first, pair.second});
3328 }
3329 }
3330 mFreedBuffers.clear();
3331 }
3332
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003333 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3334 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003335
3336 // Write metadata to FMQ.
3337 for (size_t i = 0; i < batchSize; i++) {
3338 camera3_capture_request_t* request = requests[i];
3339 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3340
3341 if (request->settings != nullptr) {
3342 size_t settingsSize = get_camera_metadata_size(request->settings);
3343 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3344 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3345 captureRequest->settings.resize(0);
3346 captureRequest->fmqSettingsSize = settingsSize;
3347 } else {
3348 if (mRequestMetadataQueue != nullptr) {
3349 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3350 }
3351 captureRequest->settings.setToExternal(
3352 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3353 get_camera_metadata_size(request->settings));
3354 captureRequest->fmqSettingsSize = 0u;
3355 }
3356 } else {
3357 // A null request settings maps to a size-0 CameraMetadata
3358 captureRequest->settings.resize(0);
3359 captureRequest->fmqSettingsSize = 0u;
3360 }
3361 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003362 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003363 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3364 status = s;
3365 *numRequestProcessed = n;
3366 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003367 if (!err.isOk()) {
3368 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3369 return DEAD_OBJECT;
3370 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003371 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3372 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3373 __FUNCTION__, *numRequestProcessed, batchSize);
3374 status = common::V1_0::Status::INTERNAL_ERROR;
3375 }
3376
3377 for (auto& handle : handlesCreated) {
3378 native_handle_delete(handle);
3379 }
3380 return CameraProviderManager::mapToStatusT(status);
3381}
3382
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003383status_t Camera3Device::HalInterface::processCaptureRequest(
3384 camera3_capture_request_t *request) {
3385 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003386 if (!valid()) return INVALID_OPERATION;
3387 status_t res = OK;
3388
3389 if (mHal3Device != nullptr) {
3390 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3391 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003392 uint32_t numRequestProcessed = 0;
3393 std::vector<camera3_capture_request_t*> requests(1);
3394 requests[0] = request;
3395 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003396 }
3397 return res;
3398}
3399
3400status_t Camera3Device::HalInterface::flush() {
3401 ATRACE_NAME("CameraHal::flush");
3402 if (!valid()) return INVALID_OPERATION;
3403 status_t res = OK;
3404
3405 if (mHal3Device != nullptr) {
3406 res = mHal3Device->ops->flush(mHal3Device);
3407 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003408 auto err = mHidlSession->flush();
3409 if (!err.isOk()) {
3410 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3411 res = DEAD_OBJECT;
3412 } else {
3413 res = CameraProviderManager::mapToStatusT(err);
3414 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003415 }
3416 return res;
3417}
3418
3419status_t Camera3Device::HalInterface::dump(int fd) {
3420 ATRACE_NAME("CameraHal::dump");
3421 if (!valid()) return INVALID_OPERATION;
3422 status_t res = OK;
3423
3424 if (mHal3Device != nullptr) {
3425 mHal3Device->ops->dump(mHal3Device, fd);
3426 } else {
3427 // Handled by CameraProviderManager::dump
3428 }
3429 return res;
3430}
3431
3432status_t Camera3Device::HalInterface::close() {
3433 ATRACE_NAME("CameraHal::close()");
3434 if (!valid()) return INVALID_OPERATION;
3435 status_t res = OK;
3436
3437 if (mHal3Device != nullptr) {
3438 mHal3Device->common.close(&mHal3Device->common);
3439 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003440 auto err = mHidlSession->close();
3441 // Interface will be dead shortly anyway, so don't log errors
3442 if (!err.isOk()) {
3443 res = DEAD_OBJECT;
3444 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003445 }
3446 return res;
3447}
3448
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003449void Camera3Device::HalInterface::getInflightBufferKeys(
3450 std::vector<std::pair<int32_t, int32_t>>* out) {
3451 std::lock_guard<std::mutex> lock(mInflightLock);
3452 out->clear();
3453 out->reserve(mInflightBufferMap.size());
3454 for (auto& pair : mInflightBufferMap) {
3455 uint64_t key = pair.first;
3456 int32_t streamId = key & 0xFFFFFFFF;
3457 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3458 out->push_back(std::make_pair(frameNumber, streamId));
3459 }
3460 return;
3461}
3462
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003463status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003464 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003465 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003466 auto pair = std::make_pair(buffer, acquireFence);
3467 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003468 return OK;
3469}
3470
3471status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003472 int32_t frameNumber, int32_t streamId,
3473 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003474 std::lock_guard<std::mutex> lock(mInflightLock);
3475
3476 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3477 auto it = mInflightBufferMap.find(key);
3478 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003479 auto pair = it->second;
3480 *buffer = pair.first;
3481 int acquireFence = pair.second;
3482 if (acquireFence > 0) {
3483 ::close(acquireFence);
3484 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003485 mInflightBufferMap.erase(it);
3486 return OK;
3487}
3488
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003489std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3490 const buffer_handle_t& buf, int streamId) {
3491 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3492
3493 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3494 auto it = bIdMap.find(buf);
3495 if (it == bIdMap.end()) {
3496 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003497 ALOGV("stream %d now have %zu buffer caches, buf %p",
3498 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003499 return std::make_pair(true, mNextBufferId - 1);
3500 } else {
3501 return std::make_pair(false, it->second);
3502 }
3503}
3504
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003505void Camera3Device::HalInterface::onBufferFreed(
3506 int streamId, const native_handle_t* handle) {
3507 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3508 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3509 auto mapIt = mBufferIdMaps.find(streamId);
3510 if (mapIt == mBufferIdMaps.end()) {
3511 // streamId might be from a deleted stream here
3512 ALOGI("%s: stream %d has been removed",
3513 __FUNCTION__, streamId);
3514 return;
3515 }
3516 BufferIdMap& bIdMap = mapIt->second;
3517 auto it = bIdMap.find(handle);
3518 if (it == bIdMap.end()) {
3519 ALOGW("%s: cannot find buffer %p in stream %d",
3520 __FUNCTION__, handle, streamId);
3521 return;
3522 } else {
3523 bufferId = it->second;
3524 bIdMap.erase(it);
3525 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3526 __FUNCTION__, streamId, bIdMap.size(), handle);
3527 }
3528 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3529}
3530
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003531/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003532 * RequestThread inner class methods
3533 */
3534
3535Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003536 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003537 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003538 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003539 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003540 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003541 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003542 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003543 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003544 mReconfigured(false),
3545 mDoPause(false),
3546 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003547 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003548 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003549 mCurrentAfTriggerId(0),
3550 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003551 mRepeatingLastFrameNumber(
3552 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003553 mPrepareVideoStream(false),
3554 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003555 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003556}
3557
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003558Camera3Device::RequestThread::~RequestThread() {}
3559
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003560void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003561 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003562 Mutex::Autolock l(mRequestLock);
3563 mListener = listener;
3564}
3565
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003566void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003567 Mutex::Autolock l(mRequestLock);
3568 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003569 // Prepare video stream for high speed recording.
3570 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003571}
3572
Jianing Wei90e59c92014-03-12 18:29:36 -07003573status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003574 List<sp<CaptureRequest> > &requests,
3575 /*out*/
3576 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003577 Mutex::Autolock l(mRequestLock);
3578 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3579 ++it) {
3580 mRequestQueue.push_back(*it);
3581 }
3582
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003583 if (lastFrameNumber != NULL) {
3584 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3585 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3586 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3587 *lastFrameNumber);
3588 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003589
Jianing Wei90e59c92014-03-12 18:29:36 -07003590 unpauseForNewRequests();
3591
3592 return OK;
3593}
3594
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003595
3596status_t Camera3Device::RequestThread::queueTrigger(
3597 RequestTrigger trigger[],
3598 size_t count) {
3599
3600 Mutex::Autolock l(mTriggerMutex);
3601 status_t ret;
3602
3603 for (size_t i = 0; i < count; ++i) {
3604 ret = queueTriggerLocked(trigger[i]);
3605
3606 if (ret != OK) {
3607 return ret;
3608 }
3609 }
3610
3611 return OK;
3612}
3613
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003614const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3615 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003616 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003617 if (d != nullptr) return d->mId;
3618 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003619}
3620
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003621status_t Camera3Device::RequestThread::queueTriggerLocked(
3622 RequestTrigger trigger) {
3623
3624 uint32_t tag = trigger.metadataTag;
3625 ssize_t index = mTriggerMap.indexOfKey(tag);
3626
3627 switch (trigger.getTagType()) {
3628 case TYPE_BYTE:
3629 // fall-through
3630 case TYPE_INT32:
3631 break;
3632 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003633 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3634 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003635 return INVALID_OPERATION;
3636 }
3637
3638 /**
3639 * Collect only the latest trigger, since we only have 1 field
3640 * in the request settings per trigger tag, and can't send more than 1
3641 * trigger per request.
3642 */
3643 if (index != NAME_NOT_FOUND) {
3644 mTriggerMap.editValueAt(index) = trigger;
3645 } else {
3646 mTriggerMap.add(tag, trigger);
3647 }
3648
3649 return OK;
3650}
3651
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003652status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003653 const RequestList &requests,
3654 /*out*/
3655 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003656 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003657 if (lastFrameNumber != NULL) {
3658 *lastFrameNumber = mRepeatingLastFrameNumber;
3659 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003660 mRepeatingRequests.clear();
3661 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3662 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003663
3664 unpauseForNewRequests();
3665
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003666 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003667 return OK;
3668}
3669
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003670bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003671 if (mRepeatingRequests.empty()) {
3672 return false;
3673 }
3674 int32_t requestId = requestIn->mResultExtras.requestId;
3675 const RequestList &repeatRequests = mRepeatingRequests;
3676 // All repeating requests are guaranteed to have same id so only check first quest
3677 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3678 return (firstRequest->mResultExtras.requestId == requestId);
3679}
3680
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003681status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003682 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003683 return clearRepeatingRequestsLocked(lastFrameNumber);
3684
3685}
3686
3687status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003688 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003689 if (lastFrameNumber != NULL) {
3690 *lastFrameNumber = mRepeatingLastFrameNumber;
3691 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003692 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003693 return OK;
3694}
3695
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003696status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003697 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003698 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003699 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003700
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003701 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003702
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003703 // Send errors for all requests pending in the request queue, including
3704 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003705 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003706 if (listener != NULL) {
3707 for (RequestList::iterator it = mRequestQueue.begin();
3708 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003709 // Abort the input buffers for reprocess requests.
3710 if ((*it)->mInputStream != NULL) {
3711 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003712 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3713 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003714 if (res != OK) {
3715 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3716 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3717 } else {
3718 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3719 if (res != OK) {
3720 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3721 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3722 }
3723 }
3724 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003725 // Set the frame number this request would have had, if it
3726 // had been submitted; this frame number will not be reused.
3727 // The requestId and burstId fields were set when the request was
3728 // submitted originally (in convertMetadataListToRequestListLocked)
3729 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003730 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003731 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003732 }
3733 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003734 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003735
3736 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003737 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003738 if (lastFrameNumber != NULL) {
3739 *lastFrameNumber = mRepeatingLastFrameNumber;
3740 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003741 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003742 return OK;
3743}
3744
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003745status_t Camera3Device::RequestThread::flush() {
3746 ATRACE_CALL();
3747 Mutex::Autolock l(mFlushLock);
3748
Emilian Peev08dd2452017-04-06 16:55:14 +01003749 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003750}
3751
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003752void Camera3Device::RequestThread::setPaused(bool paused) {
3753 Mutex::Autolock l(mPauseLock);
3754 mDoPause = paused;
3755 mDoPauseSignal.signal();
3756}
3757
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003758status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3759 int32_t requestId, nsecs_t timeout) {
3760 Mutex::Autolock l(mLatestRequestMutex);
3761 status_t res;
3762 while (mLatestRequestId != requestId) {
3763 nsecs_t startTime = systemTime();
3764
3765 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3766 if (res != OK) return res;
3767
3768 timeout -= (systemTime() - startTime);
3769 }
3770
3771 return OK;
3772}
3773
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003774void Camera3Device::RequestThread::requestExit() {
3775 // Call parent to set up shutdown
3776 Thread::requestExit();
3777 // The exit from any possible waits
3778 mDoPauseSignal.signal();
3779 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003780
3781 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3782 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003783}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003784
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003785void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003786 bool surfaceAbandoned = false;
3787 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003788 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003789 {
3790 Mutex::Autolock l(mRequestLock);
3791 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3792 // repeating requests.
3793 for (const auto& request : mRepeatingRequests) {
3794 for (const auto& s : request->mOutputStreams) {
3795 if (s->isAbandoned()) {
3796 surfaceAbandoned = true;
3797 clearRepeatingRequestsLocked(&lastFrameNumber);
3798 break;
3799 }
3800 }
3801 if (surfaceAbandoned) {
3802 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003803 }
3804 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003805 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003806 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003807
3808 if (listener != NULL && surfaceAbandoned) {
3809 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003810 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003811}
3812
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003813bool Camera3Device::RequestThread::sendRequestsBatch() {
3814 status_t res;
3815 size_t batchSize = mNextRequests.size();
3816 std::vector<camera3_capture_request_t*> requests(batchSize);
3817 uint32_t numRequestProcessed = 0;
3818 for (size_t i = 0; i < batchSize; i++) {
3819 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3820 }
3821
3822 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3823 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3824
3825 bool triggerRemoveFailed = false;
3826 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3827 for (size_t i = 0; i < numRequestProcessed; i++) {
3828 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3829 nextRequest.submitted = true;
3830
3831
3832 // Update the latest request sent to HAL
3833 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3834 Mutex::Autolock al(mLatestRequestMutex);
3835
3836 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3837 mLatestRequest.acquire(cloned);
3838
3839 sp<Camera3Device> parent = mParent.promote();
3840 if (parent != NULL) {
3841 parent->monitorMetadata(TagMonitor::REQUEST,
3842 nextRequest.halRequest.frame_number,
3843 0, mLatestRequest);
3844 }
3845 }
3846
3847 if (nextRequest.halRequest.settings != NULL) {
3848 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3849 }
3850
3851 if (!triggerRemoveFailed) {
3852 // Remove any previously queued triggers (after unlock)
3853 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3854 if (removeTriggerRes != OK) {
3855 triggerRemoveFailed = true;
3856 triggerFailedRequest = nextRequest;
3857 }
3858 }
3859 }
3860
3861 if (triggerRemoveFailed) {
3862 SET_ERR("RequestThread: Unable to remove triggers "
3863 "(capture request %d, HAL device: %s (%d)",
3864 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3865 cleanUpFailedRequests(/*sendRequestError*/ false);
3866 return false;
3867 }
3868
3869 if (res != OK) {
3870 // Should only get a failure here for malformed requests or device-level
3871 // errors, so consider all errors fatal. Bad metadata failures should
3872 // come through notify.
3873 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3874 mNextRequests[numRequestProcessed].halRequest.frame_number,
3875 strerror(-res), res);
3876 cleanUpFailedRequests(/*sendRequestError*/ false);
3877 return false;
3878 }
3879 return true;
3880}
3881
3882bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3883 status_t res;
3884
3885 for (auto& nextRequest : mNextRequests) {
3886 // Submit request and block until ready for next one
3887 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3888 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3889
3890 if (res != OK) {
3891 // Should only get a failure here for malformed requests or device-level
3892 // errors, so consider all errors fatal. Bad metadata failures should
3893 // come through notify.
3894 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3895 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3896 res);
3897 cleanUpFailedRequests(/*sendRequestError*/ false);
3898 return false;
3899 }
3900
3901 // Mark that the request has be submitted successfully.
3902 nextRequest.submitted = true;
3903
3904 // Update the latest request sent to HAL
3905 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3906 Mutex::Autolock al(mLatestRequestMutex);
3907
3908 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3909 mLatestRequest.acquire(cloned);
3910
3911 sp<Camera3Device> parent = mParent.promote();
3912 if (parent != NULL) {
3913 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3914 0, mLatestRequest);
3915 }
3916 }
3917
3918 if (nextRequest.halRequest.settings != NULL) {
3919 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3920 }
3921
3922 // Remove any previously queued triggers (after unlock)
3923 res = removeTriggers(mPrevRequest);
3924 if (res != OK) {
3925 SET_ERR("RequestThread: Unable to remove triggers "
3926 "(capture request %d, HAL device: %s (%d)",
3927 nextRequest.halRequest.frame_number, strerror(-res), res);
3928 cleanUpFailedRequests(/*sendRequestError*/ false);
3929 return false;
3930 }
3931 }
3932 return true;
3933}
3934
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003935nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3936 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3937 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3938 find_camera_metadata_ro_entry(request,
3939 ANDROID_CONTROL_AE_MODE,
3940 &e);
3941 if (e.count == 0) return maxExpectedDuration;
3942
3943 switch (e.data.u8[0]) {
3944 case ANDROID_CONTROL_AE_MODE_OFF:
3945 find_camera_metadata_ro_entry(request,
3946 ANDROID_SENSOR_EXPOSURE_TIME,
3947 &e);
3948 if (e.count > 0) {
3949 maxExpectedDuration = e.data.i64[0];
3950 }
3951 find_camera_metadata_ro_entry(request,
3952 ANDROID_SENSOR_FRAME_DURATION,
3953 &e);
3954 if (e.count > 0) {
3955 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3956 }
3957 break;
3958 default:
3959 find_camera_metadata_ro_entry(request,
3960 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3961 &e);
3962 if (e.count > 1) {
3963 maxExpectedDuration = 1e9 / e.data.u8[0];
3964 }
3965 break;
3966 }
3967
3968 return maxExpectedDuration;
3969}
3970
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003971bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003972 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003973 status_t res;
3974
3975 // Handle paused state.
3976 if (waitIfPaused()) {
3977 return true;
3978 }
3979
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003980 // Wait for the next batch of requests.
3981 waitForNextRequestBatch();
3982 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003983 return true;
3984 }
3985
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003986 // Get the latest request ID, if any
3987 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003988 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003989 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003990 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003991 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003992 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003993 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3994 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003995 }
3996
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003997 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003998 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003999 if (res == TIMED_OUT) {
4000 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004001 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004002 // Check if any stream is abandoned.
4003 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004004 return true;
4005 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004006 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004007 return false;
4008 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004009
Zhijun Hecc27e112013-10-03 16:12:43 -07004010 // Inform waitUntilRequestProcessed thread of a new request ID
4011 {
4012 Mutex::Autolock al(mLatestRequestMutex);
4013
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004014 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004015 mLatestRequestSignal.signal();
4016 }
4017
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004018 // Submit a batch of requests to HAL.
4019 // Use flush lock only when submitting multilple requests in a batch.
4020 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4021 // which may take a long time to finish so synchronizing flush() and
4022 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4023 // For now, only synchronize for high speed recording and we should figure something out for
4024 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004025 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004026
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004027 if (useFlushLock) {
4028 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004029 }
4030
Zhijun Hef0645c12016-08-02 00:58:11 -07004031 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004032 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004033
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004034 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004035 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004036 if (mInterface->supportBatchRequest()) {
4037 submitRequestSuccess = sendRequestsBatch();
4038 } else {
4039 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004040 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004041 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4042 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004043
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004044 if (useFlushLock) {
4045 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004046 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004047
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004048 // Unset as current request
4049 {
4050 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004051 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004052 }
4053
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004054 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004055}
4056
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004057status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004058 ATRACE_CALL();
4059
Shuzhen Wang4a472662017-02-26 23:29:04 -08004060 for (size_t i = 0; i < mNextRequests.size(); i++) {
4061 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004062 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4063 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4064 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4065
4066 // Prepare a request to HAL
4067 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4068
4069 // Insert any queued triggers (before metadata is locked)
4070 status_t res = insertTriggers(captureRequest);
4071
4072 if (res < 0) {
4073 SET_ERR("RequestThread: Unable to insert triggers "
4074 "(capture request %d, HAL device: %s (%d)",
4075 halRequest->frame_number, strerror(-res), res);
4076 return INVALID_OPERATION;
4077 }
4078 int triggerCount = res;
4079 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4080 mPrevTriggers = triggerCount;
4081
4082 // If the request is the same as last, or we had triggers last time
4083 if (mPrevRequest != captureRequest || triggersMixedIn) {
4084 /**
4085 * HAL workaround:
4086 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4087 */
4088 res = addDummyTriggerIds(captureRequest);
4089 if (res != OK) {
4090 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4091 "(capture request %d, HAL device: %s (%d)",
4092 halRequest->frame_number, strerror(-res), res);
4093 return INVALID_OPERATION;
4094 }
4095
4096 /**
4097 * The request should be presorted so accesses in HAL
4098 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4099 */
4100 captureRequest->mSettings.sort();
4101 halRequest->settings = captureRequest->mSettings.getAndLock();
4102 mPrevRequest = captureRequest;
4103 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4104
4105 IF_ALOGV() {
4106 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4107 find_camera_metadata_ro_entry(
4108 halRequest->settings,
4109 ANDROID_CONTROL_AF_TRIGGER,
4110 &e
4111 );
4112 if (e.count > 0) {
4113 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4114 __FUNCTION__,
4115 halRequest->frame_number,
4116 e.data.u8[0]);
4117 }
4118 }
4119 } else {
4120 // leave request.settings NULL to indicate 'reuse latest given'
4121 ALOGVV("%s: Request settings are REUSED",
4122 __FUNCTION__);
4123 }
4124
4125 uint32_t totalNumBuffers = 0;
4126
4127 // Fill in buffers
4128 if (captureRequest->mInputStream != NULL) {
4129 halRequest->input_buffer = &captureRequest->mInputBuffer;
4130 totalNumBuffers += 1;
4131 } else {
4132 halRequest->input_buffer = NULL;
4133 }
4134
4135 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4136 captureRequest->mOutputStreams.size());
4137 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004138 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4139 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004140
4141 // Prepare video buffers for high speed recording on the first video request.
4142 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4143 // Only try to prepare video stream on the first video request.
4144 mPrepareVideoStream = false;
4145
4146 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4147 while (res == NOT_ENOUGH_DATA) {
4148 res = outputStream->prepareNextBuffer();
4149 }
4150 if (res != OK) {
4151 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4152 __FUNCTION__, strerror(-res), res);
4153 outputStream->cancelPrepare();
4154 }
4155 }
4156
Shuzhen Wang4a472662017-02-26 23:29:04 -08004157 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4158 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004159 if (res != OK) {
4160 // Can't get output buffer from gralloc queue - this could be due to
4161 // abandoned queue or other consumer misbehavior, so not a fatal
4162 // error
4163 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4164 " %s (%d)", strerror(-res), res);
4165
4166 return TIMED_OUT;
4167 }
4168 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004169
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004170 }
4171 totalNumBuffers += halRequest->num_output_buffers;
4172
4173 // Log request in the in-flight queue
4174 sp<Camera3Device> parent = mParent.promote();
4175 if (parent == NULL) {
4176 // Should not happen, and nowhere to send errors to, so just log it
4177 CLOGE("RequestThread: Parent is gone");
4178 return INVALID_OPERATION;
4179 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004180
4181 // If this request list is for constrained high speed recording (not
4182 // preview), and the current request is not the last one in the batch,
4183 // do not send callback to the app.
4184 bool hasCallback = true;
4185 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4186 hasCallback = false;
4187 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004188 res = parent->registerInFlight(halRequest->frame_number,
4189 totalNumBuffers, captureRequest->mResultExtras,
4190 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004191 hasCallback,
4192 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004193 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4194 ", burstId = %" PRId32 ".",
4195 __FUNCTION__,
4196 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4197 captureRequest->mResultExtras.burstId);
4198 if (res != OK) {
4199 SET_ERR("RequestThread: Unable to register new in-flight request:"
4200 " %s (%d)", strerror(-res), res);
4201 return INVALID_OPERATION;
4202 }
4203 }
4204
4205 return OK;
4206}
4207
Igor Murashkin1e479c02013-09-06 16:55:14 -07004208CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4209 Mutex::Autolock al(mLatestRequestMutex);
4210
4211 ALOGV("RequestThread::%s", __FUNCTION__);
4212
4213 return mLatestRequest;
4214}
4215
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004216bool Camera3Device::RequestThread::isStreamPending(
4217 sp<Camera3StreamInterface>& stream) {
4218 Mutex::Autolock l(mRequestLock);
4219
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004220 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004221 if (!nextRequest.submitted) {
4222 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4223 if (stream == s) return true;
4224 }
4225 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004226 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004227 }
4228
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004229 for (const auto& request : mRequestQueue) {
4230 for (const auto& s : request->mOutputStreams) {
4231 if (stream == s) return true;
4232 }
4233 if (stream == request->mInputStream) return true;
4234 }
4235
4236 for (const auto& request : mRepeatingRequests) {
4237 for (const auto& s : request->mOutputStreams) {
4238 if (stream == s) return true;
4239 }
4240 if (stream == request->mInputStream) return true;
4241 }
4242
4243 return false;
4244}
Jianing Weicb0652e2014-03-12 18:29:36 -07004245
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004246nsecs_t Camera3Device::getExpectedInFlightDurationLocked() {
4247 return mExpectedInflightDuration > kMinInflightDuration ?
4248 mExpectedInflightDuration : kMinInflightDuration;
4249}
4250
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004251void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4252 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004253 return;
4254 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004256 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004257 // Skip the ones that have been submitted successfully.
4258 if (nextRequest.submitted) {
4259 continue;
4260 }
4261
4262 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4263 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4264 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4265
4266 if (halRequest->settings != NULL) {
4267 captureRequest->mSettings.unlock(halRequest->settings);
4268 }
4269
4270 if (captureRequest->mInputStream != NULL) {
4271 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4272 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4273 }
4274
4275 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004276 //Buffers that failed processing could still have
4277 //valid acquire fence.
4278 int acquireFence = (*outputBuffers)[i].acquire_fence;
4279 if (0 <= acquireFence) {
4280 close(acquireFence);
4281 outputBuffers->editItemAt(i).acquire_fence = -1;
4282 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004283 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4284 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4285 }
4286
4287 if (sendRequestError) {
4288 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004289 sp<NotificationListener> listener = mListener.promote();
4290 if (listener != NULL) {
4291 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004292 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004293 captureRequest->mResultExtras);
4294 }
4295 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004296
4297 // Remove yet-to-be submitted inflight request from inflightMap
4298 {
4299 sp<Camera3Device> parent = mParent.promote();
4300 if (parent != NULL) {
4301 Mutex::Autolock l(parent->mInFlightLock);
4302 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4303 if (idx >= 0) {
4304 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4305 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4306 parent->removeInFlightMapEntryLocked(idx);
4307 }
4308 }
4309 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004311
4312 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004313 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314}
4315
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004316void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 // Optimized a bit for the simple steady-state case (single repeating
4318 // request), to avoid putting that request in the queue temporarily.
4319 Mutex::Autolock l(mRequestLock);
4320
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004321 assert(mNextRequests.empty());
4322
4323 NextRequest nextRequest;
4324 nextRequest.captureRequest = waitForNextRequestLocked();
4325 if (nextRequest.captureRequest == nullptr) {
4326 return;
4327 }
4328
4329 nextRequest.halRequest = camera3_capture_request_t();
4330 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004331 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004332
4333 // Wait for additional requests
4334 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4335
4336 for (size_t i = 1; i < batchSize; i++) {
4337 NextRequest additionalRequest;
4338 additionalRequest.captureRequest = waitForNextRequestLocked();
4339 if (additionalRequest.captureRequest == nullptr) {
4340 break;
4341 }
4342
4343 additionalRequest.halRequest = camera3_capture_request_t();
4344 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004345 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004346 }
4347
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004348 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004349 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004350 mNextRequests.size(), batchSize);
4351 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004352 }
4353
4354 return;
4355}
4356
4357sp<Camera3Device::CaptureRequest>
4358 Camera3Device::RequestThread::waitForNextRequestLocked() {
4359 status_t res;
4360 sp<CaptureRequest> nextRequest;
4361
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004362 while (mRequestQueue.empty()) {
4363 if (!mRepeatingRequests.empty()) {
4364 // Always atomically enqueue all requests in a repeating request
4365 // list. Guarantees a complete in-sequence set of captures to
4366 // application.
4367 const RequestList &requests = mRepeatingRequests;
4368 RequestList::const_iterator firstRequest =
4369 requests.begin();
4370 nextRequest = *firstRequest;
4371 mRequestQueue.insert(mRequestQueue.end(),
4372 ++firstRequest,
4373 requests.end());
4374 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004375
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004376 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004377
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004378 break;
4379 }
4380
4381 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4382
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004383 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4384 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004385 Mutex::Autolock pl(mPauseLock);
4386 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004387 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004388 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004389 // Let the tracker know
4390 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4391 if (statusTracker != 0) {
4392 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004394 }
4395 // Stop waiting for now and let thread management happen
4396 return NULL;
4397 }
4398 }
4399
4400 if (nextRequest == NULL) {
4401 // Don't have a repeating request already in hand, so queue
4402 // must have an entry now.
4403 RequestList::iterator firstRequest =
4404 mRequestQueue.begin();
4405 nextRequest = *firstRequest;
4406 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004407 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4408 sp<NotificationListener> listener = mListener.promote();
4409 if (listener != NULL) {
4410 listener->notifyRequestQueueEmpty();
4411 }
4412 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 }
4414
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004415 // In case we've been unpaused by setPaused clearing mDoPause, need to
4416 // update internal pause state (capture/setRepeatingRequest unpause
4417 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004419 if (mPaused) {
4420 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4421 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4422 if (statusTracker != 0) {
4423 statusTracker->markComponentActive(mStatusId);
4424 }
4425 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004426 mPaused = false;
4427
4428 // Check if we've reconfigured since last time, and reset the preview
4429 // request if so. Can't use 'NULL request == repeat' across configure calls.
4430 if (mReconfigured) {
4431 mPrevRequest.clear();
4432 mReconfigured = false;
4433 }
4434
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004435 if (nextRequest != NULL) {
4436 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004437 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4438 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004439
4440 // Since RequestThread::clear() removes buffers from the input stream,
4441 // get the right buffer here before unlocking mRequestLock
4442 if (nextRequest->mInputStream != NULL) {
4443 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4444 if (res != OK) {
4445 // Can't get input buffer from gralloc queue - this could be due to
4446 // disconnected queue or other producer misbehavior, so not a fatal
4447 // error
4448 ALOGE("%s: Can't get input buffer, skipping request:"
4449 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004450
4451 sp<NotificationListener> listener = mListener.promote();
4452 if (listener != NULL) {
4453 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004454 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004455 nextRequest->mResultExtras);
4456 }
4457 return NULL;
4458 }
4459 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004460 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004461
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004462 return nextRequest;
4463}
4464
4465bool Camera3Device::RequestThread::waitIfPaused() {
4466 status_t res;
4467 Mutex::Autolock l(mPauseLock);
4468 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004469 if (mPaused == false) {
4470 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004471 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4472 // Let the tracker know
4473 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4474 if (statusTracker != 0) {
4475 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4476 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004477 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004478
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004480 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004481 return true;
4482 }
4483 }
4484 // We don't set mPaused to false here, because waitForNextRequest needs
4485 // to further manage the paused state in case of starvation.
4486 return false;
4487}
4488
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004489void Camera3Device::RequestThread::unpauseForNewRequests() {
4490 // With work to do, mark thread as unpaused.
4491 // If paused by request (setPaused), don't resume, to avoid
4492 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004493 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004494 Mutex::Autolock p(mPauseLock);
4495 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004496 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4497 if (mPaused) {
4498 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4499 if (statusTracker != 0) {
4500 statusTracker->markComponentActive(mStatusId);
4501 }
4502 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004503 mPaused = false;
4504 }
4505}
4506
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004507void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4508 sp<Camera3Device> parent = mParent.promote();
4509 if (parent != NULL) {
4510 va_list args;
4511 va_start(args, fmt);
4512
4513 parent->setErrorStateV(fmt, args);
4514
4515 va_end(args);
4516 }
4517}
4518
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004519status_t Camera3Device::RequestThread::insertTriggers(
4520 const sp<CaptureRequest> &request) {
4521
4522 Mutex::Autolock al(mTriggerMutex);
4523
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004524 sp<Camera3Device> parent = mParent.promote();
4525 if (parent == NULL) {
4526 CLOGE("RequestThread: Parent is gone");
4527 return DEAD_OBJECT;
4528 }
4529
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004530 CameraMetadata &metadata = request->mSettings;
4531 size_t count = mTriggerMap.size();
4532
4533 for (size_t i = 0; i < count; ++i) {
4534 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004535 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004536
4537 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4538 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4539 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004540 if (isAeTrigger) {
4541 request->mResultExtras.precaptureTriggerId = triggerId;
4542 mCurrentPreCaptureTriggerId = triggerId;
4543 } else {
4544 request->mResultExtras.afTriggerId = triggerId;
4545 mCurrentAfTriggerId = triggerId;
4546 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004547 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004548 }
4549
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004550 camera_metadata_entry entry = metadata.find(tag);
4551
4552 if (entry.count > 0) {
4553 /**
4554 * Already has an entry for this trigger in the request.
4555 * Rewrite it with our requested trigger value.
4556 */
4557 RequestTrigger oldTrigger = trigger;
4558
4559 oldTrigger.entryValue = entry.data.u8[0];
4560
4561 mTriggerReplacedMap.add(tag, oldTrigger);
4562 } else {
4563 /**
4564 * More typical, no trigger entry, so we just add it
4565 */
4566 mTriggerRemovedMap.add(tag, trigger);
4567 }
4568
4569 status_t res;
4570
4571 switch (trigger.getTagType()) {
4572 case TYPE_BYTE: {
4573 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4574 res = metadata.update(tag,
4575 &entryValue,
4576 /*count*/1);
4577 break;
4578 }
4579 case TYPE_INT32:
4580 res = metadata.update(tag,
4581 &trigger.entryValue,
4582 /*count*/1);
4583 break;
4584 default:
4585 ALOGE("%s: Type not supported: 0x%x",
4586 __FUNCTION__,
4587 trigger.getTagType());
4588 return INVALID_OPERATION;
4589 }
4590
4591 if (res != OK) {
4592 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4593 ", value %d", __FUNCTION__, trigger.getTagName(),
4594 trigger.entryValue);
4595 return res;
4596 }
4597
4598 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4599 trigger.getTagName(),
4600 trigger.entryValue);
4601 }
4602
4603 mTriggerMap.clear();
4604
4605 return count;
4606}
4607
4608status_t Camera3Device::RequestThread::removeTriggers(
4609 const sp<CaptureRequest> &request) {
4610 Mutex::Autolock al(mTriggerMutex);
4611
4612 CameraMetadata &metadata = request->mSettings;
4613
4614 /**
4615 * Replace all old entries with their old values.
4616 */
4617 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4618 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4619
4620 status_t res;
4621
4622 uint32_t tag = trigger.metadataTag;
4623 switch (trigger.getTagType()) {
4624 case TYPE_BYTE: {
4625 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4626 res = metadata.update(tag,
4627 &entryValue,
4628 /*count*/1);
4629 break;
4630 }
4631 case TYPE_INT32:
4632 res = metadata.update(tag,
4633 &trigger.entryValue,
4634 /*count*/1);
4635 break;
4636 default:
4637 ALOGE("%s: Type not supported: 0x%x",
4638 __FUNCTION__,
4639 trigger.getTagType());
4640 return INVALID_OPERATION;
4641 }
4642
4643 if (res != OK) {
4644 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4645 ", trigger value %d", __FUNCTION__,
4646 trigger.getTagName(), trigger.entryValue);
4647 return res;
4648 }
4649 }
4650 mTriggerReplacedMap.clear();
4651
4652 /**
4653 * Remove all new entries.
4654 */
4655 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4656 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4657 status_t res = metadata.erase(trigger.metadataTag);
4658
4659 if (res != OK) {
4660 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4661 ", trigger value %d", __FUNCTION__,
4662 trigger.getTagName(), trigger.entryValue);
4663 return res;
4664 }
4665 }
4666 mTriggerRemovedMap.clear();
4667
4668 return OK;
4669}
4670
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004671status_t Camera3Device::RequestThread::addDummyTriggerIds(
4672 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004673 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004674 static const int32_t dummyTriggerId = 1;
4675 status_t res;
4676
4677 CameraMetadata &metadata = request->mSettings;
4678
4679 // If AF trigger is active, insert a dummy AF trigger ID if none already
4680 // exists
4681 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4682 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4683 if (afTrigger.count > 0 &&
4684 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4685 afId.count == 0) {
4686 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4687 if (res != OK) return res;
4688 }
4689
4690 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4691 // if none already exists
4692 camera_metadata_entry pcTrigger =
4693 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4694 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4695 if (pcTrigger.count > 0 &&
4696 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4697 pcId.count == 0) {
4698 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4699 &dummyTriggerId, 1);
4700 if (res != OK) return res;
4701 }
4702
4703 return OK;
4704}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004705
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004706/**
4707 * PreparerThread inner class methods
4708 */
4709
4710Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004711 Thread(/*canCallJava*/false), mListener(nullptr),
4712 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004713}
4714
4715Camera3Device::PreparerThread::~PreparerThread() {
4716 Thread::requestExitAndWait();
4717 if (mCurrentStream != nullptr) {
4718 mCurrentStream->cancelPrepare();
4719 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4720 mCurrentStream.clear();
4721 }
4722 clear();
4723}
4724
Ruben Brunkc78ac262015-08-13 17:58:46 -07004725status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004726 status_t res;
4727
4728 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004729 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004730
Ruben Brunkc78ac262015-08-13 17:58:46 -07004731 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004732 if (res == OK) {
4733 // No preparation needed, fire listener right off
4734 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004735 if (listener != NULL) {
4736 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004737 }
4738 return OK;
4739 } else if (res != NOT_ENOUGH_DATA) {
4740 return res;
4741 }
4742
4743 // Need to prepare, start up thread if necessary
4744 if (!mActive) {
4745 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4746 // isn't running
4747 Thread::requestExitAndWait();
4748 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4749 if (res != OK) {
4750 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004751 if (listener != NULL) {
4752 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004753 }
4754 return res;
4755 }
4756 mCancelNow = false;
4757 mActive = true;
4758 ALOGV("%s: Preparer stream started", __FUNCTION__);
4759 }
4760
4761 // queue up the work
4762 mPendingStreams.push_back(stream);
4763 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4764
4765 return OK;
4766}
4767
4768status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004769 Mutex::Autolock l(mLock);
4770
4771 for (const auto& stream : mPendingStreams) {
4772 stream->cancelPrepare();
4773 }
4774 mPendingStreams.clear();
4775 mCancelNow = true;
4776
4777 return OK;
4778}
4779
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004780void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004781 Mutex::Autolock l(mLock);
4782 mListener = listener;
4783}
4784
4785bool Camera3Device::PreparerThread::threadLoop() {
4786 status_t res;
4787 {
4788 Mutex::Autolock l(mLock);
4789 if (mCurrentStream == nullptr) {
4790 // End thread if done with work
4791 if (mPendingStreams.empty()) {
4792 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4793 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4794 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4795 mActive = false;
4796 return false;
4797 }
4798
4799 // Get next stream to prepare
4800 auto it = mPendingStreams.begin();
4801 mCurrentStream = *it;
4802 mPendingStreams.erase(it);
4803 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4804 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4805 } else if (mCancelNow) {
4806 mCurrentStream->cancelPrepare();
4807 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4808 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4809 mCurrentStream.clear();
4810 mCancelNow = false;
4811 return true;
4812 }
4813 }
4814
4815 res = mCurrentStream->prepareNextBuffer();
4816 if (res == NOT_ENOUGH_DATA) return true;
4817 if (res != OK) {
4818 // Something bad happened; try to recover by cancelling prepare and
4819 // signalling listener anyway
4820 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4821 mCurrentStream->getId(), res, strerror(-res));
4822 mCurrentStream->cancelPrepare();
4823 }
4824
4825 // This stream has finished, notify listener
4826 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004827 sp<NotificationListener> listener = mListener.promote();
4828 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004829 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4830 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004831 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004832 }
4833
4834 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4835 mCurrentStream.clear();
4836
4837 return true;
4838}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004839
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004840/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004841 * Static callback forwarding methods from HAL to instance
4842 */
4843
4844void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4845 const camera3_capture_result *result) {
4846 Camera3Device *d =
4847 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004848
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004849 d->processCaptureResult(result);
4850}
4851
4852void Camera3Device::sNotify(const camera3_callback_ops *cb,
4853 const camera3_notify_msg *msg) {
4854 Camera3Device *d =
4855 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4856 d->notify(msg);
4857}
4858
4859}; // namespace android