blob: 16fcfb1c1db39ed6e7eedd96869da5accadc1f37 [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 Yehf3fe36f2017-07-07 18:23:18 -0700857 {
858 Mutex::Autolock l(mLock);
859 if (mStatus == STATUS_ERROR) {
860 // Per API contract, HAL should act as closed after device error
861 ALOGW("%s: received capture result in error state!", __FUNCTION__);
862 }
863 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700864
865 if (mProcessCaptureResultLock.tryLock() != OK) {
866 // This should never happen; it indicates a wrong client implementation
867 // that doesn't follow the contract. But, we can be tolerant here.
868 ALOGE("%s: callback overlapped! waiting 1s...",
869 __FUNCTION__);
870 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
871 ALOGE("%s: cannot acquire lock in 1s, dropping results",
872 __FUNCTION__);
873 // really don't know what to do, so bail out.
874 return hardware::Void();
875 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800876 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700877 for (const auto& result : results) {
878 processOneCaptureResultLocked(result);
879 }
880 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800881 return hardware::Void();
882}
883
Yifan Honga640c5a2017-04-12 16:30:31 -0700884void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800885 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800886 camera3_capture_result r;
887 status_t res;
888 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700889
890 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
891 if (result.fmqResultSize > 0) {
892 resultMetadata.resize(result.fmqResultSize);
893 if (mResultMetadataQueue == nullptr) {
894 return; // logged in initialize()
895 }
896 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
897 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
898 __FUNCTION__, result.frameNumber, result.fmqResultSize);
899 return;
900 }
901 } else {
902 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
903 result.result.size());
904 }
905
906 if (resultMetadata.size() != 0) {
907 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
908 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800909 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
910 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
911 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800912 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800913 }
914 } else {
915 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800916 }
917
918 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
919 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
920 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
921 auto& bDst = outputBuffers[i];
922 const StreamBuffer &bSrc = result.outputBuffers[i];
923
924 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100925 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
927 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800928 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800929 }
930 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
931
932 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800933 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800934 if (res != OK) {
935 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
936 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800937 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800938 }
939 bDst.buffer = buffer;
940 bDst.status = mapHidlBufferStatus(bSrc.status);
941 bDst.acquire_fence = -1;
942 if (bSrc.releaseFence == nullptr) {
943 bDst.release_fence = -1;
944 } else if (bSrc.releaseFence->numFds == 1) {
945 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
946 } else {
947 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
948 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800949 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800950 }
951 }
952 r.num_output_buffers = outputBuffers.size();
953 r.output_buffers = outputBuffers.data();
954
955 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800956 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800957 r.input_buffer = nullptr;
958 } else {
959 if (mInputStream->getId() != result.inputBuffer.streamId) {
960 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
961 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800962 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800963 }
964 inputBuffer.stream = mInputStream->asHalStream();
965 buffer_handle_t *buffer;
966 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
967 &buffer);
968 if (res != OK) {
969 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
970 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800971 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800972 }
973 inputBuffer.buffer = buffer;
974 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
975 inputBuffer.acquire_fence = -1;
976 if (result.inputBuffer.releaseFence == nullptr) {
977 inputBuffer.release_fence = -1;
978 } else if (result.inputBuffer.releaseFence->numFds == 1) {
979 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
980 } else {
981 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
982 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800983 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800984 }
985 r.input_buffer = &inputBuffer;
986 }
987
988 r.partial_result = result.partialResult;
989
990 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800991}
992
993hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800994 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700995 {
996 Mutex::Autolock l(mLock);
997 if (mStatus == STATUS_ERROR) {
998 // Per API contract, HAL should act as closed after device error
999 ALOGW("%s: received notify message in error state!", __FUNCTION__);
1000 }
1001 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001002 for (const auto& msg : msgs) {
1003 notify(msg);
1004 }
1005 return hardware::Void();
1006}
1007
1008void Camera3Device::notify(
1009 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1010
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001011 camera3_notify_msg m;
1012 switch (msg.type) {
1013 case MsgType::ERROR:
1014 m.type = CAMERA3_MSG_ERROR;
1015 m.message.error.frame_number = msg.msg.error.frameNumber;
1016 if (msg.msg.error.errorStreamId >= 0) {
1017 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001018 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001019 ALOGE("%s: Frame %d: Invalid error stream id %d",
1020 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001021 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001022 }
1023 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1024 } else {
1025 m.message.error.error_stream = nullptr;
1026 }
1027 switch (msg.msg.error.errorCode) {
1028 case ErrorCode::ERROR_DEVICE:
1029 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1030 break;
1031 case ErrorCode::ERROR_REQUEST:
1032 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1033 break;
1034 case ErrorCode::ERROR_RESULT:
1035 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1036 break;
1037 case ErrorCode::ERROR_BUFFER:
1038 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1039 break;
1040 }
1041 break;
1042 case MsgType::SHUTTER:
1043 m.type = CAMERA3_MSG_SHUTTER;
1044 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1045 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1046 break;
1047 }
1048 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001049}
1050
Jianing Weicb0652e2014-03-12 18:29:36 -07001051status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001052 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001053 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001054 ATRACE_CALL();
1055
Shuzhen Wang0129d522016-10-30 22:43:41 -07001056 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001057}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001058
Jianing Weicb0652e2014-03-12 18:29:36 -07001059status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1060 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001061 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001062
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001063 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001064 std::list<const SurfaceMap> surfaceMaps;
1065 convertToRequestList(requests, surfaceMaps, request);
1066
1067 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1068 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069}
1070
Jianing Weicb0652e2014-03-12 18:29:36 -07001071status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001072 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001073 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001074 ATRACE_CALL();
1075
Shuzhen Wang0129d522016-10-30 22:43:41 -07001076 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001077}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001078
1079sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001080 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001081 status_t res;
1082
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001083 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001084 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1085 // so unilaterally select normal operating mode.
1086 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001087 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001089 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001091 } else if (mStatus == STATUS_UNCONFIGURED) {
1092 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001093 CLOGE("No streams configured");
1094 return NULL;
1095 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096 }
1097
Shuzhen Wang0129d522016-10-30 22:43:41 -07001098 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001099 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001100}
1101
Jianing Weicb0652e2014-03-12 18:29:36 -07001102status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001103 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001104 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001105 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 switch (mStatus) {
1108 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001109 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001110 return INVALID_OPERATION;
1111 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001112 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001113 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001114 case STATUS_UNCONFIGURED:
1115 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001116 case STATUS_ACTIVE:
1117 // OK
1118 break;
1119 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001120 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 return INVALID_OPERATION;
1122 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001123 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001124
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001125 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001126}
1127
1128status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1129 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001130 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001131
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001132 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001133}
1134
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001135status_t Camera3Device::createInputStream(
1136 uint32_t width, uint32_t height, int format, int *id) {
1137 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001138 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001139 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001140 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1141 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001142
1143 status_t res;
1144 bool wasActive = false;
1145
1146 switch (mStatus) {
1147 case STATUS_ERROR:
1148 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1149 return INVALID_OPERATION;
1150 case STATUS_UNINITIALIZED:
1151 ALOGE("%s: Device not initialized", __FUNCTION__);
1152 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001153 case STATUS_UNCONFIGURED:
1154 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001155 // OK
1156 break;
1157 case STATUS_ACTIVE:
1158 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001159 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001160 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001161 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162 return res;
1163 }
1164 wasActive = true;
1165 break;
1166 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001167 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001168 return INVALID_OPERATION;
1169 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001170 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001171
1172 if (mInputStream != 0) {
1173 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1174 return INVALID_OPERATION;
1175 }
1176
1177 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1178 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001179 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180
1181 mInputStream = newStream;
1182
1183 *id = mNextStreamId++;
1184
1185 // Continue captures if active at start
1186 if (wasActive) {
1187 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001188 // Reuse current operating mode for new stream config
1189 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001190 if (res != OK) {
1191 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1192 __FUNCTION__, mNextStreamId, strerror(-res), res);
1193 return res;
1194 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196 }
1197
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001198 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001199 return OK;
1200}
1201
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001202status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001203 uint32_t width, uint32_t height, int format,
1204 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001205 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001206 ATRACE_CALL();
1207
1208 if (consumer == nullptr) {
1209 ALOGE("%s: consumer must not be null", __FUNCTION__);
1210 return BAD_VALUE;
1211 }
1212
1213 std::vector<sp<Surface>> consumers;
1214 consumers.push_back(consumer);
1215
1216 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001217 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218}
1219
1220status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1221 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1222 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001223 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001224 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001227 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001228 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1229 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001230
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 status_t res;
1232 bool wasActive = false;
1233
1234 switch (mStatus) {
1235 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001236 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 return INVALID_OPERATION;
1238 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001239 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001241 case STATUS_UNCONFIGURED:
1242 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 // OK
1244 break;
1245 case STATUS_ACTIVE:
1246 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001247 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return res;
1251 }
1252 wasActive = true;
1253 break;
1254 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001255 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 return INVALID_OPERATION;
1257 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259
1260 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001261
Shuzhen Wang0129d522016-10-30 22:43:41 -07001262 if (consumers.size() == 0 && !hasDeferredConsumer) {
1263 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1264 return BAD_VALUE;
1265 }
Zhijun He5d677d12016-05-29 16:52:39 -07001266
Shuzhen Wang0129d522016-10-30 22:43:41 -07001267 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001268 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1269 return BAD_VALUE;
1270 }
1271
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001273 ssize_t blobBufferSize;
1274 if (dataSpace != HAL_DATASPACE_DEPTH) {
1275 blobBufferSize = getJpegBufferSize(width, height);
1276 if (blobBufferSize <= 0) {
1277 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1278 return BAD_VALUE;
1279 }
1280 } else {
1281 blobBufferSize = getPointCloudBufferSize();
1282 if (blobBufferSize <= 0) {
1283 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1284 return BAD_VALUE;
1285 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001286 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001287 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001288 width, height, blobBufferSize, format, dataSpace, rotation,
1289 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001290 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1291 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1292 if (rawOpaqueBufferSize <= 0) {
1293 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1294 return BAD_VALUE;
1295 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001296 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001297 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1298 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001299 } else if (isShared) {
1300 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1301 width, height, format, consumerUsage, dataSpace, rotation,
1302 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001303 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001304 newStream = new Camera3OutputStream(mNextStreamId,
1305 width, height, format, consumerUsage, dataSpace, rotation,
1306 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001307 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001308 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001309 width, height, format, dataSpace, rotation,
1310 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001311 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001313
Emilian Peev08dd2452017-04-06 16:55:14 +01001314 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001315
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001316 res = mOutputStreams.add(mNextStreamId, newStream);
1317 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001318 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001319 return res;
1320 }
1321
1322 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001323 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001324
1325 // Continue captures if active at start
1326 if (wasActive) {
1327 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001328 // Reuse current operating mode for new stream config
1329 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001330 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001331 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1332 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333 return res;
1334 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001335 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001336 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001337 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001339}
1340
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001342 uint32_t *width, uint32_t *height,
1343 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001345 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001346 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001347
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 switch (mStatus) {
1349 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001350 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 return INVALID_OPERATION;
1352 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001353 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001355 case STATUS_UNCONFIGURED:
1356 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 case STATUS_ACTIVE:
1358 // OK
1359 break;
1360 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001361 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 return INVALID_OPERATION;
1363 }
1364
1365 ssize_t idx = mOutputStreams.indexOfKey(id);
1366 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001367 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return idx;
1369 }
1370
1371 if (width) *width = mOutputStreams[idx]->getWidth();
1372 if (height) *height = mOutputStreams[idx]->getHeight();
1373 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001374 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001376}
1377
1378status_t Camera3Device::setStreamTransform(int id,
1379 int transform) {
1380 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001381 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 switch (mStatus) {
1385 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001386 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 return INVALID_OPERATION;
1388 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001389 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001391 case STATUS_UNCONFIGURED:
1392 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 case STATUS_ACTIVE:
1394 // OK
1395 break;
1396 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001397 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 return INVALID_OPERATION;
1399 }
1400
1401 ssize_t idx = mOutputStreams.indexOfKey(id);
1402 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001403 CLOGE("Stream %d does not exist",
1404 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 return BAD_VALUE;
1406 }
1407
1408 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001409}
1410
1411status_t Camera3Device::deleteStream(int id) {
1412 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001413 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 Mutex::Autolock l(mLock);
1415 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001416
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001417 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001418
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 // CameraDevice semantics require device to already be idle before
1420 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001422 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001423 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 }
1425
Igor Murashkin2fba5842013-04-22 14:03:54 -07001426 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001427 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 if (mInputStream != NULL && id == mInputStream->getId()) {
1429 deletedStream = mInputStream;
1430 mInputStream.clear();
1431 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001432 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001433 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 return BAD_VALUE;
1435 }
Zhijun He5f446352014-01-22 09:49:33 -08001436 }
1437
1438 // Delete output stream or the output part of a bi-directional stream.
1439 if (outputStreamIdx != NAME_NOT_FOUND) {
1440 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 mOutputStreams.removeItem(id);
1442 }
1443
1444 // Free up the stream endpoint so that it can be used by some other stream
1445 res = deletedStream->disconnect();
1446 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001447 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 // fall through since we want to still list the stream as deleted.
1449 }
1450 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001451 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452
1453 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454}
1455
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001456status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001457 ATRACE_CALL();
1458 ALOGV("%s: E", __FUNCTION__);
1459
1460 Mutex::Autolock il(mInterfaceLock);
1461 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001462
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001463 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001464}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001465
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001466status_t Camera3Device::getInputBufferProducer(
1467 sp<IGraphicBufferProducer> *producer) {
1468 Mutex::Autolock il(mInterfaceLock);
1469 Mutex::Autolock l(mLock);
1470
1471 if (producer == NULL) {
1472 return BAD_VALUE;
1473 } else if (mInputStream == NULL) {
1474 return INVALID_OPERATION;
1475 }
1476
1477 return mInputStream->getInputBufferProducer(producer);
1478}
1479
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001480status_t Camera3Device::createDefaultRequest(int templateId,
1481 CameraMetadata *request) {
1482 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001483 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001484
1485 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1486 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1487 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1488 return BAD_VALUE;
1489 }
1490
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001491 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 Mutex::Autolock l(mLock);
1493
1494 switch (mStatus) {
1495 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001496 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 return INVALID_OPERATION;
1498 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001499 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 case STATUS_UNCONFIGURED:
1502 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 case STATUS_ACTIVE:
1504 // OK
1505 break;
1506 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001507 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 return INVALID_OPERATION;
1509 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001510
Zhijun Hea1530f12014-09-14 12:44:20 -07001511 if (!mRequestTemplateCache[templateId].isEmpty()) {
1512 *request = mRequestTemplateCache[templateId];
1513 return OK;
1514 }
1515
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001516 camera_metadata_t *rawRequest;
1517 status_t res = mInterface->constructDefaultRequestSettings(
1518 (camera3_request_template_t) templateId, &rawRequest);
1519 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001520 ALOGI("%s: template %d is not supported on this camera device",
1521 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001522 return res;
1523 } else if (res != OK) {
1524 CLOGE("Unable to construct request template %d: %s (%d)",
1525 templateId, strerror(-res), res);
1526 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001528
Emilian Peev71c73a22017-03-21 16:35:51 +00001529 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001530 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001531
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001532 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533 return OK;
1534}
1535
1536status_t Camera3Device::waitUntilDrained() {
1537 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001538 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540
Zhijun He69a37482014-03-23 18:44:49 -07001541 return waitUntilDrainedLocked();
1542}
1543
1544status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 switch (mStatus) {
1546 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 ALOGV("%s: Already idle", __FUNCTION__);
1549 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 case STATUS_CONFIGURED:
1551 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 case STATUS_ERROR:
1553 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001554 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 break;
1556 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001557 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return INVALID_OPERATION;
1559 }
1560
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001561 nsecs_t maxExpectedDuration = getExpectedInFlightDurationLocked();
1562
1563 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1564 maxExpectedDuration);
1565 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001566 if (res != OK) {
1567 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1568 res);
1569 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 return res;
1571}
1572
Ruben Brunk183f0562015-08-12 12:55:02 -07001573
1574void Camera3Device::internalUpdateStatusLocked(Status status) {
1575 mStatus = status;
1576 mRecentStatusUpdates.add(mStatus);
1577 mStatusChanged.broadcast();
1578}
1579
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001580// Pause to reconfigure
1581status_t Camera3Device::internalPauseAndWaitLocked() {
1582 mRequestThread->setPaused(true);
1583 mPauseStateNotify = true;
1584
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001585 nsecs_t maxExpectedDuration = getExpectedInFlightDurationLocked();
1586 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1587 maxExpectedDuration);
1588 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 if (res != OK) {
1590 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001591 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 }
1593
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594 return res;
1595}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597// Resume after internalPauseAndWaitLocked
1598status_t Camera3Device::internalResumeLocked() {
1599 status_t res;
1600
1601 mRequestThread->setPaused(false);
1602
1603 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1604 if (res != OK) {
1605 SET_ERR_L("Can't transition to active in %f seconds!",
1606 kActiveTimeout/1e9);
1607 }
1608 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610}
1611
Ruben Brunk183f0562015-08-12 12:55:02 -07001612status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001614
1615 size_t startIndex = 0;
1616 if (mStatusWaiters == 0) {
1617 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1618 // this status list
1619 mRecentStatusUpdates.clear();
1620 } else {
1621 // If other threads are waiting on updates to this status list, set the position of the
1622 // first element that this list will check rather than clearing the list.
1623 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001624 }
1625
Ruben Brunk183f0562015-08-12 12:55:02 -07001626 mStatusWaiters++;
1627
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 bool stateSeen = false;
1629 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001630 if (active == (mStatus == STATUS_ACTIVE)) {
1631 // Desired state is current
1632 break;
1633 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001634
1635 res = mStatusChanged.waitRelative(mLock, timeout);
1636 if (res != OK) break;
1637
Ruben Brunk183f0562015-08-12 12:55:02 -07001638 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1639 // transitions.
1640 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1641 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1642 __FUNCTION__);
1643
1644 // Encountered desired state since we began waiting
1645 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001646 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1647 stateSeen = true;
1648 break;
1649 }
1650 }
1651 } while (!stateSeen);
1652
Ruben Brunk183f0562015-08-12 12:55:02 -07001653 mStatusWaiters--;
1654
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001655 return res;
1656}
1657
1658
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001659status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001661 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001663 if (listener != NULL && mListener != NULL) {
1664 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1665 }
1666 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001667 mRequestThread->setNotificationListener(listener);
1668 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001669
1670 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001671}
1672
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001673bool Camera3Device::willNotify3A() {
1674 return false;
1675}
1676
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 status_t res;
1679 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001681 while (mResultQueue.empty()) {
1682 res = mResultSignal.waitRelative(mOutputLock, timeout);
1683 if (res == TIMED_OUT) {
1684 return res;
1685 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001686 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1687 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001688 return res;
1689 }
1690 }
1691 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692}
1693
Jianing Weicb0652e2014-03-12 18:29:36 -07001694status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001695 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001696 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001698 if (mResultQueue.empty()) {
1699 return NOT_ENOUGH_DATA;
1700 }
1701
Jianing Weicb0652e2014-03-12 18:29:36 -07001702 if (frame == NULL) {
1703 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1704 return BAD_VALUE;
1705 }
1706
1707 CaptureResult &result = *(mResultQueue.begin());
1708 frame->mResultExtras = result.mResultExtras;
1709 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001710 mResultQueue.erase(mResultQueue.begin());
1711
1712 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713}
1714
1715status_t Camera3Device::triggerAutofocus(uint32_t id) {
1716 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001717 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001719 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1720 // Mix-in this trigger into the next request and only the next request.
1721 RequestTrigger trigger[] = {
1722 {
1723 ANDROID_CONTROL_AF_TRIGGER,
1724 ANDROID_CONTROL_AF_TRIGGER_START
1725 },
1726 {
1727 ANDROID_CONTROL_AF_TRIGGER_ID,
1728 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001729 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001730 };
1731
1732 return mRequestThread->queueTrigger(trigger,
1733 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734}
1735
1736status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1737 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001738 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001739
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001740 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1741 // Mix-in this trigger into the next request and only the next request.
1742 RequestTrigger trigger[] = {
1743 {
1744 ANDROID_CONTROL_AF_TRIGGER,
1745 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1746 },
1747 {
1748 ANDROID_CONTROL_AF_TRIGGER_ID,
1749 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001750 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001751 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001753 return mRequestThread->queueTrigger(trigger,
1754 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001755}
1756
1757status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1758 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001759 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001760
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001761 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1762 // Mix-in this trigger into the next request and only the next request.
1763 RequestTrigger trigger[] = {
1764 {
1765 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1766 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1767 },
1768 {
1769 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1770 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001771 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001772 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001773
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001774 return mRequestThread->queueTrigger(trigger,
1775 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001776}
1777
Jianing Weicb0652e2014-03-12 18:29:36 -07001778status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001779 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001780 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001781 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001782
Zhijun He7ef20392014-04-21 16:04:17 -07001783 {
1784 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001785 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001786 }
1787
Emilian Peev08dd2452017-04-06 16:55:14 +01001788 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001789}
1790
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001791status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001792 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1793}
1794
1795status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001796 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001797 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001798 Mutex::Autolock il(mInterfaceLock);
1799 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001800
1801 sp<Camera3StreamInterface> stream;
1802 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1803 if (outputStreamIdx == NAME_NOT_FOUND) {
1804 CLOGE("Stream %d does not exist", streamId);
1805 return BAD_VALUE;
1806 }
1807
1808 stream = mOutputStreams.editValueAt(outputStreamIdx);
1809
1810 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001811 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001812 return BAD_VALUE;
1813 }
1814
1815 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001816 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001817 return BAD_VALUE;
1818 }
1819
Ruben Brunkc78ac262015-08-13 17:58:46 -07001820 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001821}
1822
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001823status_t Camera3Device::tearDown(int streamId) {
1824 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001825 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001826 Mutex::Autolock il(mInterfaceLock);
1827 Mutex::Autolock l(mLock);
1828
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001829 sp<Camera3StreamInterface> stream;
1830 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1831 if (outputStreamIdx == NAME_NOT_FOUND) {
1832 CLOGE("Stream %d does not exist", streamId);
1833 return BAD_VALUE;
1834 }
1835
1836 stream = mOutputStreams.editValueAt(outputStreamIdx);
1837
1838 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1839 CLOGE("Stream %d is a target of a in-progress request", streamId);
1840 return BAD_VALUE;
1841 }
1842
1843 return stream->tearDown();
1844}
1845
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001846status_t Camera3Device::addBufferListenerForStream(int streamId,
1847 wp<Camera3StreamBufferListener> listener) {
1848 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001849 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001850 Mutex::Autolock il(mInterfaceLock);
1851 Mutex::Autolock l(mLock);
1852
1853 sp<Camera3StreamInterface> stream;
1854 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1855 if (outputStreamIdx == NAME_NOT_FOUND) {
1856 CLOGE("Stream %d does not exist", streamId);
1857 return BAD_VALUE;
1858 }
1859
1860 stream = mOutputStreams.editValueAt(outputStreamIdx);
1861 stream->addBufferListener(listener);
1862
1863 return OK;
1864}
1865
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001866/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 * Methods called by subclasses
1868 */
1869
1870void Camera3Device::notifyStatus(bool idle) {
1871 {
1872 // Need mLock to safely update state and synchronize to current
1873 // state of methods in flight.
1874 Mutex::Autolock l(mLock);
1875 // We can get various system-idle notices from the status tracker
1876 // while starting up. Only care about them if we've actually sent
1877 // in some requests recently.
1878 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1879 return;
1880 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001881 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001883 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001884
1885 // Skip notifying listener if we're doing some user-transparent
1886 // state changes
1887 if (mPauseStateNotify) return;
1888 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001889
1890 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 {
1892 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001893 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001894 }
1895 if (idle && listener != NULL) {
1896 listener->notifyIdle();
1897 }
1898}
1899
Shuzhen Wang758c2152017-01-10 18:26:18 -08001900status_t Camera3Device::setConsumerSurfaces(int streamId,
1901 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001902 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001903 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1904 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001905 Mutex::Autolock il(mInterfaceLock);
1906 Mutex::Autolock l(mLock);
1907
Shuzhen Wang758c2152017-01-10 18:26:18 -08001908 if (consumers.size() == 0) {
1909 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001910 return BAD_VALUE;
1911 }
1912
1913 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1914 if (idx == NAME_NOT_FOUND) {
1915 CLOGE("Stream %d is unknown", streamId);
1916 return idx;
1917 }
1918 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001919 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001920 if (res != OK) {
1921 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1922 return res;
1923 }
1924
Shuzhen Wang0129d522016-10-30 22:43:41 -07001925 if (stream->isConsumerConfigurationDeferred()) {
1926 if (!stream->isConfiguring()) {
1927 CLOGE("Stream %d was already fully configured.", streamId);
1928 return INVALID_OPERATION;
1929 }
Zhijun He5d677d12016-05-29 16:52:39 -07001930
Shuzhen Wang0129d522016-10-30 22:43:41 -07001931 res = stream->finishConfiguration();
1932 if (res != OK) {
1933 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1934 stream->getId(), strerror(-res), res);
1935 return res;
1936 }
Zhijun He5d677d12016-05-29 16:52:39 -07001937 }
1938
1939 return OK;
1940}
1941
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001942/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001943 * Camera3Device private methods
1944 */
1945
1946sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001947 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001948 ATRACE_CALL();
1949 status_t res;
1950
1951 sp<CaptureRequest> newRequest = new CaptureRequest;
1952 newRequest->mSettings = request;
1953
1954 camera_metadata_entry_t inputStreams =
1955 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1956 if (inputStreams.count > 0) {
1957 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001958 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001959 CLOGE("Request references unknown input stream %d",
1960 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001961 return NULL;
1962 }
1963 // Lazy completion of stream configuration (allocation/registration)
1964 // on first use
1965 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001966 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001967 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001968 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001969 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001970 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001971 return NULL;
1972 }
1973 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001974 // Check if stream is being prepared
1975 if (mInputStream->isPreparing()) {
1976 CLOGE("Request references an input stream that's being prepared!");
1977 return NULL;
1978 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001979
1980 newRequest->mInputStream = mInputStream;
1981 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1982 }
1983
1984 camera_metadata_entry_t streams =
1985 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1986 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001987 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988 return NULL;
1989 }
1990
1991 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001992 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001994 CLOGE("Request references unknown stream %d",
1995 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001996 return NULL;
1997 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001998 sp<Camera3OutputStreamInterface> stream =
1999 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002000
Zhijun He5d677d12016-05-29 16:52:39 -07002001 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002002 auto iter = surfaceMap.find(streams.data.i32[i]);
2003 if (iter != surfaceMap.end()) {
2004 const std::vector<size_t>& surfaces = iter->second;
2005 for (const auto& surface : surfaces) {
2006 if (stream->isConsumerConfigurationDeferred(surface)) {
2007 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2008 "due to deferred consumer", stream->getId(), surface);
2009 return NULL;
2010 }
2011 }
2012 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002013 }
2014
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002015 // Lazy completion of stream configuration (allocation/registration)
2016 // on first use
2017 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002018 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002020 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2021 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022 return NULL;
2023 }
2024 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002025 // Check if stream is being prepared
2026 if (stream->isPreparing()) {
2027 CLOGE("Request references an output stream that's being prepared!");
2028 return NULL;
2029 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002030
2031 newRequest->mOutputStreams.push(stream);
2032 }
2033 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002034 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035
2036 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002037}
2038
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002039bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2040 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2041 Size size = mSupportedOpaqueInputSizes[i];
2042 if (size.width == width && size.height == height) {
2043 return true;
2044 }
2045 }
2046
2047 return false;
2048}
2049
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002050void Camera3Device::cancelStreamsConfigurationLocked() {
2051 int res = OK;
2052 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2053 res = mInputStream->cancelConfiguration();
2054 if (res != OK) {
2055 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2056 mInputStream->getId(), strerror(-res), res);
2057 }
2058 }
2059
2060 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2061 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2062 if (outputStream->isConfiguring()) {
2063 res = outputStream->cancelConfiguration();
2064 if (res != OK) {
2065 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2066 outputStream->getId(), strerror(-res), res);
2067 }
2068 }
2069 }
2070
2071 // Return state to that at start of call, so that future configures
2072 // properly clean things up
2073 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2074 mNeedConfig = true;
2075}
2076
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002077status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078 ATRACE_CALL();
2079 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002080
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002081 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002082 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 return INVALID_OPERATION;
2084 }
2085
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002086 if (operatingMode < 0) {
2087 CLOGE("Invalid operating mode: %d", operatingMode);
2088 return BAD_VALUE;
2089 }
2090
2091 bool isConstrainedHighSpeed =
2092 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2093 operatingMode;
2094
2095 if (mOperatingMode != operatingMode) {
2096 mNeedConfig = true;
2097 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2098 mOperatingMode = operatingMode;
2099 }
2100
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002101 if (!mNeedConfig) {
2102 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2103 return OK;
2104 }
2105
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002106 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2107 // adding a dummy stream instead.
2108 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2109 if (mOutputStreams.size() == 0) {
2110 addDummyStreamLocked();
2111 } else {
2112 tryRemoveDummyStreamLocked();
2113 }
2114
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002116 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117
2118 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002119 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2121
2122 Vector<camera3_stream_t*> streams;
2123 streams.setCapacity(config.num_streams);
2124
2125 if (mInputStream != NULL) {
2126 camera3_stream_t *inputStream;
2127 inputStream = mInputStream->startConfiguration();
2128 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002129 CLOGE("Can't start input stream configuration");
2130 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002131 return INVALID_OPERATION;
2132 }
2133 streams.add(inputStream);
2134 }
2135
2136 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002137
2138 // Don't configure bidi streams twice, nor add them twice to the list
2139 if (mOutputStreams[i].get() ==
2140 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2141
2142 config.num_streams--;
2143 continue;
2144 }
2145
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146 camera3_stream_t *outputStream;
2147 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2148 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002149 CLOGE("Can't start output stream configuration");
2150 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 return INVALID_OPERATION;
2152 }
2153 streams.add(outputStream);
2154 }
2155
2156 config.streams = streams.editArray();
2157
2158 // Do the HAL configuration; will potentially touch stream
2159 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002160
2161 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002163 if (res == BAD_VALUE) {
2164 // HAL rejected this set of streams as unsupported, clean up config
2165 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002166 CLOGE("Set of requested inputs/outputs not supported by HAL");
2167 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002168 return BAD_VALUE;
2169 } else if (res != OK) {
2170 // Some other kind of error from configure_streams - this is not
2171 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002172 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2173 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002174 return res;
2175 }
2176
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002177 // Finish all stream configuration immediately.
2178 // TODO: Try to relax this later back to lazy completion, which should be
2179 // faster
2180
Igor Murashkin073f8572013-05-02 14:59:28 -07002181 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002182 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002183 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002184 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002185 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002186 cancelStreamsConfigurationLocked();
2187 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002188 }
2189 }
2190
2191 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002192 sp<Camera3OutputStreamInterface> outputStream =
2193 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002194 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002195 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002196 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002197 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002198 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002199 cancelStreamsConfigurationLocked();
2200 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002201 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002202 }
2203 }
2204
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 // Request thread needs to know to avoid using repeat-last-settings protocol
2206 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002207 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002208
Zhijun He90f7c372016-08-16 16:19:43 -07002209 char value[PROPERTY_VALUE_MAX];
2210 property_get("camera.fifo.disable", value, "0");
2211 int32_t disableFifo = atoi(value);
2212 if (disableFifo != 1) {
2213 // Boost priority of request thread to SCHED_FIFO.
2214 pid_t requestThreadTid = mRequestThread->getTid();
2215 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002216 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002217 if (res != OK) {
2218 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2219 strerror(-res), res);
2220 } else {
2221 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2222 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002223 }
2224
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002226
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002227 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228
Ruben Brunk183f0562015-08-12 12:55:02 -07002229 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2230 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002231
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002232 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233
Zhijun He0a210512014-07-24 13:45:15 -07002234 // tear down the deleted streams after configure streams.
2235 mDeletedStreams.clear();
2236
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002237 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002238}
2239
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002240status_t Camera3Device::addDummyStreamLocked() {
2241 ATRACE_CALL();
2242 status_t res;
2243
2244 if (mDummyStreamId != NO_STREAM) {
2245 // Should never be adding a second dummy stream when one is already
2246 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002247 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2248 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002249 return INVALID_OPERATION;
2250 }
2251
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002252 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002253
2254 sp<Camera3OutputStreamInterface> dummyStream =
2255 new Camera3DummyStream(mNextStreamId);
2256
2257 res = mOutputStreams.add(mNextStreamId, dummyStream);
2258 if (res < 0) {
2259 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2260 return res;
2261 }
2262
2263 mDummyStreamId = mNextStreamId;
2264 mNextStreamId++;
2265
2266 return OK;
2267}
2268
2269status_t Camera3Device::tryRemoveDummyStreamLocked() {
2270 ATRACE_CALL();
2271 status_t res;
2272
2273 if (mDummyStreamId == NO_STREAM) return OK;
2274 if (mOutputStreams.size() == 1) return OK;
2275
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002276 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002277
2278 // Ok, have a dummy stream and there's at least one other output stream,
2279 // so remove the dummy
2280
2281 sp<Camera3StreamInterface> deletedStream;
2282 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2283 if (outputStreamIdx == NAME_NOT_FOUND) {
2284 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2285 return INVALID_OPERATION;
2286 }
2287
2288 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2289 mOutputStreams.removeItemsAt(outputStreamIdx);
2290
2291 // Free up the stream endpoint so that it can be used by some other stream
2292 res = deletedStream->disconnect();
2293 if (res != OK) {
2294 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2295 // fall through since we want to still list the stream as deleted.
2296 }
2297 mDeletedStreams.add(deletedStream);
2298 mDummyStreamId = NO_STREAM;
2299
2300 return res;
2301}
2302
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002303void Camera3Device::setErrorState(const char *fmt, ...) {
2304 Mutex::Autolock l(mLock);
2305 va_list args;
2306 va_start(args, fmt);
2307
2308 setErrorStateLockedV(fmt, args);
2309
2310 va_end(args);
2311}
2312
2313void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2314 Mutex::Autolock l(mLock);
2315 setErrorStateLockedV(fmt, args);
2316}
2317
2318void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2319 va_list args;
2320 va_start(args, fmt);
2321
2322 setErrorStateLockedV(fmt, args);
2323
2324 va_end(args);
2325}
2326
2327void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002328 // Print out all error messages to log
2329 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002330 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002331
2332 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002333 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002334
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002335 mErrorCause = errorCause;
2336
2337 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002338 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002339
2340 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002341 sp<NotificationListener> listener = mListener.promote();
2342 if (listener != NULL) {
2343 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002344 CaptureResultExtras());
2345 }
2346
2347 // Save stack trace. View by dumping it later.
2348 CameraTraces::saveTrace();
2349 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002350}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351
2352/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002353 * In-flight request management
2354 */
2355
Jianing Weicb0652e2014-03-12 18:29:36 -07002356status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002357 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002358 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002359 ATRACE_CALL();
2360 Mutex::Autolock l(mInFlightLock);
2361
2362 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002363 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002364 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002365 if (res < 0) return res;
2366
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002367 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002368 // hold mLock to prevent race with disconnect
2369 Mutex::Autolock l(mLock);
2370 if (mStatusTracker != nullptr) {
2371 mStatusTracker->markComponentActive(mInFlightStatusId);
2372 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002373 }
2374
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002375 Mutex::Autolock ml(mLock);
2376 mExpectedInflightDuration += maxExpectedDuration;
2377
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002378 return OK;
2379}
2380
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002381void Camera3Device::returnOutputBuffers(
2382 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2383 nsecs_t timestamp) {
2384 for (size_t i = 0; i < numBuffers; i++)
2385 {
2386 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2387 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2388 // Note: stream may be deallocated at this point, if this buffer was
2389 // the last reference to it.
2390 if (res != OK) {
2391 ALOGE("Can't return buffer to its stream: %s (%d)",
2392 strerror(-res), res);
2393 }
2394 }
2395}
2396
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002397void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002398 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002399 mInFlightMap.removeItemsAt(idx, 1);
2400
2401 // Indicate idle inFlightMap to the status tracker
2402 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002403 // hold mLock to prevent race with disconnect
2404 Mutex::Autolock l(mLock);
2405 if (mStatusTracker != nullptr) {
2406 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2407 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002408 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002409 Mutex::Autolock l(mLock);
2410 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002411}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002412
2413void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2414
2415 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2416 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2417
2418 nsecs_t sensorTimestamp = request.sensorTimestamp;
2419 nsecs_t shutterTimestamp = request.shutterTimestamp;
2420
Emilian Peevc6747862017-06-12 15:57:26 +01002421 bool skipResultMetadata = false;
2422 if (request.requestStatus != OK) {
2423 switch (request.requestStatus) {
2424 case CAMERA3_MSG_ERROR_DEVICE:
2425 case CAMERA3_MSG_ERROR_REQUEST:
2426 case CAMERA3_MSG_ERROR_RESULT:
2427 skipResultMetadata = true;
2428 break;
2429 case CAMERA3_MSG_ERROR_BUFFER:
2430 //Result metadata should return in this case.
2431 skipResultMetadata = false;
2432 break;
2433 default:
2434 SET_ERR("Unknown error message: %d", request.requestStatus);
2435 skipResultMetadata = false;
2436 break;
2437 }
2438 }
2439
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002440 // Check if it's okay to remove the request from InFlightMap:
2441 // In the case of a successful request:
2442 // all input and output buffers, all result metadata, shutter callback
2443 // arrived.
2444 // In the case of a unsuccessful request:
2445 // all input and output buffers arrived.
2446 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002447 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002448 (request.haveResultMetadata && shutterTimestamp != 0))) {
2449 ATRACE_ASYNC_END("frame capture", frameNumber);
2450
Shuzhen Wang403044a2017-02-26 23:29:04 -08002451 // Sanity check - if sensor timestamp matches shutter timestamp in the
2452 // case of request having callback.
2453 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002454 sensorTimestamp != shutterTimestamp) {
2455 SET_ERR("sensor timestamp (%" PRId64
2456 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2457 sensorTimestamp, frameNumber, shutterTimestamp);
2458 }
2459
2460 // for an unsuccessful request, it may have pending output buffers to
2461 // return.
2462 assert(request.requestStatus != OK ||
2463 request.pendingOutputBuffers.size() == 0);
2464 returnOutputBuffers(request.pendingOutputBuffers.array(),
2465 request.pendingOutputBuffers.size(), 0);
2466
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002467 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002468 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2469 }
2470
2471 // Sanity check - if we have too many in-flight frames, something has
2472 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002473 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002474 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002475 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2476 kInFlightWarnLimitHighSpeed) {
2477 CLOGE("In-flight list too large for high speed configuration: %zu",
2478 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002479 }
2480}
2481
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002482void Camera3Device::flushInflightRequests() {
2483 { // First return buffers cached in mInFlightMap
2484 Mutex::Autolock l(mInFlightLock);
2485 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2486 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2487 returnOutputBuffers(request.pendingOutputBuffers.array(),
2488 request.pendingOutputBuffers.size(), 0);
2489 }
2490 mInFlightMap.clear();
2491 }
2492
2493 // Then return all inflight buffers not returned by HAL
2494 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2495 mInterface->getInflightBufferKeys(&inflightKeys);
2496
2497 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2498 for (auto& pair : inflightKeys) {
2499 int32_t frameNumber = pair.first;
2500 int32_t streamId = pair.second;
2501 buffer_handle_t* buffer;
2502 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2503 if (res != OK) {
2504 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2505 __FUNCTION__, frameNumber, streamId);
2506 continue;
2507 }
2508
2509 camera3_stream_buffer_t streamBuffer;
2510 streamBuffer.buffer = buffer;
2511 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2512 streamBuffer.acquire_fence = -1;
2513 streamBuffer.release_fence = -1;
2514 if (streamId == inputStreamId) {
2515 streamBuffer.stream = mInputStream->asHalStream();
2516 res = mInputStream->returnInputBuffer(streamBuffer);
2517 if (res != OK) {
2518 ALOGE("%s: Can't return input buffer for frame %d to"
2519 " its stream:%s (%d)", __FUNCTION__,
2520 frameNumber, strerror(-res), res);
2521 }
2522 } else {
2523 streamBuffer.stream = mOutputStreams.valueFor(streamId)->asHalStream();
2524 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2525 }
2526 }
2527}
2528
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002529void Camera3Device::insertResultLocked(CaptureResult *result,
2530 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002531 if (result == nullptr) return;
2532
Emilian Peev71c73a22017-03-21 16:35:51 +00002533 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2534 result->mMetadata.getAndLock());
2535 set_camera_metadata_vendor_id(meta, mVendorTagId);
2536 result->mMetadata.unlock(meta);
2537
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002538 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2539 (int32_t*)&frameNumber, 1) != OK) {
2540 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2541 return;
2542 }
2543
2544 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2545 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2546 return;
2547 }
2548
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002549 // Valid result, insert into queue
2550 List<CaptureResult>::iterator queuedResult =
2551 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2552 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2553 ", burstId = %" PRId32, __FUNCTION__,
2554 queuedResult->mResultExtras.requestId,
2555 queuedResult->mResultExtras.frameNumber,
2556 queuedResult->mResultExtras.burstId);
2557
2558 mResultSignal.signal();
2559}
2560
2561
2562void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002563 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002564 Mutex::Autolock l(mOutputLock);
2565
2566 CaptureResult captureResult;
2567 captureResult.mResultExtras = resultExtras;
2568 captureResult.mMetadata = partialResult;
2569
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002570 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002571}
2572
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002573
2574void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2575 CaptureResultExtras &resultExtras,
2576 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002577 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002578 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002579 if (pendingMetadata.isEmpty())
2580 return;
2581
2582 Mutex::Autolock l(mOutputLock);
2583
2584 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002585 if (reprocess) {
2586 if (frameNumber < mNextReprocessResultFrameNumber) {
2587 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002588 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002589 frameNumber, mNextReprocessResultFrameNumber);
2590 return;
2591 }
2592 mNextReprocessResultFrameNumber = frameNumber + 1;
2593 } else {
2594 if (frameNumber < mNextResultFrameNumber) {
2595 SET_ERR("Out-of-order capture result metadata submitted! "
2596 "(got frame number %d, expecting %d)",
2597 frameNumber, mNextResultFrameNumber);
2598 return;
2599 }
2600 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002601 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002602
2603 CaptureResult captureResult;
2604 captureResult.mResultExtras = resultExtras;
2605 captureResult.mMetadata = pendingMetadata;
2606
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002607 // Append any previous partials to form a complete result
2608 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2609 captureResult.mMetadata.append(collectedPartialResult);
2610 }
2611
2612 captureResult.mMetadata.sort();
2613
2614 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002615 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2616 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002617 SET_ERR("No timestamp provided by HAL for frame %d!",
2618 frameNumber);
2619 return;
2620 }
2621
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002622 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2623 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2624
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002625 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002626}
2627
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002628/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629 * Camera HAL device callback methods
2630 */
2631
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002632void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002633 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002634
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002635 status_t res;
2636
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002637 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002638 if (result->result == NULL && result->num_output_buffers == 0 &&
2639 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002640 SET_ERR("No result data provided by HAL for frame %d",
2641 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002642 return;
2643 }
Zhijun He204e3292014-07-14 17:09:23 -07002644
Zhijun He204e3292014-07-14 17:09:23 -07002645 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002646 result->result != NULL &&
2647 result->partial_result != 1) {
2648 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2649 " if partial result is not supported",
2650 frameNumber, result->partial_result);
2651 return;
2652 }
2653
2654 bool isPartialResult = false;
2655 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002656 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002657 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002658
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002659 // Get shutter timestamp and resultExtras from list of in-flight requests,
2660 // where it was added by the shutter notification for this frame. If the
2661 // shutter timestamp isn't received yet, append the output buffers to the
2662 // in-flight request and they will be returned when the shutter timestamp
2663 // arrives. Update the in-flight status and remove the in-flight entry if
2664 // all result data and shutter timestamp have been received.
2665 nsecs_t shutterTimestamp = 0;
2666
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002667 {
2668 Mutex::Autolock l(mInFlightLock);
2669 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2670 if (idx == NAME_NOT_FOUND) {
2671 SET_ERR("Unknown frame number for capture result: %d",
2672 frameNumber);
2673 return;
2674 }
2675 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002676 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2677 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002678 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002679 __FUNCTION__, request.resultExtras.requestId,
2680 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002681 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002682 // Always update the partial count to the latest one if it's not 0
2683 // (buffers only). When framework aggregates adjacent partial results
2684 // into one, the latest partial count will be used.
2685 if (result->partial_result != 0)
2686 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002687
2688 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002689 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002690 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2691 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2692 " the range of [1, %d] when metadata is included in the result",
2693 frameNumber, result->partial_result, mNumPartialResults);
2694 return;
2695 }
2696 isPartialResult = (result->partial_result < mNumPartialResults);
2697 if (isPartialResult) {
2698 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002699 }
2700
Shuzhen Wang4a472662017-02-26 23:29:04 -08002701 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002702 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002703 sendPartialCaptureResult(result->result, request.resultExtras,
2704 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002705 }
2706 }
2707
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002708 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002709 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002710
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002711 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002712 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002713 if (request.haveResultMetadata) {
2714 SET_ERR("Called multiple times with metadata for frame %d",
2715 frameNumber);
2716 return;
2717 }
Zhijun He204e3292014-07-14 17:09:23 -07002718 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002719 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002720 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002721 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002722 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723 request.haveResultMetadata = true;
2724 }
2725
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002726 uint32_t numBuffersReturned = result->num_output_buffers;
2727 if (result->input_buffer != NULL) {
2728 if (hasInputBufferInRequest) {
2729 numBuffersReturned += 1;
2730 } else {
2731 ALOGW("%s: Input buffer should be NULL if there is no input"
2732 " buffer sent in the request",
2733 __FUNCTION__);
2734 }
2735 }
2736 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002737 if (request.numBuffersLeft < 0) {
2738 SET_ERR("Too many buffers returned for frame %d",
2739 frameNumber);
2740 return;
2741 }
2742
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002743 camera_metadata_ro_entry_t entry;
2744 res = find_camera_metadata_ro_entry(result->result,
2745 ANDROID_SENSOR_TIMESTAMP, &entry);
2746 if (res == OK && entry.count == 1) {
2747 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002748 }
2749
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002750 // If shutter event isn't received yet, append the output buffers to
2751 // the in-flight request. Otherwise, return the output buffers to
2752 // streams.
2753 if (shutterTimestamp == 0) {
2754 request.pendingOutputBuffers.appendArray(result->output_buffers,
2755 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002756 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757 returnOutputBuffers(result->output_buffers,
2758 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002759 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002760
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002761 if (result->result != NULL && !isPartialResult) {
2762 if (shutterTimestamp == 0) {
2763 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002764 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002765 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002766 CameraMetadata metadata;
2767 metadata = result->result;
2768 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002769 collectedPartialResult, frameNumber,
2770 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002772 }
2773
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002774 removeInFlightRequestIfReadyLocked(idx);
2775 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002776
Zhijun Hef0d962a2014-06-30 10:24:11 -07002777 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002778 if (hasInputBufferInRequest) {
2779 Camera3Stream *stream =
2780 Camera3Stream::cast(result->input_buffer->stream);
2781 res = stream->returnInputBuffer(*(result->input_buffer));
2782 // Note: stream may be deallocated at this point, if this buffer was the
2783 // last reference to it.
2784 if (res != OK) {
2785 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2786 " its stream:%s (%d)", __FUNCTION__,
2787 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002788 }
2789 } else {
2790 ALOGW("%s: Input buffer should be NULL if there is no input"
2791 " buffer sent in the request, skipping input buffer return.",
2792 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002793 }
2794 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002795}
2796
2797void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002798 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002799 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002800 {
2801 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002802 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002803 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002804
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002805 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002806 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002807 return;
2808 }
2809
2810 switch (msg->type) {
2811 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002812 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002813 break;
2814 }
2815 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002816 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002817 break;
2818 }
2819 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002820 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002821 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002822 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002823}
2824
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002825void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002826 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002827
2828 // Map camera HAL error codes to ICameraDeviceCallback error codes
2829 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002830 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002831 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002832 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002833 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002834 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002836 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002837 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002838 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002839 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002840 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002841 };
2842
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002843 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002844 ((msg.error_code >= 0) &&
2845 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2846 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848
2849 int streamId = 0;
2850 if (msg.error_stream != NULL) {
2851 Camera3Stream *stream =
2852 Camera3Stream::cast(msg.error_stream);
2853 streamId = stream->getId();
2854 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002855 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2856 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857 streamId, msg.error_code);
2858
2859 CaptureResultExtras resultExtras;
2860 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002861 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002862 // SET_ERR calls notifyError
2863 SET_ERR("Camera HAL reported serious device error");
2864 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002865 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2866 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2867 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868 {
2869 Mutex::Autolock l(mInFlightLock);
2870 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2871 if (idx >= 0) {
2872 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2873 r.requestStatus = msg.error_code;
2874 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002875 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2876 errorCode) {
2877 // In case of missing result check whether the buffers
2878 // returned. If they returned, then remove inflight
2879 // request.
2880 removeInFlightRequestIfReadyLocked(idx);
2881 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002882 } else {
2883 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002884 ALOGE("Camera %s: %s: cannot find in-flight request on "
2885 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002886 resultExtras.frameNumber);
2887 }
2888 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002889 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890 if (listener != NULL) {
2891 listener->notifyError(errorCode, resultExtras);
2892 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002893 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002894 }
2895 break;
2896 default:
2897 // SET_ERR calls notifyError
2898 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2899 break;
2900 }
2901}
2902
2903void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002904 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002905 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002906
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002907 // Set timestamp for the request in the in-flight tracking
2908 // and get the request ID to send upstream
2909 {
2910 Mutex::Autolock l(mInFlightLock);
2911 idx = mInFlightMap.indexOfKey(msg.frame_number);
2912 if (idx >= 0) {
2913 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002914
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002915 // Verify ordering of shutter notifications
2916 {
2917 Mutex::Autolock l(mOutputLock);
2918 // TODO: need to track errors for tighter bounds on expected frame number.
2919 if (r.hasInputBuffer) {
2920 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2921 SET_ERR("Shutter notification out-of-order. Expected "
2922 "notification for frame %d, got frame %d",
2923 mNextReprocessShutterFrameNumber, msg.frame_number);
2924 return;
2925 }
2926 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2927 } else {
2928 if (msg.frame_number < mNextShutterFrameNumber) {
2929 SET_ERR("Shutter notification out-of-order. Expected "
2930 "notification for frame %d, got frame %d",
2931 mNextShutterFrameNumber, msg.frame_number);
2932 return;
2933 }
2934 mNextShutterFrameNumber = msg.frame_number + 1;
2935 }
2936 }
2937
Shuzhen Wang4a472662017-02-26 23:29:04 -08002938 r.shutterTimestamp = msg.timestamp;
2939 if (r.hasCallback) {
2940 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002941 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002942 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002943 // Call listener, if any
2944 if (listener != NULL) {
2945 listener->notifyShutter(r.resultExtras, msg.timestamp);
2946 }
2947 // send pending result and buffers
2948 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2949 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002950 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002951 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002952 returnOutputBuffers(r.pendingOutputBuffers.array(),
2953 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2954 r.pendingOutputBuffers.clear();
2955
2956 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002957 }
2958 }
2959 if (idx < 0) {
2960 SET_ERR("Shutter notification for non-existent frame number %d",
2961 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962 }
2963}
2964
2965
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002966CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002967 ALOGV("%s", __FUNCTION__);
2968
Igor Murashkin1e479c02013-09-06 16:55:14 -07002969 CameraMetadata retVal;
2970
2971 if (mRequestThread != NULL) {
2972 retVal = mRequestThread->getLatestRequest();
2973 }
2974
Igor Murashkin1e479c02013-09-06 16:55:14 -07002975 return retVal;
2976}
2977
Jianing Weicb0652e2014-03-12 18:29:36 -07002978
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002979void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2980 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2981 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2982}
2983
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002984/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002985 * HalInterface inner class methods
2986 */
2987
Yifan Hongf79b5542017-04-11 14:44:25 -07002988Camera3Device::HalInterface::HalInterface(
2989 sp<ICameraDeviceSession> &session,
2990 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002991 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002992 mHidlSession(session),
2993 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002994
2995Camera3Device::HalInterface::HalInterface() :
2996 mHal3Device(nullptr) {}
2997
2998Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002999 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07003000 mHidlSession(other.mHidlSession),
3001 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003002
3003bool Camera3Device::HalInterface::valid() {
3004 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3005}
3006
3007void Camera3Device::HalInterface::clear() {
3008 mHal3Device = nullptr;
3009 mHidlSession.clear();
3010}
3011
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003012bool Camera3Device::HalInterface::supportBatchRequest() {
3013 return mHidlSession != nullptr;
3014}
3015
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003016status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3017 camera3_request_template_t templateId,
3018 /*out*/ camera_metadata_t **requestTemplate) {
3019 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3020 if (!valid()) return INVALID_OPERATION;
3021 status_t res = OK;
3022
3023 if (mHal3Device != nullptr) {
3024 const camera_metadata *r;
3025 r = mHal3Device->ops->construct_default_request_settings(
3026 mHal3Device, templateId);
3027 if (r == nullptr) return BAD_VALUE;
3028 *requestTemplate = clone_camera_metadata(r);
3029 if (requestTemplate == nullptr) {
3030 ALOGE("%s: Unable to clone camera metadata received from HAL",
3031 __FUNCTION__);
3032 return INVALID_OPERATION;
3033 }
3034 } else {
3035 common::V1_0::Status status;
3036 RequestTemplate id;
3037 switch (templateId) {
3038 case CAMERA3_TEMPLATE_PREVIEW:
3039 id = RequestTemplate::PREVIEW;
3040 break;
3041 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3042 id = RequestTemplate::STILL_CAPTURE;
3043 break;
3044 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3045 id = RequestTemplate::VIDEO_RECORD;
3046 break;
3047 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3048 id = RequestTemplate::VIDEO_SNAPSHOT;
3049 break;
3050 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3051 id = RequestTemplate::ZERO_SHUTTER_LAG;
3052 break;
3053 case CAMERA3_TEMPLATE_MANUAL:
3054 id = RequestTemplate::MANUAL;
3055 break;
3056 default:
3057 // Unknown template ID
3058 return BAD_VALUE;
3059 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003060 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003061 [&status, &requestTemplate]
3062 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3063 status = s;
3064 if (status == common::V1_0::Status::OK) {
3065 const camera_metadata *r =
3066 reinterpret_cast<const camera_metadata_t*>(request.data());
3067 size_t expectedSize = request.size();
3068 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003069 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003070 *requestTemplate = clone_camera_metadata(r);
3071 if (*requestTemplate == nullptr) {
3072 ALOGE("%s: Unable to clone camera metadata received from HAL",
3073 __FUNCTION__);
3074 status = common::V1_0::Status::INTERNAL_ERROR;
3075 }
3076 } else {
3077 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3078 status = common::V1_0::Status::INTERNAL_ERROR;
3079 }
3080 }
3081 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003082 if (!err.isOk()) {
3083 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3084 res = DEAD_OBJECT;
3085 } else {
3086 res = CameraProviderManager::mapToStatusT(status);
3087 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088 }
3089 return res;
3090}
3091
3092status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3093 ATRACE_NAME("CameraHal::configureStreams");
3094 if (!valid()) return INVALID_OPERATION;
3095 status_t res = OK;
3096
3097 if (mHal3Device != nullptr) {
3098 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3099 } else {
3100 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003101 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003102 StreamConfiguration requestedConfiguration;
3103 requestedConfiguration.streams.resize(config->num_streams);
3104 for (size_t i = 0; i < config->num_streams; i++) {
3105 Stream &dst = requestedConfiguration.streams[i];
3106 camera3_stream_t *src = config->streams[i];
3107
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003108 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3109 cam3stream->setBufferFreedListener(this);
3110 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003111 StreamType streamType;
3112 switch (src->stream_type) {
3113 case CAMERA3_STREAM_OUTPUT:
3114 streamType = StreamType::OUTPUT;
3115 break;
3116 case CAMERA3_STREAM_INPUT:
3117 streamType = StreamType::INPUT;
3118 break;
3119 default:
3120 ALOGE("%s: Stream %d: Unsupported stream type %d",
3121 __FUNCTION__, streamId, config->streams[i]->stream_type);
3122 return BAD_VALUE;
3123 }
3124 dst.id = streamId;
3125 dst.streamType = streamType;
3126 dst.width = src->width;
3127 dst.height = src->height;
3128 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003129 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130 dst.dataSpace = mapToHidlDataspace(src->data_space);
3131 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003132
3133 activeStreams.insert(streamId);
3134 // Create Buffer ID map if necessary
3135 if (mBufferIdMaps.count(streamId) == 0) {
3136 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3137 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003138 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003139 // remove BufferIdMap for deleted streams
3140 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3141 int streamId = it->first;
3142 bool active = activeStreams.count(streamId) > 0;
3143 if (!active) {
3144 it = mBufferIdMaps.erase(it);
3145 } else {
3146 ++it;
3147 }
3148 }
3149
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003150 res = mapToStreamConfigurationMode(
3151 (camera3_stream_configuration_mode_t) config->operation_mode,
3152 /*out*/ &requestedConfiguration.operationMode);
3153 if (res != OK) {
3154 return res;
3155 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003156
3157 // Invoke configureStreams
3158
3159 HalStreamConfiguration finalConfiguration;
3160 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003161 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003162 [&status, &finalConfiguration]
3163 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3164 finalConfiguration = halConfiguration;
3165 status = s;
3166 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003167 if (!err.isOk()) {
3168 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3169 return DEAD_OBJECT;
3170 }
3171
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172 if (status != common::V1_0::Status::OK ) {
3173 return CameraProviderManager::mapToStatusT(status);
3174 }
3175
3176 // And convert output stream configuration from HIDL
3177
3178 for (size_t i = 0; i < config->num_streams; i++) {
3179 camera3_stream_t *dst = config->streams[i];
3180 int streamId = Camera3Stream::cast(dst)->getId();
3181
3182 // Start scan at i, with the assumption that the stream order matches
3183 size_t realIdx = i;
3184 bool found = false;
3185 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3186 if (finalConfiguration.streams[realIdx].id == streamId) {
3187 found = true;
3188 break;
3189 }
3190 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3191 }
3192 if (!found) {
3193 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3194 __FUNCTION__, streamId);
3195 return INVALID_OPERATION;
3196 }
3197 HalStream &src = finalConfiguration.streams[realIdx];
3198
3199 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3200 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3201 if (dst->format != overrideFormat) {
3202 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3203 streamId, dst->format);
3204 }
3205 } else {
3206 // Override allowed with IMPLEMENTATION_DEFINED
3207 dst->format = overrideFormat;
3208 }
3209
3210 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3211 if (src.producerUsage != 0) {
3212 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3213 __FUNCTION__, streamId);
3214 return INVALID_OPERATION;
3215 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003216 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003217 } else {
3218 // OUTPUT
3219 if (src.consumerUsage != 0) {
3220 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3221 __FUNCTION__, streamId);
3222 return INVALID_OPERATION;
3223 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003224 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003225 }
3226 dst->max_buffers = src.maxBuffers;
3227 }
3228 }
3229 return res;
3230}
3231
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003232void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3233 /*out*/device::V3_2::CaptureRequest* captureRequest,
3234 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3235
3236 if (captureRequest == nullptr || handlesCreated == nullptr) {
3237 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3238 __FUNCTION__, captureRequest, handlesCreated);
3239 return;
3240 }
3241
3242 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003243
3244 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003245
3246 {
3247 std::lock_guard<std::mutex> lock(mInflightLock);
3248 if (request->input_buffer != nullptr) {
3249 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3250 buffer_handle_t buf = *(request->input_buffer->buffer);
3251 auto pair = getBufferId(buf, streamId);
3252 bool isNewBuffer = pair.first;
3253 uint64_t bufferId = pair.second;
3254 captureRequest->inputBuffer.streamId = streamId;
3255 captureRequest->inputBuffer.bufferId = bufferId;
3256 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3257 captureRequest->inputBuffer.status = BufferStatus::OK;
3258 native_handle_t *acquireFence = nullptr;
3259 if (request->input_buffer->acquire_fence != -1) {
3260 acquireFence = native_handle_create(1,0);
3261 acquireFence->data[0] = request->input_buffer->acquire_fence;
3262 handlesCreated->push_back(acquireFence);
3263 }
3264 captureRequest->inputBuffer.acquireFence = acquireFence;
3265 captureRequest->inputBuffer.releaseFence = nullptr;
3266
3267 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3268 request->input_buffer->buffer,
3269 request->input_buffer->acquire_fence);
3270 } else {
3271 captureRequest->inputBuffer.streamId = -1;
3272 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3273 }
3274
3275 captureRequest->outputBuffers.resize(request->num_output_buffers);
3276 for (size_t i = 0; i < request->num_output_buffers; i++) {
3277 const camera3_stream_buffer_t *src = request->output_buffers + i;
3278 StreamBuffer &dst = captureRequest->outputBuffers[i];
3279 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3280 buffer_handle_t buf = *(src->buffer);
3281 auto pair = getBufferId(buf, streamId);
3282 bool isNewBuffer = pair.first;
3283 dst.streamId = streamId;
3284 dst.bufferId = pair.second;
3285 dst.buffer = isNewBuffer ? buf : nullptr;
3286 dst.status = BufferStatus::OK;
3287 native_handle_t *acquireFence = nullptr;
3288 if (src->acquire_fence != -1) {
3289 acquireFence = native_handle_create(1,0);
3290 acquireFence->data[0] = src->acquire_fence;
3291 handlesCreated->push_back(acquireFence);
3292 }
3293 dst.acquireFence = acquireFence;
3294 dst.releaseFence = nullptr;
3295
3296 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3297 src->buffer, src->acquire_fence);
3298 }
3299 }
3300}
3301
3302status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3303 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3304 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3305 if (!valid()) return INVALID_OPERATION;
3306
3307 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3308 size_t batchSize = requests.size();
3309 captureRequests.resize(batchSize);
3310 std::vector<native_handle_t*> handlesCreated;
3311
3312 for (size_t i = 0; i < batchSize; i++) {
3313 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3314 }
3315
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003316 std::vector<device::V3_2::BufferCache> cachesToRemove;
3317 {
3318 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3319 for (auto& pair : mFreedBuffers) {
3320 // The stream might have been removed since onBufferFreed
3321 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3322 cachesToRemove.push_back({pair.first, pair.second});
3323 }
3324 }
3325 mFreedBuffers.clear();
3326 }
3327
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003328 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3329 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003330
3331 // Write metadata to FMQ.
3332 for (size_t i = 0; i < batchSize; i++) {
3333 camera3_capture_request_t* request = requests[i];
3334 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3335
3336 if (request->settings != nullptr) {
3337 size_t settingsSize = get_camera_metadata_size(request->settings);
3338 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3339 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3340 captureRequest->settings.resize(0);
3341 captureRequest->fmqSettingsSize = settingsSize;
3342 } else {
3343 if (mRequestMetadataQueue != nullptr) {
3344 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3345 }
3346 captureRequest->settings.setToExternal(
3347 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3348 get_camera_metadata_size(request->settings));
3349 captureRequest->fmqSettingsSize = 0u;
3350 }
3351 } else {
3352 // A null request settings maps to a size-0 CameraMetadata
3353 captureRequest->settings.resize(0);
3354 captureRequest->fmqSettingsSize = 0u;
3355 }
3356 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003357 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003358 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3359 status = s;
3360 *numRequestProcessed = n;
3361 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003362 if (!err.isOk()) {
3363 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3364 return DEAD_OBJECT;
3365 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003366 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3367 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3368 __FUNCTION__, *numRequestProcessed, batchSize);
3369 status = common::V1_0::Status::INTERNAL_ERROR;
3370 }
3371
3372 for (auto& handle : handlesCreated) {
3373 native_handle_delete(handle);
3374 }
3375 return CameraProviderManager::mapToStatusT(status);
3376}
3377
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003378status_t Camera3Device::HalInterface::processCaptureRequest(
3379 camera3_capture_request_t *request) {
3380 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003381 if (!valid()) return INVALID_OPERATION;
3382 status_t res = OK;
3383
3384 if (mHal3Device != nullptr) {
3385 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3386 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003387 uint32_t numRequestProcessed = 0;
3388 std::vector<camera3_capture_request_t*> requests(1);
3389 requests[0] = request;
3390 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003391 }
3392 return res;
3393}
3394
3395status_t Camera3Device::HalInterface::flush() {
3396 ATRACE_NAME("CameraHal::flush");
3397 if (!valid()) return INVALID_OPERATION;
3398 status_t res = OK;
3399
3400 if (mHal3Device != nullptr) {
3401 res = mHal3Device->ops->flush(mHal3Device);
3402 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003403 auto err = mHidlSession->flush();
3404 if (!err.isOk()) {
3405 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3406 res = DEAD_OBJECT;
3407 } else {
3408 res = CameraProviderManager::mapToStatusT(err);
3409 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003410 }
3411 return res;
3412}
3413
3414status_t Camera3Device::HalInterface::dump(int fd) {
3415 ATRACE_NAME("CameraHal::dump");
3416 if (!valid()) return INVALID_OPERATION;
3417 status_t res = OK;
3418
3419 if (mHal3Device != nullptr) {
3420 mHal3Device->ops->dump(mHal3Device, fd);
3421 } else {
3422 // Handled by CameraProviderManager::dump
3423 }
3424 return res;
3425}
3426
3427status_t Camera3Device::HalInterface::close() {
3428 ATRACE_NAME("CameraHal::close()");
3429 if (!valid()) return INVALID_OPERATION;
3430 status_t res = OK;
3431
3432 if (mHal3Device != nullptr) {
3433 mHal3Device->common.close(&mHal3Device->common);
3434 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003435 auto err = mHidlSession->close();
3436 // Interface will be dead shortly anyway, so don't log errors
3437 if (!err.isOk()) {
3438 res = DEAD_OBJECT;
3439 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003440 }
3441 return res;
3442}
3443
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003444void Camera3Device::HalInterface::getInflightBufferKeys(
3445 std::vector<std::pair<int32_t, int32_t>>* out) {
3446 std::lock_guard<std::mutex> lock(mInflightLock);
3447 out->clear();
3448 out->reserve(mInflightBufferMap.size());
3449 for (auto& pair : mInflightBufferMap) {
3450 uint64_t key = pair.first;
3451 int32_t streamId = key & 0xFFFFFFFF;
3452 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3453 out->push_back(std::make_pair(frameNumber, streamId));
3454 }
3455 return;
3456}
3457
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003458status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003459 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003460 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003461 auto pair = std::make_pair(buffer, acquireFence);
3462 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003463 return OK;
3464}
3465
3466status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003467 int32_t frameNumber, int32_t streamId,
3468 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003469 std::lock_guard<std::mutex> lock(mInflightLock);
3470
3471 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3472 auto it = mInflightBufferMap.find(key);
3473 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003474 auto pair = it->second;
3475 *buffer = pair.first;
3476 int acquireFence = pair.second;
3477 if (acquireFence > 0) {
3478 ::close(acquireFence);
3479 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003480 mInflightBufferMap.erase(it);
3481 return OK;
3482}
3483
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003484std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3485 const buffer_handle_t& buf, int streamId) {
3486 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3487
3488 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3489 auto it = bIdMap.find(buf);
3490 if (it == bIdMap.end()) {
3491 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003492 ALOGV("stream %d now have %zu buffer caches, buf %p",
3493 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003494 return std::make_pair(true, mNextBufferId - 1);
3495 } else {
3496 return std::make_pair(false, it->second);
3497 }
3498}
3499
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003500void Camera3Device::HalInterface::onBufferFreed(
3501 int streamId, const native_handle_t* handle) {
3502 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3503 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3504 auto mapIt = mBufferIdMaps.find(streamId);
3505 if (mapIt == mBufferIdMaps.end()) {
3506 // streamId might be from a deleted stream here
3507 ALOGI("%s: stream %d has been removed",
3508 __FUNCTION__, streamId);
3509 return;
3510 }
3511 BufferIdMap& bIdMap = mapIt->second;
3512 auto it = bIdMap.find(handle);
3513 if (it == bIdMap.end()) {
3514 ALOGW("%s: cannot find buffer %p in stream %d",
3515 __FUNCTION__, handle, streamId);
3516 return;
3517 } else {
3518 bufferId = it->second;
3519 bIdMap.erase(it);
3520 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3521 __FUNCTION__, streamId, bIdMap.size(), handle);
3522 }
3523 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3524}
3525
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003526/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003527 * RequestThread inner class methods
3528 */
3529
3530Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003531 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003532 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003533 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003534 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003535 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003536 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003537 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003538 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003539 mReconfigured(false),
3540 mDoPause(false),
3541 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003542 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003543 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003544 mCurrentAfTriggerId(0),
3545 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003546 mRepeatingLastFrameNumber(
3547 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003548 mPrepareVideoStream(false),
3549 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003550 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003551}
3552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003553Camera3Device::RequestThread::~RequestThread() {}
3554
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003555void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003556 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003557 Mutex::Autolock l(mRequestLock);
3558 mListener = listener;
3559}
3560
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003561void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003562 Mutex::Autolock l(mRequestLock);
3563 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003564 // Prepare video stream for high speed recording.
3565 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003566}
3567
Jianing Wei90e59c92014-03-12 18:29:36 -07003568status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003569 List<sp<CaptureRequest> > &requests,
3570 /*out*/
3571 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003572 Mutex::Autolock l(mRequestLock);
3573 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3574 ++it) {
3575 mRequestQueue.push_back(*it);
3576 }
3577
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003578 if (lastFrameNumber != NULL) {
3579 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3580 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3581 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3582 *lastFrameNumber);
3583 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003584
Jianing Wei90e59c92014-03-12 18:29:36 -07003585 unpauseForNewRequests();
3586
3587 return OK;
3588}
3589
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003590
3591status_t Camera3Device::RequestThread::queueTrigger(
3592 RequestTrigger trigger[],
3593 size_t count) {
3594
3595 Mutex::Autolock l(mTriggerMutex);
3596 status_t ret;
3597
3598 for (size_t i = 0; i < count; ++i) {
3599 ret = queueTriggerLocked(trigger[i]);
3600
3601 if (ret != OK) {
3602 return ret;
3603 }
3604 }
3605
3606 return OK;
3607}
3608
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003609const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3610 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003611 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003612 if (d != nullptr) return d->mId;
3613 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003614}
3615
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003616status_t Camera3Device::RequestThread::queueTriggerLocked(
3617 RequestTrigger trigger) {
3618
3619 uint32_t tag = trigger.metadataTag;
3620 ssize_t index = mTriggerMap.indexOfKey(tag);
3621
3622 switch (trigger.getTagType()) {
3623 case TYPE_BYTE:
3624 // fall-through
3625 case TYPE_INT32:
3626 break;
3627 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003628 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3629 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003630 return INVALID_OPERATION;
3631 }
3632
3633 /**
3634 * Collect only the latest trigger, since we only have 1 field
3635 * in the request settings per trigger tag, and can't send more than 1
3636 * trigger per request.
3637 */
3638 if (index != NAME_NOT_FOUND) {
3639 mTriggerMap.editValueAt(index) = trigger;
3640 } else {
3641 mTriggerMap.add(tag, trigger);
3642 }
3643
3644 return OK;
3645}
3646
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003647status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003648 const RequestList &requests,
3649 /*out*/
3650 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003651 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003652 if (lastFrameNumber != NULL) {
3653 *lastFrameNumber = mRepeatingLastFrameNumber;
3654 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003655 mRepeatingRequests.clear();
3656 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3657 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003658
3659 unpauseForNewRequests();
3660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003661 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003662 return OK;
3663}
3664
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003665bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003666 if (mRepeatingRequests.empty()) {
3667 return false;
3668 }
3669 int32_t requestId = requestIn->mResultExtras.requestId;
3670 const RequestList &repeatRequests = mRepeatingRequests;
3671 // All repeating requests are guaranteed to have same id so only check first quest
3672 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3673 return (firstRequest->mResultExtras.requestId == requestId);
3674}
3675
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003676status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003677 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003678 return clearRepeatingRequestsLocked(lastFrameNumber);
3679
3680}
3681
3682status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003683 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003684 if (lastFrameNumber != NULL) {
3685 *lastFrameNumber = mRepeatingLastFrameNumber;
3686 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003687 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003688 return OK;
3689}
3690
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003691status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003692 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003693 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003694 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003695
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003696 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003697
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003698 // Send errors for all requests pending in the request queue, including
3699 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003700 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003701 if (listener != NULL) {
3702 for (RequestList::iterator it = mRequestQueue.begin();
3703 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003704 // Abort the input buffers for reprocess requests.
3705 if ((*it)->mInputStream != NULL) {
3706 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003707 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3708 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003709 if (res != OK) {
3710 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3711 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3712 } else {
3713 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3714 if (res != OK) {
3715 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3716 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3717 }
3718 }
3719 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003720 // Set the frame number this request would have had, if it
3721 // had been submitted; this frame number will not be reused.
3722 // The requestId and burstId fields were set when the request was
3723 // submitted originally (in convertMetadataListToRequestListLocked)
3724 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003725 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003726 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003727 }
3728 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003729 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003730
3731 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003732 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003733 if (lastFrameNumber != NULL) {
3734 *lastFrameNumber = mRepeatingLastFrameNumber;
3735 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003737 return OK;
3738}
3739
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003740status_t Camera3Device::RequestThread::flush() {
3741 ATRACE_CALL();
3742 Mutex::Autolock l(mFlushLock);
3743
Emilian Peev08dd2452017-04-06 16:55:14 +01003744 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003745}
3746
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003747void Camera3Device::RequestThread::setPaused(bool paused) {
3748 Mutex::Autolock l(mPauseLock);
3749 mDoPause = paused;
3750 mDoPauseSignal.signal();
3751}
3752
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003753status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3754 int32_t requestId, nsecs_t timeout) {
3755 Mutex::Autolock l(mLatestRequestMutex);
3756 status_t res;
3757 while (mLatestRequestId != requestId) {
3758 nsecs_t startTime = systemTime();
3759
3760 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3761 if (res != OK) return res;
3762
3763 timeout -= (systemTime() - startTime);
3764 }
3765
3766 return OK;
3767}
3768
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003769void Camera3Device::RequestThread::requestExit() {
3770 // Call parent to set up shutdown
3771 Thread::requestExit();
3772 // The exit from any possible waits
3773 mDoPauseSignal.signal();
3774 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003775
3776 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3777 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003778}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003779
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003780void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003781 bool surfaceAbandoned = false;
3782 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003783 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003784 {
3785 Mutex::Autolock l(mRequestLock);
3786 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3787 // repeating requests.
3788 for (const auto& request : mRepeatingRequests) {
3789 for (const auto& s : request->mOutputStreams) {
3790 if (s->isAbandoned()) {
3791 surfaceAbandoned = true;
3792 clearRepeatingRequestsLocked(&lastFrameNumber);
3793 break;
3794 }
3795 }
3796 if (surfaceAbandoned) {
3797 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003798 }
3799 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003800 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003801 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003802
3803 if (listener != NULL && surfaceAbandoned) {
3804 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003805 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003806}
3807
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003808bool Camera3Device::RequestThread::sendRequestsBatch() {
3809 status_t res;
3810 size_t batchSize = mNextRequests.size();
3811 std::vector<camera3_capture_request_t*> requests(batchSize);
3812 uint32_t numRequestProcessed = 0;
3813 for (size_t i = 0; i < batchSize; i++) {
3814 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3815 }
3816
3817 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3818 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3819
3820 bool triggerRemoveFailed = false;
3821 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3822 for (size_t i = 0; i < numRequestProcessed; i++) {
3823 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3824 nextRequest.submitted = true;
3825
3826
3827 // Update the latest request sent to HAL
3828 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3829 Mutex::Autolock al(mLatestRequestMutex);
3830
3831 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3832 mLatestRequest.acquire(cloned);
3833
3834 sp<Camera3Device> parent = mParent.promote();
3835 if (parent != NULL) {
3836 parent->monitorMetadata(TagMonitor::REQUEST,
3837 nextRequest.halRequest.frame_number,
3838 0, mLatestRequest);
3839 }
3840 }
3841
3842 if (nextRequest.halRequest.settings != NULL) {
3843 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3844 }
3845
3846 if (!triggerRemoveFailed) {
3847 // Remove any previously queued triggers (after unlock)
3848 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3849 if (removeTriggerRes != OK) {
3850 triggerRemoveFailed = true;
3851 triggerFailedRequest = nextRequest;
3852 }
3853 }
3854 }
3855
3856 if (triggerRemoveFailed) {
3857 SET_ERR("RequestThread: Unable to remove triggers "
3858 "(capture request %d, HAL device: %s (%d)",
3859 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3860 cleanUpFailedRequests(/*sendRequestError*/ false);
3861 return false;
3862 }
3863
3864 if (res != OK) {
3865 // Should only get a failure here for malformed requests or device-level
3866 // errors, so consider all errors fatal. Bad metadata failures should
3867 // come through notify.
3868 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3869 mNextRequests[numRequestProcessed].halRequest.frame_number,
3870 strerror(-res), res);
3871 cleanUpFailedRequests(/*sendRequestError*/ false);
3872 return false;
3873 }
3874 return true;
3875}
3876
3877bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3878 status_t res;
3879
3880 for (auto& nextRequest : mNextRequests) {
3881 // Submit request and block until ready for next one
3882 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3883 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3884
3885 if (res != OK) {
3886 // Should only get a failure here for malformed requests or device-level
3887 // errors, so consider all errors fatal. Bad metadata failures should
3888 // come through notify.
3889 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3890 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3891 res);
3892 cleanUpFailedRequests(/*sendRequestError*/ false);
3893 return false;
3894 }
3895
3896 // Mark that the request has be submitted successfully.
3897 nextRequest.submitted = true;
3898
3899 // Update the latest request sent to HAL
3900 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3901 Mutex::Autolock al(mLatestRequestMutex);
3902
3903 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3904 mLatestRequest.acquire(cloned);
3905
3906 sp<Camera3Device> parent = mParent.promote();
3907 if (parent != NULL) {
3908 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3909 0, mLatestRequest);
3910 }
3911 }
3912
3913 if (nextRequest.halRequest.settings != NULL) {
3914 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3915 }
3916
3917 // Remove any previously queued triggers (after unlock)
3918 res = removeTriggers(mPrevRequest);
3919 if (res != OK) {
3920 SET_ERR("RequestThread: Unable to remove triggers "
3921 "(capture request %d, HAL device: %s (%d)",
3922 nextRequest.halRequest.frame_number, strerror(-res), res);
3923 cleanUpFailedRequests(/*sendRequestError*/ false);
3924 return false;
3925 }
3926 }
3927 return true;
3928}
3929
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003930nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3931 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3932 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3933 find_camera_metadata_ro_entry(request,
3934 ANDROID_CONTROL_AE_MODE,
3935 &e);
3936 if (e.count == 0) return maxExpectedDuration;
3937
3938 switch (e.data.u8[0]) {
3939 case ANDROID_CONTROL_AE_MODE_OFF:
3940 find_camera_metadata_ro_entry(request,
3941 ANDROID_SENSOR_EXPOSURE_TIME,
3942 &e);
3943 if (e.count > 0) {
3944 maxExpectedDuration = e.data.i64[0];
3945 }
3946 find_camera_metadata_ro_entry(request,
3947 ANDROID_SENSOR_FRAME_DURATION,
3948 &e);
3949 if (e.count > 0) {
3950 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3951 }
3952 break;
3953 default:
3954 find_camera_metadata_ro_entry(request,
3955 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3956 &e);
3957 if (e.count > 1) {
3958 maxExpectedDuration = 1e9 / e.data.u8[0];
3959 }
3960 break;
3961 }
3962
3963 return maxExpectedDuration;
3964}
3965
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003966bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003967 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003968 status_t res;
3969
3970 // Handle paused state.
3971 if (waitIfPaused()) {
3972 return true;
3973 }
3974
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003975 // Wait for the next batch of requests.
3976 waitForNextRequestBatch();
3977 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003978 return true;
3979 }
3980
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003981 // Get the latest request ID, if any
3982 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003983 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003984 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003985 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003986 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003987 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003988 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3989 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003990 }
3991
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003992 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003993 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003994 if (res == TIMED_OUT) {
3995 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003996 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003997 // Check if any stream is abandoned.
3998 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003999 return true;
4000 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004001 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004002 return false;
4003 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004004
Zhijun Hecc27e112013-10-03 16:12:43 -07004005 // Inform waitUntilRequestProcessed thread of a new request ID
4006 {
4007 Mutex::Autolock al(mLatestRequestMutex);
4008
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004009 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004010 mLatestRequestSignal.signal();
4011 }
4012
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004013 // Submit a batch of requests to HAL.
4014 // Use flush lock only when submitting multilple requests in a batch.
4015 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4016 // which may take a long time to finish so synchronizing flush() and
4017 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4018 // For now, only synchronize for high speed recording and we should figure something out for
4019 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004020 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004021
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004022 if (useFlushLock) {
4023 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004024 }
4025
Zhijun Hef0645c12016-08-02 00:58:11 -07004026 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004027 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004028
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004029 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004030 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004031 if (mInterface->supportBatchRequest()) {
4032 submitRequestSuccess = sendRequestsBatch();
4033 } else {
4034 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004035 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004036 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4037 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004038
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004039 if (useFlushLock) {
4040 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004041 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004042
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004043 // Unset as current request
4044 {
4045 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004046 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004047 }
4048
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004049 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004050}
4051
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004052status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004053 ATRACE_CALL();
4054
Shuzhen Wang4a472662017-02-26 23:29:04 -08004055 for (size_t i = 0; i < mNextRequests.size(); i++) {
4056 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004057 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4058 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4059 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4060
4061 // Prepare a request to HAL
4062 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4063
4064 // Insert any queued triggers (before metadata is locked)
4065 status_t res = insertTriggers(captureRequest);
4066
4067 if (res < 0) {
4068 SET_ERR("RequestThread: Unable to insert triggers "
4069 "(capture request %d, HAL device: %s (%d)",
4070 halRequest->frame_number, strerror(-res), res);
4071 return INVALID_OPERATION;
4072 }
4073 int triggerCount = res;
4074 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4075 mPrevTriggers = triggerCount;
4076
4077 // If the request is the same as last, or we had triggers last time
4078 if (mPrevRequest != captureRequest || triggersMixedIn) {
4079 /**
4080 * HAL workaround:
4081 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4082 */
4083 res = addDummyTriggerIds(captureRequest);
4084 if (res != OK) {
4085 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4086 "(capture request %d, HAL device: %s (%d)",
4087 halRequest->frame_number, strerror(-res), res);
4088 return INVALID_OPERATION;
4089 }
4090
4091 /**
4092 * The request should be presorted so accesses in HAL
4093 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4094 */
4095 captureRequest->mSettings.sort();
4096 halRequest->settings = captureRequest->mSettings.getAndLock();
4097 mPrevRequest = captureRequest;
4098 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4099
4100 IF_ALOGV() {
4101 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4102 find_camera_metadata_ro_entry(
4103 halRequest->settings,
4104 ANDROID_CONTROL_AF_TRIGGER,
4105 &e
4106 );
4107 if (e.count > 0) {
4108 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4109 __FUNCTION__,
4110 halRequest->frame_number,
4111 e.data.u8[0]);
4112 }
4113 }
4114 } else {
4115 // leave request.settings NULL to indicate 'reuse latest given'
4116 ALOGVV("%s: Request settings are REUSED",
4117 __FUNCTION__);
4118 }
4119
4120 uint32_t totalNumBuffers = 0;
4121
4122 // Fill in buffers
4123 if (captureRequest->mInputStream != NULL) {
4124 halRequest->input_buffer = &captureRequest->mInputBuffer;
4125 totalNumBuffers += 1;
4126 } else {
4127 halRequest->input_buffer = NULL;
4128 }
4129
4130 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4131 captureRequest->mOutputStreams.size());
4132 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004133 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4134 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004135
4136 // Prepare video buffers for high speed recording on the first video request.
4137 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4138 // Only try to prepare video stream on the first video request.
4139 mPrepareVideoStream = false;
4140
4141 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4142 while (res == NOT_ENOUGH_DATA) {
4143 res = outputStream->prepareNextBuffer();
4144 }
4145 if (res != OK) {
4146 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4147 __FUNCTION__, strerror(-res), res);
4148 outputStream->cancelPrepare();
4149 }
4150 }
4151
Shuzhen Wang4a472662017-02-26 23:29:04 -08004152 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4153 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004154 if (res != OK) {
4155 // Can't get output buffer from gralloc queue - this could be due to
4156 // abandoned queue or other consumer misbehavior, so not a fatal
4157 // error
4158 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4159 " %s (%d)", strerror(-res), res);
4160
4161 return TIMED_OUT;
4162 }
4163 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004164
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004165 }
4166 totalNumBuffers += halRequest->num_output_buffers;
4167
4168 // Log request in the in-flight queue
4169 sp<Camera3Device> parent = mParent.promote();
4170 if (parent == NULL) {
4171 // Should not happen, and nowhere to send errors to, so just log it
4172 CLOGE("RequestThread: Parent is gone");
4173 return INVALID_OPERATION;
4174 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004175
4176 // If this request list is for constrained high speed recording (not
4177 // preview), and the current request is not the last one in the batch,
4178 // do not send callback to the app.
4179 bool hasCallback = true;
4180 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4181 hasCallback = false;
4182 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004183 res = parent->registerInFlight(halRequest->frame_number,
4184 totalNumBuffers, captureRequest->mResultExtras,
4185 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004186 hasCallback,
4187 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004188 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4189 ", burstId = %" PRId32 ".",
4190 __FUNCTION__,
4191 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4192 captureRequest->mResultExtras.burstId);
4193 if (res != OK) {
4194 SET_ERR("RequestThread: Unable to register new in-flight request:"
4195 " %s (%d)", strerror(-res), res);
4196 return INVALID_OPERATION;
4197 }
4198 }
4199
4200 return OK;
4201}
4202
Igor Murashkin1e479c02013-09-06 16:55:14 -07004203CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4204 Mutex::Autolock al(mLatestRequestMutex);
4205
4206 ALOGV("RequestThread::%s", __FUNCTION__);
4207
4208 return mLatestRequest;
4209}
4210
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004211bool Camera3Device::RequestThread::isStreamPending(
4212 sp<Camera3StreamInterface>& stream) {
4213 Mutex::Autolock l(mRequestLock);
4214
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004215 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004216 if (!nextRequest.submitted) {
4217 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4218 if (stream == s) return true;
4219 }
4220 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004221 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004222 }
4223
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004224 for (const auto& request : mRequestQueue) {
4225 for (const auto& s : request->mOutputStreams) {
4226 if (stream == s) return true;
4227 }
4228 if (stream == request->mInputStream) return true;
4229 }
4230
4231 for (const auto& request : mRepeatingRequests) {
4232 for (const auto& s : request->mOutputStreams) {
4233 if (stream == s) return true;
4234 }
4235 if (stream == request->mInputStream) return true;
4236 }
4237
4238 return false;
4239}
Jianing Weicb0652e2014-03-12 18:29:36 -07004240
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004241nsecs_t Camera3Device::getExpectedInFlightDurationLocked() {
4242 return mExpectedInflightDuration > kMinInflightDuration ?
4243 mExpectedInflightDuration : kMinInflightDuration;
4244}
4245
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004246void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4247 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004248 return;
4249 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004250
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004251 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004252 // Skip the ones that have been submitted successfully.
4253 if (nextRequest.submitted) {
4254 continue;
4255 }
4256
4257 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4258 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4259 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4260
4261 if (halRequest->settings != NULL) {
4262 captureRequest->mSettings.unlock(halRequest->settings);
4263 }
4264
4265 if (captureRequest->mInputStream != NULL) {
4266 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4267 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4268 }
4269
4270 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004271 //Buffers that failed processing could still have
4272 //valid acquire fence.
4273 int acquireFence = (*outputBuffers)[i].acquire_fence;
4274 if (0 <= acquireFence) {
4275 close(acquireFence);
4276 outputBuffers->editItemAt(i).acquire_fence = -1;
4277 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004278 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4279 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4280 }
4281
4282 if (sendRequestError) {
4283 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004284 sp<NotificationListener> listener = mListener.promote();
4285 if (listener != NULL) {
4286 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004287 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004288 captureRequest->mResultExtras);
4289 }
4290 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004291
4292 // Remove yet-to-be submitted inflight request from inflightMap
4293 {
4294 sp<Camera3Device> parent = mParent.promote();
4295 if (parent != NULL) {
4296 Mutex::Autolock l(parent->mInFlightLock);
4297 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4298 if (idx >= 0) {
4299 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4300 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4301 parent->removeInFlightMapEntryLocked(idx);
4302 }
4303 }
4304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004305 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004306
4307 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004308 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309}
4310
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004311void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 // Optimized a bit for the simple steady-state case (single repeating
4313 // request), to avoid putting that request in the queue temporarily.
4314 Mutex::Autolock l(mRequestLock);
4315
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004316 assert(mNextRequests.empty());
4317
4318 NextRequest nextRequest;
4319 nextRequest.captureRequest = waitForNextRequestLocked();
4320 if (nextRequest.captureRequest == nullptr) {
4321 return;
4322 }
4323
4324 nextRequest.halRequest = camera3_capture_request_t();
4325 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004326 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004327
4328 // Wait for additional requests
4329 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4330
4331 for (size_t i = 1; i < batchSize; i++) {
4332 NextRequest additionalRequest;
4333 additionalRequest.captureRequest = waitForNextRequestLocked();
4334 if (additionalRequest.captureRequest == nullptr) {
4335 break;
4336 }
4337
4338 additionalRequest.halRequest = camera3_capture_request_t();
4339 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004340 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004341 }
4342
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004343 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004344 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004345 mNextRequests.size(), batchSize);
4346 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004347 }
4348
4349 return;
4350}
4351
4352sp<Camera3Device::CaptureRequest>
4353 Camera3Device::RequestThread::waitForNextRequestLocked() {
4354 status_t res;
4355 sp<CaptureRequest> nextRequest;
4356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 while (mRequestQueue.empty()) {
4358 if (!mRepeatingRequests.empty()) {
4359 // Always atomically enqueue all requests in a repeating request
4360 // list. Guarantees a complete in-sequence set of captures to
4361 // application.
4362 const RequestList &requests = mRepeatingRequests;
4363 RequestList::const_iterator firstRequest =
4364 requests.begin();
4365 nextRequest = *firstRequest;
4366 mRequestQueue.insert(mRequestQueue.end(),
4367 ++firstRequest,
4368 requests.end());
4369 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004370
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004371 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004372
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004373 break;
4374 }
4375
4376 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4377
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004378 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4379 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 Mutex::Autolock pl(mPauseLock);
4381 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004382 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004383 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004384 // Let the tracker know
4385 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4386 if (statusTracker != 0) {
4387 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4388 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004389 }
4390 // Stop waiting for now and let thread management happen
4391 return NULL;
4392 }
4393 }
4394
4395 if (nextRequest == NULL) {
4396 // Don't have a repeating request already in hand, so queue
4397 // must have an entry now.
4398 RequestList::iterator firstRequest =
4399 mRequestQueue.begin();
4400 nextRequest = *firstRequest;
4401 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004402 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4403 sp<NotificationListener> listener = mListener.promote();
4404 if (listener != NULL) {
4405 listener->notifyRequestQueueEmpty();
4406 }
4407 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408 }
4409
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004410 // In case we've been unpaused by setPaused clearing mDoPause, need to
4411 // update internal pause state (capture/setRepeatingRequest unpause
4412 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004414 if (mPaused) {
4415 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4416 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4417 if (statusTracker != 0) {
4418 statusTracker->markComponentActive(mStatusId);
4419 }
4420 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004421 mPaused = false;
4422
4423 // Check if we've reconfigured since last time, and reset the preview
4424 // request if so. Can't use 'NULL request == repeat' across configure calls.
4425 if (mReconfigured) {
4426 mPrevRequest.clear();
4427 mReconfigured = false;
4428 }
4429
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004430 if (nextRequest != NULL) {
4431 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004432 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4433 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004434
4435 // Since RequestThread::clear() removes buffers from the input stream,
4436 // get the right buffer here before unlocking mRequestLock
4437 if (nextRequest->mInputStream != NULL) {
4438 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4439 if (res != OK) {
4440 // Can't get input buffer from gralloc queue - this could be due to
4441 // disconnected queue or other producer misbehavior, so not a fatal
4442 // error
4443 ALOGE("%s: Can't get input buffer, skipping request:"
4444 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004445
4446 sp<NotificationListener> listener = mListener.promote();
4447 if (listener != NULL) {
4448 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004449 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004450 nextRequest->mResultExtras);
4451 }
4452 return NULL;
4453 }
4454 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004455 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457 return nextRequest;
4458}
4459
4460bool Camera3Device::RequestThread::waitIfPaused() {
4461 status_t res;
4462 Mutex::Autolock l(mPauseLock);
4463 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004464 if (mPaused == false) {
4465 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004466 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4467 // Let the tracker know
4468 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4469 if (statusTracker != 0) {
4470 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4471 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004472 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004473
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004474 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004475 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004476 return true;
4477 }
4478 }
4479 // We don't set mPaused to false here, because waitForNextRequest needs
4480 // to further manage the paused state in case of starvation.
4481 return false;
4482}
4483
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004484void Camera3Device::RequestThread::unpauseForNewRequests() {
4485 // With work to do, mark thread as unpaused.
4486 // If paused by request (setPaused), don't resume, to avoid
4487 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004488 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004489 Mutex::Autolock p(mPauseLock);
4490 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004491 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4492 if (mPaused) {
4493 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4494 if (statusTracker != 0) {
4495 statusTracker->markComponentActive(mStatusId);
4496 }
4497 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004498 mPaused = false;
4499 }
4500}
4501
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004502void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4503 sp<Camera3Device> parent = mParent.promote();
4504 if (parent != NULL) {
4505 va_list args;
4506 va_start(args, fmt);
4507
4508 parent->setErrorStateV(fmt, args);
4509
4510 va_end(args);
4511 }
4512}
4513
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004514status_t Camera3Device::RequestThread::insertTriggers(
4515 const sp<CaptureRequest> &request) {
4516
4517 Mutex::Autolock al(mTriggerMutex);
4518
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004519 sp<Camera3Device> parent = mParent.promote();
4520 if (parent == NULL) {
4521 CLOGE("RequestThread: Parent is gone");
4522 return DEAD_OBJECT;
4523 }
4524
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004525 CameraMetadata &metadata = request->mSettings;
4526 size_t count = mTriggerMap.size();
4527
4528 for (size_t i = 0; i < count; ++i) {
4529 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004530 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004531
4532 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4533 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4534 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004535 if (isAeTrigger) {
4536 request->mResultExtras.precaptureTriggerId = triggerId;
4537 mCurrentPreCaptureTriggerId = triggerId;
4538 } else {
4539 request->mResultExtras.afTriggerId = triggerId;
4540 mCurrentAfTriggerId = triggerId;
4541 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004542 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004543 }
4544
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004545 camera_metadata_entry entry = metadata.find(tag);
4546
4547 if (entry.count > 0) {
4548 /**
4549 * Already has an entry for this trigger in the request.
4550 * Rewrite it with our requested trigger value.
4551 */
4552 RequestTrigger oldTrigger = trigger;
4553
4554 oldTrigger.entryValue = entry.data.u8[0];
4555
4556 mTriggerReplacedMap.add(tag, oldTrigger);
4557 } else {
4558 /**
4559 * More typical, no trigger entry, so we just add it
4560 */
4561 mTriggerRemovedMap.add(tag, trigger);
4562 }
4563
4564 status_t res;
4565
4566 switch (trigger.getTagType()) {
4567 case TYPE_BYTE: {
4568 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4569 res = metadata.update(tag,
4570 &entryValue,
4571 /*count*/1);
4572 break;
4573 }
4574 case TYPE_INT32:
4575 res = metadata.update(tag,
4576 &trigger.entryValue,
4577 /*count*/1);
4578 break;
4579 default:
4580 ALOGE("%s: Type not supported: 0x%x",
4581 __FUNCTION__,
4582 trigger.getTagType());
4583 return INVALID_OPERATION;
4584 }
4585
4586 if (res != OK) {
4587 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4588 ", value %d", __FUNCTION__, trigger.getTagName(),
4589 trigger.entryValue);
4590 return res;
4591 }
4592
4593 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4594 trigger.getTagName(),
4595 trigger.entryValue);
4596 }
4597
4598 mTriggerMap.clear();
4599
4600 return count;
4601}
4602
4603status_t Camera3Device::RequestThread::removeTriggers(
4604 const sp<CaptureRequest> &request) {
4605 Mutex::Autolock al(mTriggerMutex);
4606
4607 CameraMetadata &metadata = request->mSettings;
4608
4609 /**
4610 * Replace all old entries with their old values.
4611 */
4612 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4613 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4614
4615 status_t res;
4616
4617 uint32_t tag = trigger.metadataTag;
4618 switch (trigger.getTagType()) {
4619 case TYPE_BYTE: {
4620 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4621 res = metadata.update(tag,
4622 &entryValue,
4623 /*count*/1);
4624 break;
4625 }
4626 case TYPE_INT32:
4627 res = metadata.update(tag,
4628 &trigger.entryValue,
4629 /*count*/1);
4630 break;
4631 default:
4632 ALOGE("%s: Type not supported: 0x%x",
4633 __FUNCTION__,
4634 trigger.getTagType());
4635 return INVALID_OPERATION;
4636 }
4637
4638 if (res != OK) {
4639 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4640 ", trigger value %d", __FUNCTION__,
4641 trigger.getTagName(), trigger.entryValue);
4642 return res;
4643 }
4644 }
4645 mTriggerReplacedMap.clear();
4646
4647 /**
4648 * Remove all new entries.
4649 */
4650 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4651 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4652 status_t res = metadata.erase(trigger.metadataTag);
4653
4654 if (res != OK) {
4655 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4656 ", trigger value %d", __FUNCTION__,
4657 trigger.getTagName(), trigger.entryValue);
4658 return res;
4659 }
4660 }
4661 mTriggerRemovedMap.clear();
4662
4663 return OK;
4664}
4665
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004666status_t Camera3Device::RequestThread::addDummyTriggerIds(
4667 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004668 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004669 static const int32_t dummyTriggerId = 1;
4670 status_t res;
4671
4672 CameraMetadata &metadata = request->mSettings;
4673
4674 // If AF trigger is active, insert a dummy AF trigger ID if none already
4675 // exists
4676 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4677 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4678 if (afTrigger.count > 0 &&
4679 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4680 afId.count == 0) {
4681 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4682 if (res != OK) return res;
4683 }
4684
4685 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4686 // if none already exists
4687 camera_metadata_entry pcTrigger =
4688 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4689 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4690 if (pcTrigger.count > 0 &&
4691 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4692 pcId.count == 0) {
4693 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4694 &dummyTriggerId, 1);
4695 if (res != OK) return res;
4696 }
4697
4698 return OK;
4699}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004700
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004701/**
4702 * PreparerThread inner class methods
4703 */
4704
4705Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004706 Thread(/*canCallJava*/false), mListener(nullptr),
4707 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004708}
4709
4710Camera3Device::PreparerThread::~PreparerThread() {
4711 Thread::requestExitAndWait();
4712 if (mCurrentStream != nullptr) {
4713 mCurrentStream->cancelPrepare();
4714 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4715 mCurrentStream.clear();
4716 }
4717 clear();
4718}
4719
Ruben Brunkc78ac262015-08-13 17:58:46 -07004720status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004721 status_t res;
4722
4723 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004724 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004725
Ruben Brunkc78ac262015-08-13 17:58:46 -07004726 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004727 if (res == OK) {
4728 // No preparation needed, fire listener right off
4729 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004730 if (listener != NULL) {
4731 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004732 }
4733 return OK;
4734 } else if (res != NOT_ENOUGH_DATA) {
4735 return res;
4736 }
4737
4738 // Need to prepare, start up thread if necessary
4739 if (!mActive) {
4740 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4741 // isn't running
4742 Thread::requestExitAndWait();
4743 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4744 if (res != OK) {
4745 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004746 if (listener != NULL) {
4747 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004748 }
4749 return res;
4750 }
4751 mCancelNow = false;
4752 mActive = true;
4753 ALOGV("%s: Preparer stream started", __FUNCTION__);
4754 }
4755
4756 // queue up the work
4757 mPendingStreams.push_back(stream);
4758 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4759
4760 return OK;
4761}
4762
4763status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004764 Mutex::Autolock l(mLock);
4765
4766 for (const auto& stream : mPendingStreams) {
4767 stream->cancelPrepare();
4768 }
4769 mPendingStreams.clear();
4770 mCancelNow = true;
4771
4772 return OK;
4773}
4774
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004775void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776 Mutex::Autolock l(mLock);
4777 mListener = listener;
4778}
4779
4780bool Camera3Device::PreparerThread::threadLoop() {
4781 status_t res;
4782 {
4783 Mutex::Autolock l(mLock);
4784 if (mCurrentStream == nullptr) {
4785 // End thread if done with work
4786 if (mPendingStreams.empty()) {
4787 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4788 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4789 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4790 mActive = false;
4791 return false;
4792 }
4793
4794 // Get next stream to prepare
4795 auto it = mPendingStreams.begin();
4796 mCurrentStream = *it;
4797 mPendingStreams.erase(it);
4798 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4799 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4800 } else if (mCancelNow) {
4801 mCurrentStream->cancelPrepare();
4802 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4803 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4804 mCurrentStream.clear();
4805 mCancelNow = false;
4806 return true;
4807 }
4808 }
4809
4810 res = mCurrentStream->prepareNextBuffer();
4811 if (res == NOT_ENOUGH_DATA) return true;
4812 if (res != OK) {
4813 // Something bad happened; try to recover by cancelling prepare and
4814 // signalling listener anyway
4815 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4816 mCurrentStream->getId(), res, strerror(-res));
4817 mCurrentStream->cancelPrepare();
4818 }
4819
4820 // This stream has finished, notify listener
4821 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004822 sp<NotificationListener> listener = mListener.promote();
4823 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004824 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4825 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004826 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004827 }
4828
4829 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4830 mCurrentStream.clear();
4831
4832 return true;
4833}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004834
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004835/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004836 * Static callback forwarding methods from HAL to instance
4837 */
4838
4839void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4840 const camera3_capture_result *result) {
4841 Camera3Device *d =
4842 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004843
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004844 d->processCaptureResult(result);
4845}
4846
4847void Camera3Device::sNotify(const camera3_callback_ops *cb,
4848 const camera3_notify_msg *msg) {
4849 Camera3Device *d =
4850 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4851 d->notify(msg);
4852}
4853
4854}; // namespace android