blob: 02f54245e07fb072bf217b408dbdd05f2db65bb3 [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;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700243 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 {
245 Mutex::Autolock l(mLock);
246 if (mStatus == STATUS_UNINITIALIZED) return res;
247
248 if (mStatus == STATUS_ACTIVE ||
249 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
250 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700251 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700252 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700253 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700255 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 Talvala0b1cb142016-12-19 16:29:17 -0800314 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700315 mOutputStreams.clear();
316 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700317 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700318 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(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100410 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700411 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
Emilian Peev050f5dc2017-05-18 14:43:56 +0100463uint64_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
Emilian Peev050f5dc2017-05-18 14:43:56 +0100468uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700469 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700470 return usage;
471}
472
Zhijun Hef7da0962014-04-24 13:27:56 -0700473ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700474 // Get max jpeg size (area-wise).
475 Size maxJpegResolution = getMaxJpegResolution();
476 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800477 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
478 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700479 return BAD_VALUE;
480 }
481
Zhijun Hef7da0962014-04-24 13:27:56 -0700482 // Get max jpeg buffer size
483 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
485 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800486 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
487 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700488 return BAD_VALUE;
489 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700490 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800491 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700492
493 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700494 float scaleFactor = ((float) (width * height)) /
495 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800496 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
497 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700498 if (jpegBufferSize > maxJpegBufferSize) {
499 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700500 }
501
502 return jpegBufferSize;
503}
504
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700505ssize_t Camera3Device::getPointCloudBufferSize() const {
506 const int FLOATS_PER_POINT=4;
507 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
508 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800509 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
510 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700511 return BAD_VALUE;
512 }
513 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
514 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
515 return maxBytesForPointCloud;
516}
517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800518ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800519 const int PER_CONFIGURATION_SIZE = 3;
520 const int WIDTH_OFFSET = 0;
521 const int HEIGHT_OFFSET = 1;
522 const int SIZE_OFFSET = 2;
523 camera_metadata_ro_entry rawOpaqueSizes =
524 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800525 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800526 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800527 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
528 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800529 return BAD_VALUE;
530 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700531
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800532 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
533 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
534 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
535 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
536 }
537 }
538
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800539 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
540 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800541 return BAD_VALUE;
542}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700543
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800544status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
545 ATRACE_CALL();
546 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700547
548 // Try to lock, but continue in case of failure (to avoid blocking in
549 // deadlocks)
550 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
551 bool gotLock = tryLockSpinRightRound(mLock);
552
553 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
555 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700556 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
558 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700559
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800560 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700561
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800562 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700563 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800564 int n = args.size();
565 for (int i = 0; i < n; i++) {
566 if (args[i] == templatesOption) {
567 dumpTemplates = true;
568 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700569 if (args[i] == monitorOption) {
570 if (i + 1 < n) {
571 String8 monitorTags = String8(args[i + 1]);
572 if (monitorTags == "off") {
573 mTagMonitor.disableMonitoring();
574 } else {
575 mTagMonitor.parseTagsToMonitor(monitorTags);
576 }
577 } else {
578 mTagMonitor.disableMonitoring();
579 }
580 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800581 }
582
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800583 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800584
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800585 const char *status =
586 mStatus == STATUS_ERROR ? "ERROR" :
587 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700588 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
589 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800590 mStatus == STATUS_ACTIVE ? "ACTIVE" :
591 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800593 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700594 if (mStatus == STATUS_ERROR) {
595 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
596 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800597 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800598 const char *mode =
599 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
600 mOperatingMode == static_cast<int>(
601 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
602 "CUSTOM";
603 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800604
605 if (mInputStream != NULL) {
606 write(fd, lines.string(), lines.size());
607 mInputStream->dump(fd, args);
608 } else {
609 lines.appendFormat(" No input stream.\n");
610 write(fd, lines.string(), lines.size());
611 }
612 for (size_t i = 0; i < mOutputStreams.size(); i++) {
613 mOutputStreams[i]->dump(fd,args);
614 }
615
Zhijun He431503c2016-03-07 17:30:16 -0800616 if (mBufferManager != NULL) {
617 lines = String8(" Camera3 Buffer Manager:\n");
618 write(fd, lines.string(), lines.size());
619 mBufferManager->dump(fd, args);
620 }
Zhijun He125684a2015-12-26 15:07:30 -0800621
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700622 lines = String8(" In-flight requests:\n");
623 if (mInFlightMap.size() == 0) {
624 lines.append(" None\n");
625 } else {
626 for (size_t i = 0; i < mInFlightMap.size(); i++) {
627 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700628 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700629 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800630 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700631 r.numBuffersLeft);
632 }
633 }
634 write(fd, lines.string(), lines.size());
635
Shuzhen Wang686f6442017-06-20 16:16:04 -0700636 if (mRequestThread != NULL) {
637 mRequestThread->dumpCaptureRequestLatency(fd,
638 " ProcessCaptureRequest latency histogram:");
639 }
640
Igor Murashkin1e479c02013-09-06 16:55:14 -0700641 {
642 lines = String8(" Last request sent:\n");
643 write(fd, lines.string(), lines.size());
644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700646 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
647 }
648
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800649 if (dumpTemplates) {
650 const char *templateNames[] = {
651 "TEMPLATE_PREVIEW",
652 "TEMPLATE_STILL_CAPTURE",
653 "TEMPLATE_VIDEO_RECORD",
654 "TEMPLATE_VIDEO_SNAPSHOT",
655 "TEMPLATE_ZERO_SHUTTER_LAG",
656 "TEMPLATE_MANUAL"
657 };
658
659 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800660 camera_metadata_t *templateRequest = nullptr;
661 mInterface->constructDefaultRequestSettings(
662 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800663 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800664 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800665 lines.append(" Not supported\n");
666 write(fd, lines.string(), lines.size());
667 } else {
668 write(fd, lines.string(), lines.size());
669 dump_indented_camera_metadata(templateRequest,
670 fd, /*verbosity*/2, /*indentation*/8);
671 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 }
674 }
675
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700676 mTagMonitor.dumpMonitoredMetadata(fd);
677
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800678 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800679 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800681 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800683
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700684 if (gotLock) mLock.unlock();
685 if (gotInterfaceLock) mInterfaceLock.unlock();
686
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800687 return OK;
688}
689
690const CameraMetadata& Camera3Device::info() const {
691 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800692 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
693 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700694 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800695 mStatus == STATUS_ERROR ?
696 "when in error state" : "before init");
697 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800698 return mDeviceInfo;
699}
700
Jianing Wei90e59c92014-03-12 18:29:36 -0700701status_t Camera3Device::checkStatusOkToCaptureLocked() {
702 switch (mStatus) {
703 case STATUS_ERROR:
704 CLOGE("Device has encountered a serious error");
705 return INVALID_OPERATION;
706 case STATUS_UNINITIALIZED:
707 CLOGE("Device not initialized");
708 return INVALID_OPERATION;
709 case STATUS_UNCONFIGURED:
710 case STATUS_CONFIGURED:
711 case STATUS_ACTIVE:
712 // OK
713 break;
714 default:
715 SET_ERR_L("Unexpected status: %d", mStatus);
716 return INVALID_OPERATION;
717 }
718 return OK;
719}
720
721status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700722 const List<const CameraMetadata> &metadataList,
723 const std::list<const SurfaceMap> &surfaceMaps,
724 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700725 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700726 if (requestList == NULL) {
727 CLOGE("requestList cannot be NULL.");
728 return BAD_VALUE;
729 }
730
Jianing Weicb0652e2014-03-12 18:29:36 -0700731 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700732 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
733 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
734 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
735 ++metadataIt, ++surfaceMapIt) {
736 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700737 if (newRequest == 0) {
738 CLOGE("Can't create capture request");
739 return BAD_VALUE;
740 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700741
Shuzhen Wang9d066012016-09-30 11:30:20 -0700742 newRequest->mRepeating = repeating;
743
Jianing Weicb0652e2014-03-12 18:29:36 -0700744 // Setup burst Id and request Id
745 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
747 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700748 CLOGE("RequestID entry exists; but must not be empty in metadata");
749 return BAD_VALUE;
750 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700752 } else {
753 CLOGE("RequestID does not exist in metadata");
754 return BAD_VALUE;
755 }
756
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700758
759 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700760 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
762 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
763 return BAD_VALUE;
764 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700765
766 // Setup batch size if this is a high speed video recording request.
767 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
768 auto firstRequest = requestList->begin();
769 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
770 if (outputStream->isVideoStream()) {
771 (*firstRequest)->mBatchSize = requestList->size();
772 break;
773 }
774 }
775 }
776
Jianing Wei90e59c92014-03-12 18:29:36 -0700777 return OK;
778}
779
Jianing Weicb0652e2014-03-12 18:29:36 -0700780status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800781 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800782
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700783 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 std::list<const SurfaceMap> surfaceMaps;
785 convertToRequestList(requests, surfaceMaps, request);
786
787 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
788}
789
790void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
791 std::list<const SurfaceMap>& surfaceMaps,
792 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700793 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794
795 SurfaceMap surfaceMap;
796 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
797 // With no surface list passed in, stream and surface will have 1-to-1
798 // mapping. So the surface index is 0 for each stream in the surfaceMap.
799 for (size_t i = 0; i < streams.count; i++) {
800 surfaceMap[streams.data.i32[i]].push_back(0);
801 }
802 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800803}
804
Jianing Wei90e59c92014-03-12 18:29:36 -0700805status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 const List<const CameraMetadata> &requests,
807 const std::list<const SurfaceMap> &surfaceMaps,
808 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700809 /*out*/
810 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 ATRACE_CALL();
812 Mutex::Autolock il(mInterfaceLock);
813 Mutex::Autolock l(mLock);
814
815 status_t res = checkStatusOkToCaptureLocked();
816 if (res != OK) {
817 // error logged by previous call
818 return res;
819 }
820
821 RequestList requestList;
822
Shuzhen Wang0129d522016-10-30 22:43:41 -0700823 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
824 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 if (res != OK) {
826 // error logged by previous call
827 return res;
828 }
829
830 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700831 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700832 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700833 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
835
836 if (res == OK) {
837 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
838 if (res != OK) {
839 SET_ERR_L("Can't transition to active in %f seconds!",
840 kActiveTimeout/1e9);
841 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800842 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700843 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 } else {
845 CLOGE("Cannot queue request. Impossible.");
846 return BAD_VALUE;
847 }
848
849 return res;
850}
851
Yifan Honga640c5a2017-04-12 16:30:31 -0700852// Only one processCaptureResult should be called at a time, so
853// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800854hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800855 const hardware::hidl_vec<
856 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700857 // Ideally we should grab mLock, but that can lead to deadlock, and
858 // it's not super important to get up to date value of mStatus for this
859 // warning print, hence skipping the lock here
860 if (mStatus == STATUS_ERROR) {
861 // Per API contract, HAL should act as closed after device error
862 // But mStatus can be set to error by framework as well, so just log
863 // a warning here.
864 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700865 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700866
867 if (mProcessCaptureResultLock.tryLock() != OK) {
868 // This should never happen; it indicates a wrong client implementation
869 // that doesn't follow the contract. But, we can be tolerant here.
870 ALOGE("%s: callback overlapped! waiting 1s...",
871 __FUNCTION__);
872 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
873 ALOGE("%s: cannot acquire lock in 1s, dropping results",
874 __FUNCTION__);
875 // really don't know what to do, so bail out.
876 return hardware::Void();
877 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800878 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700879 for (const auto& result : results) {
880 processOneCaptureResultLocked(result);
881 }
882 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800883 return hardware::Void();
884}
885
Yifan Honga640c5a2017-04-12 16:30:31 -0700886void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800887 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800888 camera3_capture_result r;
889 status_t res;
890 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700891
892 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
893 if (result.fmqResultSize > 0) {
894 resultMetadata.resize(result.fmqResultSize);
895 if (mResultMetadataQueue == nullptr) {
896 return; // logged in initialize()
897 }
898 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
899 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
900 __FUNCTION__, result.frameNumber, result.fmqResultSize);
901 return;
902 }
903 } else {
904 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
905 result.result.size());
906 }
907
908 if (resultMetadata.size() != 0) {
909 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
910 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800911 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
912 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
913 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800914 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800915 }
916 } else {
917 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 }
919
920 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
921 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
922 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
923 auto& bDst = outputBuffers[i];
924 const StreamBuffer &bSrc = result.outputBuffers[i];
925
926 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100927 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800928 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
929 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800930 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 }
932 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
933
934 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800935 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 if (res != OK) {
937 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
938 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800939 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 }
941 bDst.buffer = buffer;
942 bDst.status = mapHidlBufferStatus(bSrc.status);
943 bDst.acquire_fence = -1;
944 if (bSrc.releaseFence == nullptr) {
945 bDst.release_fence = -1;
946 } else if (bSrc.releaseFence->numFds == 1) {
947 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
948 } else {
949 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
950 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800951 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 }
953 }
954 r.num_output_buffers = outputBuffers.size();
955 r.output_buffers = outputBuffers.data();
956
957 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800958 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800959 r.input_buffer = nullptr;
960 } else {
961 if (mInputStream->getId() != result.inputBuffer.streamId) {
962 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
963 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800964 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800965 }
966 inputBuffer.stream = mInputStream->asHalStream();
967 buffer_handle_t *buffer;
968 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
969 &buffer);
970 if (res != OK) {
971 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
972 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800973 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800974 }
975 inputBuffer.buffer = buffer;
976 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
977 inputBuffer.acquire_fence = -1;
978 if (result.inputBuffer.releaseFence == nullptr) {
979 inputBuffer.release_fence = -1;
980 } else if (result.inputBuffer.releaseFence->numFds == 1) {
981 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
982 } else {
983 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
984 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800985 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 }
987 r.input_buffer = &inputBuffer;
988 }
989
990 r.partial_result = result.partialResult;
991
992 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800993}
994
995hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800996 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700997 // Ideally we should grab mLock, but that can lead to deadlock, and
998 // it's not super important to get up to date value of mStatus for this
999 // warning print, hence skipping the lock here
1000 if (mStatus == STATUS_ERROR) {
1001 // Per API contract, HAL should act as closed after device error
1002 // But mStatus can be set to error by framework as well, so just log
1003 // a warning here.
1004 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001005 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001006
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001007 for (const auto& msg : msgs) {
1008 notify(msg);
1009 }
1010 return hardware::Void();
1011}
1012
1013void Camera3Device::notify(
1014 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1015
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 camera3_notify_msg m;
1017 switch (msg.type) {
1018 case MsgType::ERROR:
1019 m.type = CAMERA3_MSG_ERROR;
1020 m.message.error.frame_number = msg.msg.error.frameNumber;
1021 if (msg.msg.error.errorStreamId >= 0) {
1022 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001023 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001024 ALOGE("%s: Frame %d: Invalid error stream id %d",
1025 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001026 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001027 }
1028 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1029 } else {
1030 m.message.error.error_stream = nullptr;
1031 }
1032 switch (msg.msg.error.errorCode) {
1033 case ErrorCode::ERROR_DEVICE:
1034 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1035 break;
1036 case ErrorCode::ERROR_REQUEST:
1037 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1038 break;
1039 case ErrorCode::ERROR_RESULT:
1040 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1041 break;
1042 case ErrorCode::ERROR_BUFFER:
1043 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1044 break;
1045 }
1046 break;
1047 case MsgType::SHUTTER:
1048 m.type = CAMERA3_MSG_SHUTTER;
1049 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1050 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1051 break;
1052 }
1053 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001054}
1055
Jianing Weicb0652e2014-03-12 18:29:36 -07001056status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001057 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001058 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001059 ATRACE_CALL();
1060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001062}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001063
Jianing Weicb0652e2014-03-12 18:29:36 -07001064status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1065 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001066 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001067
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001068 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001069 std::list<const SurfaceMap> surfaceMaps;
1070 convertToRequestList(requests, surfaceMaps, request);
1071
1072 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1073 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074}
1075
Jianing Weicb0652e2014-03-12 18:29:36 -07001076status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001078 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001079 ATRACE_CALL();
1080
Shuzhen Wang0129d522016-10-30 22:43:41 -07001081 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001082}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083
1084sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001085 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001086 status_t res;
1087
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001088 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001089 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1090 // so unilaterally select normal operating mode.
1091 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001092 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001094 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001095 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001096 } else if (mStatus == STATUS_UNCONFIGURED) {
1097 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001098 CLOGE("No streams configured");
1099 return NULL;
1100 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001101 }
1102
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105}
1106
Jianing Weicb0652e2014-03-12 18:29:36 -07001107status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001108 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001109 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001110 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001111
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001112 switch (mStatus) {
1113 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001114 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 return INVALID_OPERATION;
1116 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001117 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001119 case STATUS_UNCONFIGURED:
1120 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 case STATUS_ACTIVE:
1122 // OK
1123 break;
1124 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001125 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 return INVALID_OPERATION;
1127 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001128 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001129
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001130 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001131}
1132
1133status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1134 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001136
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001137 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001138}
1139
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001140status_t Camera3Device::createInputStream(
1141 uint32_t width, uint32_t height, int format, int *id) {
1142 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001143 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001144 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001145 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001146 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1147 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001148
1149 status_t res;
1150 bool wasActive = false;
1151
1152 switch (mStatus) {
1153 case STATUS_ERROR:
1154 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1155 return INVALID_OPERATION;
1156 case STATUS_UNINITIALIZED:
1157 ALOGE("%s: Device not initialized", __FUNCTION__);
1158 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001159 case STATUS_UNCONFIGURED:
1160 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001161 // OK
1162 break;
1163 case STATUS_ACTIVE:
1164 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001165 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001166 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001167 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001168 return res;
1169 }
1170 wasActive = true;
1171 break;
1172 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001174 return INVALID_OPERATION;
1175 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001176 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001177
1178 if (mInputStream != 0) {
1179 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1180 return INVALID_OPERATION;
1181 }
1182
1183 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1184 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001186
1187 mInputStream = newStream;
1188
1189 *id = mNextStreamId++;
1190
1191 // Continue captures if active at start
1192 if (wasActive) {
1193 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001194 // Reuse current operating mode for new stream config
1195 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196 if (res != OK) {
1197 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1198 __FUNCTION__, mNextStreamId, strerror(-res), res);
1199 return res;
1200 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001201 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001202 }
1203
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001204 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001205 return OK;
1206}
1207
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001208status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001209 uint32_t width, uint32_t height, int format,
1210 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev050f5dc2017-05-18 14:43:56 +01001211 int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 ATRACE_CALL();
1213
1214 if (consumer == nullptr) {
1215 ALOGE("%s: consumer must not be null", __FUNCTION__);
1216 return BAD_VALUE;
1217 }
1218
1219 std::vector<sp<Surface>> consumers;
1220 consumers.push_back(consumer);
1221
1222 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001223 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001224}
1225
1226status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1227 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1228 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Emilian Peev050f5dc2017-05-18 14:43:56 +01001229 int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001230 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001231 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001232 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001234 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Emilian Peev050f5dc2017-05-18 14:43:56 +01001235 " consumer usage %" PRIu64 ", isShared %d", mId.string(), mNextStreamId, width, height, format,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001236 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 status_t res;
1239 bool wasActive = false;
1240
1241 switch (mStatus) {
1242 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001243 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 return INVALID_OPERATION;
1245 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001246 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001248 case STATUS_UNCONFIGURED:
1249 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 // OK
1251 break;
1252 case STATUS_ACTIVE:
1253 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001254 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001256 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 return res;
1258 }
1259 wasActive = true;
1260 break;
1261 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
1264 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001265 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266
1267 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001268
Shuzhen Wang0129d522016-10-30 22:43:41 -07001269 if (consumers.size() == 0 && !hasDeferredConsumer) {
1270 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1271 return BAD_VALUE;
1272 }
Zhijun He5d677d12016-05-29 16:52:39 -07001273
Shuzhen Wang0129d522016-10-30 22:43:41 -07001274 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001275 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1276 return BAD_VALUE;
1277 }
1278
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001280 ssize_t blobBufferSize;
1281 if (dataSpace != HAL_DATASPACE_DEPTH) {
1282 blobBufferSize = getJpegBufferSize(width, height);
1283 if (blobBufferSize <= 0) {
1284 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1285 return BAD_VALUE;
1286 }
1287 } else {
1288 blobBufferSize = getPointCloudBufferSize();
1289 if (blobBufferSize <= 0) {
1290 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1291 return BAD_VALUE;
1292 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001293 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001294 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001295 width, height, blobBufferSize, format, dataSpace, rotation,
1296 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001297 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1298 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1299 if (rawOpaqueBufferSize <= 0) {
1300 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1301 return BAD_VALUE;
1302 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001303 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001304 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1305 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001306 } else if (isShared) {
1307 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1308 width, height, format, consumerUsage, dataSpace, rotation,
1309 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001310 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001311 newStream = new Camera3OutputStream(mNextStreamId,
1312 width, height, format, consumerUsage, dataSpace, rotation,
1313 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001314 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001315 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001316 width, height, format, dataSpace, rotation,
1317 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001319 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001320
Emilian Peev08dd2452017-04-06 16:55:14 +01001321 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001322
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001323 res = mOutputStreams.add(mNextStreamId, newStream);
1324 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001325 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001326 return res;
1327 }
1328
1329 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001330 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331
1332 // Continue captures if active at start
1333 if (wasActive) {
1334 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001335 // Reuse current operating mode for new stream config
1336 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001338 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1339 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001340 return res;
1341 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001342 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346}
1347
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001348status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001349 uint32_t *width, uint32_t *height,
1350 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001351 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001352 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001354
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001355 switch (mStatus) {
1356 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001357 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001358 return INVALID_OPERATION;
1359 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001360 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001362 case STATUS_UNCONFIGURED:
1363 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 case STATUS_ACTIVE:
1365 // OK
1366 break;
1367 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001368 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 return INVALID_OPERATION;
1370 }
1371
1372 ssize_t idx = mOutputStreams.indexOfKey(id);
1373 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001374 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 return idx;
1376 }
1377
1378 if (width) *width = mOutputStreams[idx]->getWidth();
1379 if (height) *height = mOutputStreams[idx]->getHeight();
1380 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001381 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001383}
1384
1385status_t Camera3Device::setStreamTransform(int id,
1386 int transform) {
1387 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 switch (mStatus) {
1392 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001393 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 return INVALID_OPERATION;
1395 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001396 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001398 case STATUS_UNCONFIGURED:
1399 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 case STATUS_ACTIVE:
1401 // OK
1402 break;
1403 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001404 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 return INVALID_OPERATION;
1406 }
1407
1408 ssize_t idx = mOutputStreams.indexOfKey(id);
1409 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 CLOGE("Stream %d does not exist",
1411 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return BAD_VALUE;
1413 }
1414
1415 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001416}
1417
1418status_t Camera3Device::deleteStream(int id) {
1419 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001420 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 Mutex::Autolock l(mLock);
1422 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001423
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001424 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001425
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 // CameraDevice semantics require device to already be idle before
1427 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001428 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001429 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001430 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 }
1432
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001433 if (mStatus == STATUS_ERROR) {
1434 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1435 __FUNCTION__, mId.string());
1436 return -EBUSY;
1437 }
1438
Igor Murashkin2fba5842013-04-22 14:03:54 -07001439 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001440 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 if (mInputStream != NULL && id == mInputStream->getId()) {
1442 deletedStream = mInputStream;
1443 mInputStream.clear();
1444 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001445 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001446 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 return BAD_VALUE;
1448 }
Zhijun He5f446352014-01-22 09:49:33 -08001449 }
1450
1451 // Delete output stream or the output part of a bi-directional stream.
1452 if (outputStreamIdx != NAME_NOT_FOUND) {
1453 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 mOutputStreams.removeItem(id);
1455 }
1456
1457 // Free up the stream endpoint so that it can be used by some other stream
1458 res = deletedStream->disconnect();
1459 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001460 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 // fall through since we want to still list the stream as deleted.
1462 }
1463 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001464 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465
1466 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467}
1468
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001469status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001470 ATRACE_CALL();
1471 ALOGV("%s: E", __FUNCTION__);
1472
1473 Mutex::Autolock il(mInterfaceLock);
1474 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001475
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001476 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001477}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001479status_t Camera3Device::getInputBufferProducer(
1480 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001481 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001482 Mutex::Autolock il(mInterfaceLock);
1483 Mutex::Autolock l(mLock);
1484
1485 if (producer == NULL) {
1486 return BAD_VALUE;
1487 } else if (mInputStream == NULL) {
1488 return INVALID_OPERATION;
1489 }
1490
1491 return mInputStream->getInputBufferProducer(producer);
1492}
1493
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494status_t Camera3Device::createDefaultRequest(int templateId,
1495 CameraMetadata *request) {
1496 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001497 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001498
1499 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1500 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1501 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1502 return BAD_VALUE;
1503 }
1504
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001507 {
1508 Mutex::Autolock l(mLock);
1509 switch (mStatus) {
1510 case STATUS_ERROR:
1511 CLOGE("Device has encountered a serious error");
1512 return INVALID_OPERATION;
1513 case STATUS_UNINITIALIZED:
1514 CLOGE("Device is not initialized!");
1515 return INVALID_OPERATION;
1516 case STATUS_UNCONFIGURED:
1517 case STATUS_CONFIGURED:
1518 case STATUS_ACTIVE:
1519 // OK
1520 break;
1521 default:
1522 SET_ERR_L("Unexpected status: %d", mStatus);
1523 return INVALID_OPERATION;
1524 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001525
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001526 if (!mRequestTemplateCache[templateId].isEmpty()) {
1527 *request = mRequestTemplateCache[templateId];
1528 return OK;
1529 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001530 }
1531
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001532 camera_metadata_t *rawRequest;
1533 status_t res = mInterface->constructDefaultRequestSettings(
1534 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001535
1536 {
1537 Mutex::Autolock l(mLock);
1538 if (res == BAD_VALUE) {
1539 ALOGI("%s: template %d is not supported on this camera device",
1540 __FUNCTION__, templateId);
1541 return res;
1542 } else if (res != OK) {
1543 CLOGE("Unable to construct request template %d: %s (%d)",
1544 templateId, strerror(-res), res);
1545 return res;
1546 }
1547
1548 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1549 mRequestTemplateCache[templateId].acquire(rawRequest);
1550
1551 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001552 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001553 return OK;
1554}
1555
1556status_t Camera3Device::waitUntilDrained() {
1557 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001559 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001561
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001562 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001563}
1564
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001565status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 switch (mStatus) {
1567 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 ALOGV("%s: Already idle", __FUNCTION__);
1570 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 case STATUS_CONFIGURED:
1572 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 case STATUS_ERROR:
1574 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 break;
1577 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001578 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return INVALID_OPERATION;
1580 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001581 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1582 maxExpectedDuration);
1583 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001584 if (res != OK) {
1585 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1586 res);
1587 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 return res;
1589}
1590
Ruben Brunk183f0562015-08-12 12:55:02 -07001591
1592void Camera3Device::internalUpdateStatusLocked(Status status) {
1593 mStatus = status;
1594 mRecentStatusUpdates.add(mStatus);
1595 mStatusChanged.broadcast();
1596}
1597
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001598// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001599status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 mRequestThread->setPaused(true);
1601 mPauseStateNotify = true;
1602
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001603 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1604 maxExpectedDuration);
1605 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001606 if (res != OK) {
1607 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001608 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 }
1610
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001611 return res;
1612}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001613
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001614// Resume after internalPauseAndWaitLocked
1615status_t Camera3Device::internalResumeLocked() {
1616 status_t res;
1617
1618 mRequestThread->setPaused(false);
1619
1620 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1621 if (res != OK) {
1622 SET_ERR_L("Can't transition to active in %f seconds!",
1623 kActiveTimeout/1e9);
1624 }
1625 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001627}
1628
Ruben Brunk183f0562015-08-12 12:55:02 -07001629status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001631
1632 size_t startIndex = 0;
1633 if (mStatusWaiters == 0) {
1634 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1635 // this status list
1636 mRecentStatusUpdates.clear();
1637 } else {
1638 // If other threads are waiting on updates to this status list, set the position of the
1639 // first element that this list will check rather than clearing the list.
1640 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 }
1642
Ruben Brunk183f0562015-08-12 12:55:02 -07001643 mStatusWaiters++;
1644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 bool stateSeen = false;
1646 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001647 if (active == (mStatus == STATUS_ACTIVE)) {
1648 // Desired state is current
1649 break;
1650 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651
1652 res = mStatusChanged.waitRelative(mLock, timeout);
1653 if (res != OK) break;
1654
Ruben Brunk183f0562015-08-12 12:55:02 -07001655 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1656 // transitions.
1657 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1658 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1659 __FUNCTION__);
1660
1661 // Encountered desired state since we began waiting
1662 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1664 stateSeen = true;
1665 break;
1666 }
1667 }
1668 } while (!stateSeen);
1669
Ruben Brunk183f0562015-08-12 12:55:02 -07001670 mStatusWaiters--;
1671
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 return res;
1673}
1674
1675
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001676status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001679
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001680 if (listener != NULL && mListener != NULL) {
1681 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1682 }
1683 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001684 mRequestThread->setNotificationListener(listener);
1685 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001686
1687 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001688}
1689
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001690bool Camera3Device::willNotify3A() {
1691 return false;
1692}
1693
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001695 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001696 status_t res;
1697 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001699 while (mResultQueue.empty()) {
1700 res = mResultSignal.waitRelative(mOutputLock, timeout);
1701 if (res == TIMED_OUT) {
1702 return res;
1703 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001704 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1705 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001706 return res;
1707 }
1708 }
1709 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710}
1711
Jianing Weicb0652e2014-03-12 18:29:36 -07001712status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001714 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001715
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001716 if (mResultQueue.empty()) {
1717 return NOT_ENOUGH_DATA;
1718 }
1719
Jianing Weicb0652e2014-03-12 18:29:36 -07001720 if (frame == NULL) {
1721 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1722 return BAD_VALUE;
1723 }
1724
1725 CaptureResult &result = *(mResultQueue.begin());
1726 frame->mResultExtras = result.mResultExtras;
1727 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001728 mResultQueue.erase(mResultQueue.begin());
1729
1730 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731}
1732
1733status_t Camera3Device::triggerAutofocus(uint32_t id) {
1734 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001736
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001737 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1738 // Mix-in this trigger into the next request and only the next request.
1739 RequestTrigger trigger[] = {
1740 {
1741 ANDROID_CONTROL_AF_TRIGGER,
1742 ANDROID_CONTROL_AF_TRIGGER_START
1743 },
1744 {
1745 ANDROID_CONTROL_AF_TRIGGER_ID,
1746 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001747 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001748 };
1749
1750 return mRequestThread->queueTrigger(trigger,
1751 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752}
1753
1754status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1755 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001758 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1759 // Mix-in this trigger into the next request and only the next request.
1760 RequestTrigger trigger[] = {
1761 {
1762 ANDROID_CONTROL_AF_TRIGGER,
1763 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1764 },
1765 {
1766 ANDROID_CONTROL_AF_TRIGGER_ID,
1767 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001768 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001769 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001771 return mRequestThread->queueTrigger(trigger,
1772 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001773}
1774
1775status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1776 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001777 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001778
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001779 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1780 // Mix-in this trigger into the next request and only the next request.
1781 RequestTrigger trigger[] = {
1782 {
1783 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1784 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1785 },
1786 {
1787 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1788 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001789 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001790 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001791
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001792 return mRequestThread->queueTrigger(trigger,
1793 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001794}
1795
Jianing Weicb0652e2014-03-12 18:29:36 -07001796status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001797 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001798 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001800
Zhijun He7ef20392014-04-21 16:04:17 -07001801 {
1802 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001803 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001804 }
1805
Emilian Peev08dd2452017-04-06 16:55:14 +01001806 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001807}
1808
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001809status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001810 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1811}
1812
1813status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001814 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001815 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001816 Mutex::Autolock il(mInterfaceLock);
1817 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001818
1819 sp<Camera3StreamInterface> stream;
1820 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1821 if (outputStreamIdx == NAME_NOT_FOUND) {
1822 CLOGE("Stream %d does not exist", streamId);
1823 return BAD_VALUE;
1824 }
1825
1826 stream = mOutputStreams.editValueAt(outputStreamIdx);
1827
1828 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001829 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001830 return BAD_VALUE;
1831 }
1832
1833 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001834 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001835 return BAD_VALUE;
1836 }
1837
Ruben Brunkc78ac262015-08-13 17:58:46 -07001838 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001839}
1840
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001841status_t Camera3Device::tearDown(int streamId) {
1842 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001843 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001844 Mutex::Autolock il(mInterfaceLock);
1845 Mutex::Autolock l(mLock);
1846
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001847 sp<Camera3StreamInterface> stream;
1848 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1849 if (outputStreamIdx == NAME_NOT_FOUND) {
1850 CLOGE("Stream %d does not exist", streamId);
1851 return BAD_VALUE;
1852 }
1853
1854 stream = mOutputStreams.editValueAt(outputStreamIdx);
1855
1856 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1857 CLOGE("Stream %d is a target of a in-progress request", streamId);
1858 return BAD_VALUE;
1859 }
1860
1861 return stream->tearDown();
1862}
1863
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001864status_t Camera3Device::addBufferListenerForStream(int streamId,
1865 wp<Camera3StreamBufferListener> listener) {
1866 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001867 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001868 Mutex::Autolock il(mInterfaceLock);
1869 Mutex::Autolock l(mLock);
1870
1871 sp<Camera3StreamInterface> stream;
1872 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1873 if (outputStreamIdx == NAME_NOT_FOUND) {
1874 CLOGE("Stream %d does not exist", streamId);
1875 return BAD_VALUE;
1876 }
1877
1878 stream = mOutputStreams.editValueAt(outputStreamIdx);
1879 stream->addBufferListener(listener);
1880
1881 return OK;
1882}
1883
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001884/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001885 * Methods called by subclasses
1886 */
1887
1888void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001889 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890 {
1891 // Need mLock to safely update state and synchronize to current
1892 // state of methods in flight.
1893 Mutex::Autolock l(mLock);
1894 // We can get various system-idle notices from the status tracker
1895 // while starting up. Only care about them if we've actually sent
1896 // in some requests recently.
1897 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1898 return;
1899 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001900 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001901 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001902 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903
1904 // Skip notifying listener if we're doing some user-transparent
1905 // state changes
1906 if (mPauseStateNotify) return;
1907 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001908
1909 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001910 {
1911 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001912 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
1914 if (idle && listener != NULL) {
1915 listener->notifyIdle();
1916 }
1917}
1918
Shuzhen Wang758c2152017-01-10 18:26:18 -08001919status_t Camera3Device::setConsumerSurfaces(int streamId,
1920 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001921 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001922 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1923 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001924 Mutex::Autolock il(mInterfaceLock);
1925 Mutex::Autolock l(mLock);
1926
Shuzhen Wang758c2152017-01-10 18:26:18 -08001927 if (consumers.size() == 0) {
1928 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001929 return BAD_VALUE;
1930 }
1931
1932 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1933 if (idx == NAME_NOT_FOUND) {
1934 CLOGE("Stream %d is unknown", streamId);
1935 return idx;
1936 }
1937 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001938 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001939 if (res != OK) {
1940 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1941 return res;
1942 }
1943
Shuzhen Wang0129d522016-10-30 22:43:41 -07001944 if (stream->isConsumerConfigurationDeferred()) {
1945 if (!stream->isConfiguring()) {
1946 CLOGE("Stream %d was already fully configured.", streamId);
1947 return INVALID_OPERATION;
1948 }
Zhijun He5d677d12016-05-29 16:52:39 -07001949
Shuzhen Wang0129d522016-10-30 22:43:41 -07001950 res = stream->finishConfiguration();
1951 if (res != OK) {
1952 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1953 stream->getId(), strerror(-res), res);
1954 return res;
1955 }
Zhijun He5d677d12016-05-29 16:52:39 -07001956 }
1957
1958 return OK;
1959}
1960
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001961/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001962 * Camera3Device private methods
1963 */
1964
1965sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001966 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001967 ATRACE_CALL();
1968 status_t res;
1969
1970 sp<CaptureRequest> newRequest = new CaptureRequest;
1971 newRequest->mSettings = request;
1972
1973 camera_metadata_entry_t inputStreams =
1974 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1975 if (inputStreams.count > 0) {
1976 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001977 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001978 CLOGE("Request references unknown input stream %d",
1979 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980 return NULL;
1981 }
1982 // Lazy completion of stream configuration (allocation/registration)
1983 // on first use
1984 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001985 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001987 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001989 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001990 return NULL;
1991 }
1992 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001993 // Check if stream is being prepared
1994 if (mInputStream->isPreparing()) {
1995 CLOGE("Request references an input stream that's being prepared!");
1996 return NULL;
1997 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998
1999 newRequest->mInputStream = mInputStream;
2000 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2001 }
2002
2003 camera_metadata_entry_t streams =
2004 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2005 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002006 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002007 return NULL;
2008 }
2009
2010 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002011 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002012 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002013 CLOGE("Request references unknown stream %d",
2014 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002015 return NULL;
2016 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002017 sp<Camera3OutputStreamInterface> stream =
2018 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019
Zhijun He5d677d12016-05-29 16:52:39 -07002020 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002021 auto iter = surfaceMap.find(streams.data.i32[i]);
2022 if (iter != surfaceMap.end()) {
2023 const std::vector<size_t>& surfaces = iter->second;
2024 for (const auto& surface : surfaces) {
2025 if (stream->isConsumerConfigurationDeferred(surface)) {
2026 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2027 "due to deferred consumer", stream->getId(), surface);
2028 return NULL;
2029 }
2030 }
2031 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002032 }
2033
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002034 // Lazy completion of stream configuration (allocation/registration)
2035 // on first use
2036 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002037 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002038 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002039 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2040 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041 return NULL;
2042 }
2043 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044 // Check if stream is being prepared
2045 if (stream->isPreparing()) {
2046 CLOGE("Request references an output stream that's being prepared!");
2047 return NULL;
2048 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049
2050 newRequest->mOutputStreams.push(stream);
2051 }
2052 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002053 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002054
2055 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002056}
2057
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002058bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2059 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2060 Size size = mSupportedOpaqueInputSizes[i];
2061 if (size.width == width && size.height == height) {
2062 return true;
2063 }
2064 }
2065
2066 return false;
2067}
2068
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002069void Camera3Device::cancelStreamsConfigurationLocked() {
2070 int res = OK;
2071 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2072 res = mInputStream->cancelConfiguration();
2073 if (res != OK) {
2074 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2075 mInputStream->getId(), strerror(-res), res);
2076 }
2077 }
2078
2079 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2080 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2081 if (outputStream->isConfiguring()) {
2082 res = outputStream->cancelConfiguration();
2083 if (res != OK) {
2084 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2085 outputStream->getId(), strerror(-res), res);
2086 }
2087 }
2088 }
2089
2090 // Return state to that at start of call, so that future configures
2091 // properly clean things up
2092 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2093 mNeedConfig = true;
2094}
2095
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002096status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097 ATRACE_CALL();
2098 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002099
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002100 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002101 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 return INVALID_OPERATION;
2103 }
2104
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002105 if (operatingMode < 0) {
2106 CLOGE("Invalid operating mode: %d", operatingMode);
2107 return BAD_VALUE;
2108 }
2109
2110 bool isConstrainedHighSpeed =
2111 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2112 operatingMode;
2113
2114 if (mOperatingMode != operatingMode) {
2115 mNeedConfig = true;
2116 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2117 mOperatingMode = operatingMode;
2118 }
2119
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002120 if (!mNeedConfig) {
2121 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2122 return OK;
2123 }
2124
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002125 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2126 // adding a dummy stream instead.
2127 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2128 if (mOutputStreams.size() == 0) {
2129 addDummyStreamLocked();
2130 } else {
2131 tryRemoveDummyStreamLocked();
2132 }
2133
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002134 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002135 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136
2137 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002138 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2140
2141 Vector<camera3_stream_t*> streams;
2142 streams.setCapacity(config.num_streams);
2143
2144 if (mInputStream != NULL) {
2145 camera3_stream_t *inputStream;
2146 inputStream = mInputStream->startConfiguration();
2147 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002148 CLOGE("Can't start input stream configuration");
2149 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 return INVALID_OPERATION;
2151 }
2152 streams.add(inputStream);
2153 }
2154
2155 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002156
2157 // Don't configure bidi streams twice, nor add them twice to the list
2158 if (mOutputStreams[i].get() ==
2159 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2160
2161 config.num_streams--;
2162 continue;
2163 }
2164
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 camera3_stream_t *outputStream;
2166 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2167 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002168 CLOGE("Can't start output stream configuration");
2169 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170 return INVALID_OPERATION;
2171 }
2172 streams.add(outputStream);
2173 }
2174
2175 config.streams = streams.editArray();
2176
2177 // Do the HAL configuration; will potentially touch stream
2178 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002179
2180 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002182 if (res == BAD_VALUE) {
2183 // HAL rejected this set of streams as unsupported, clean up config
2184 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002185 CLOGE("Set of requested inputs/outputs not supported by HAL");
2186 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002187 return BAD_VALUE;
2188 } else if (res != OK) {
2189 // Some other kind of error from configure_streams - this is not
2190 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002191 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2192 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 return res;
2194 }
2195
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002196 // Finish all stream configuration immediately.
2197 // TODO: Try to relax this later back to lazy completion, which should be
2198 // faster
2199
Igor Murashkin073f8572013-05-02 14:59:28 -07002200 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002201 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002202 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002203 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002204 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002205 cancelStreamsConfigurationLocked();
2206 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002207 }
2208 }
2209
2210 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002211 sp<Camera3OutputStreamInterface> outputStream =
2212 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002213 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002214 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002215 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002216 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002217 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002218 cancelStreamsConfigurationLocked();
2219 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002220 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002221 }
2222 }
2223
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224 // Request thread needs to know to avoid using repeat-last-settings protocol
2225 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002226 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002227
Zhijun He90f7c372016-08-16 16:19:43 -07002228 char value[PROPERTY_VALUE_MAX];
2229 property_get("camera.fifo.disable", value, "0");
2230 int32_t disableFifo = atoi(value);
2231 if (disableFifo != 1) {
2232 // Boost priority of request thread to SCHED_FIFO.
2233 pid_t requestThreadTid = mRequestThread->getTid();
2234 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002235 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002236 if (res != OK) {
2237 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2238 strerror(-res), res);
2239 } else {
2240 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2241 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002242 }
2243
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002244 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002246 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247
Ruben Brunk183f0562015-08-12 12:55:02 -07002248 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2249 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002250
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002251 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002252
Zhijun He0a210512014-07-24 13:45:15 -07002253 // tear down the deleted streams after configure streams.
2254 mDeletedStreams.clear();
2255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002256 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002257}
2258
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002259status_t Camera3Device::addDummyStreamLocked() {
2260 ATRACE_CALL();
2261 status_t res;
2262
2263 if (mDummyStreamId != NO_STREAM) {
2264 // Should never be adding a second dummy stream when one is already
2265 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002266 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2267 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002268 return INVALID_OPERATION;
2269 }
2270
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002271 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002272
2273 sp<Camera3OutputStreamInterface> dummyStream =
2274 new Camera3DummyStream(mNextStreamId);
2275
2276 res = mOutputStreams.add(mNextStreamId, dummyStream);
2277 if (res < 0) {
2278 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2279 return res;
2280 }
2281
2282 mDummyStreamId = mNextStreamId;
2283 mNextStreamId++;
2284
2285 return OK;
2286}
2287
2288status_t Camera3Device::tryRemoveDummyStreamLocked() {
2289 ATRACE_CALL();
2290 status_t res;
2291
2292 if (mDummyStreamId == NO_STREAM) return OK;
2293 if (mOutputStreams.size() == 1) return OK;
2294
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002295 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002296
2297 // Ok, have a dummy stream and there's at least one other output stream,
2298 // so remove the dummy
2299
2300 sp<Camera3StreamInterface> deletedStream;
2301 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2302 if (outputStreamIdx == NAME_NOT_FOUND) {
2303 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2304 return INVALID_OPERATION;
2305 }
2306
2307 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2308 mOutputStreams.removeItemsAt(outputStreamIdx);
2309
2310 // Free up the stream endpoint so that it can be used by some other stream
2311 res = deletedStream->disconnect();
2312 if (res != OK) {
2313 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2314 // fall through since we want to still list the stream as deleted.
2315 }
2316 mDeletedStreams.add(deletedStream);
2317 mDummyStreamId = NO_STREAM;
2318
2319 return res;
2320}
2321
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002322void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002323 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002324 Mutex::Autolock l(mLock);
2325 va_list args;
2326 va_start(args, fmt);
2327
2328 setErrorStateLockedV(fmt, args);
2329
2330 va_end(args);
2331}
2332
2333void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002334 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002335 Mutex::Autolock l(mLock);
2336 setErrorStateLockedV(fmt, args);
2337}
2338
2339void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2340 va_list args;
2341 va_start(args, fmt);
2342
2343 setErrorStateLockedV(fmt, args);
2344
2345 va_end(args);
2346}
2347
2348void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002349 // Print out all error messages to log
2350 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002351 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002352
2353 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002354 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002355
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002356 mErrorCause = errorCause;
2357
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002358 if (mRequestThread != nullptr) {
2359 mRequestThread->setPaused(true);
2360 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002361 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002362
2363 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002364 sp<NotificationListener> listener = mListener.promote();
2365 if (listener != NULL) {
2366 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002367 CaptureResultExtras());
2368 }
2369
2370 // Save stack trace. View by dumping it later.
2371 CameraTraces::saveTrace();
2372 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002373}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374
2375/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002376 * In-flight request management
2377 */
2378
Jianing Weicb0652e2014-03-12 18:29:36 -07002379status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002380 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002381 bool hasAppCallback, nsecs_t maxExpectedDuration) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002382 ATRACE_CALL();
2383 Mutex::Autolock l(mInFlightLock);
2384
2385 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002386 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002387 hasAppCallback, maxExpectedDuration));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002388 if (res < 0) return res;
2389
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002390 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002391 // hold mLock to prevent race with disconnect
2392 Mutex::Autolock l(mLock);
2393 if (mStatusTracker != nullptr) {
2394 mStatusTracker->markComponentActive(mInFlightStatusId);
2395 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002396 }
2397
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002398 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002399 return OK;
2400}
2401
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002402void Camera3Device::returnOutputBuffers(
2403 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2404 nsecs_t timestamp) {
2405 for (size_t i = 0; i < numBuffers; i++)
2406 {
2407 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2408 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2409 // Note: stream may be deallocated at this point, if this buffer was
2410 // the last reference to it.
2411 if (res != OK) {
2412 ALOGE("Can't return buffer to its stream: %s (%d)",
2413 strerror(-res), res);
2414 }
2415 }
2416}
2417
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002418void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002419 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002420 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002421 mInFlightMap.removeItemsAt(idx, 1);
2422
2423 // Indicate idle inFlightMap to the status tracker
2424 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002425 // hold mLock to prevent race with disconnect
2426 Mutex::Autolock l(mLock);
2427 if (mStatusTracker != nullptr) {
2428 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2429 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002430 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002431 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002432}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002433
2434void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2435
2436 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2437 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2438
2439 nsecs_t sensorTimestamp = request.sensorTimestamp;
2440 nsecs_t shutterTimestamp = request.shutterTimestamp;
2441
Emilian Peevc6747862017-06-12 15:57:26 +01002442 bool skipResultMetadata = false;
2443 if (request.requestStatus != OK) {
2444 switch (request.requestStatus) {
2445 case CAMERA3_MSG_ERROR_DEVICE:
2446 case CAMERA3_MSG_ERROR_REQUEST:
2447 case CAMERA3_MSG_ERROR_RESULT:
2448 skipResultMetadata = true;
2449 break;
2450 case CAMERA3_MSG_ERROR_BUFFER:
2451 //Result metadata should return in this case.
2452 skipResultMetadata = false;
2453 break;
2454 default:
2455 SET_ERR("Unknown error message: %d", request.requestStatus);
2456 skipResultMetadata = false;
2457 break;
2458 }
2459 }
2460
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002461 // Check if it's okay to remove the request from InFlightMap:
2462 // In the case of a successful request:
2463 // all input and output buffers, all result metadata, shutter callback
2464 // arrived.
2465 // In the case of a unsuccessful request:
2466 // all input and output buffers arrived.
2467 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002468 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002469 (request.haveResultMetadata && shutterTimestamp != 0))) {
2470 ATRACE_ASYNC_END("frame capture", frameNumber);
2471
Shuzhen Wang403044a2017-02-26 23:29:04 -08002472 // Sanity check - if sensor timestamp matches shutter timestamp in the
2473 // case of request having callback.
2474 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002475 sensorTimestamp != shutterTimestamp) {
2476 SET_ERR("sensor timestamp (%" PRId64
2477 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2478 sensorTimestamp, frameNumber, shutterTimestamp);
2479 }
2480
2481 // for an unsuccessful request, it may have pending output buffers to
2482 // return.
2483 assert(request.requestStatus != OK ||
2484 request.pendingOutputBuffers.size() == 0);
2485 returnOutputBuffers(request.pendingOutputBuffers.array(),
2486 request.pendingOutputBuffers.size(), 0);
2487
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002488 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002489 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2490 }
2491
2492 // Sanity check - if we have too many in-flight frames, something has
2493 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002494 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002495 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002496 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2497 kInFlightWarnLimitHighSpeed) {
2498 CLOGE("In-flight list too large for high speed configuration: %zu",
2499 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002500 }
2501}
2502
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002503void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002504 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002505 { // First return buffers cached in mInFlightMap
2506 Mutex::Autolock l(mInFlightLock);
2507 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2508 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2509 returnOutputBuffers(request.pendingOutputBuffers.array(),
2510 request.pendingOutputBuffers.size(), 0);
2511 }
2512 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002513 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002514 }
2515
2516 // Then return all inflight buffers not returned by HAL
2517 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2518 mInterface->getInflightBufferKeys(&inflightKeys);
2519
2520 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2521 for (auto& pair : inflightKeys) {
2522 int32_t frameNumber = pair.first;
2523 int32_t streamId = pair.second;
2524 buffer_handle_t* buffer;
2525 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2526 if (res != OK) {
2527 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2528 __FUNCTION__, frameNumber, streamId);
2529 continue;
2530 }
2531
2532 camera3_stream_buffer_t streamBuffer;
2533 streamBuffer.buffer = buffer;
2534 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2535 streamBuffer.acquire_fence = -1;
2536 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002537
2538 // First check if the buffer belongs to deleted stream
2539 bool streamDeleted = false;
2540 for (auto& stream : mDeletedStreams) {
2541 if (streamId == stream->getId()) {
2542 streamDeleted = true;
2543 // Return buffer to deleted stream
2544 camera3_stream* halStream = stream->asHalStream();
2545 streamBuffer.stream = halStream;
2546 switch (halStream->stream_type) {
2547 case CAMERA3_STREAM_OUTPUT:
2548 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2549 if (res != OK) {
2550 ALOGE("%s: Can't return output buffer for frame %d to"
2551 " stream %d: %s (%d)", __FUNCTION__,
2552 frameNumber, streamId, strerror(-res), res);
2553 }
2554 break;
2555 case CAMERA3_STREAM_INPUT:
2556 res = stream->returnInputBuffer(streamBuffer);
2557 if (res != OK) {
2558 ALOGE("%s: Can't return input buffer for frame %d to"
2559 " stream %d: %s (%d)", __FUNCTION__,
2560 frameNumber, streamId, strerror(-res), res);
2561 }
2562 break;
2563 default: // Bi-direcitonal stream is deprecated
2564 ALOGE("%s: stream %d has unknown stream type %d",
2565 __FUNCTION__, streamId, halStream->stream_type);
2566 break;
2567 }
2568 break;
2569 }
2570 }
2571 if (streamDeleted) {
2572 continue;
2573 }
2574
2575 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002576 if (streamId == inputStreamId) {
2577 streamBuffer.stream = mInputStream->asHalStream();
2578 res = mInputStream->returnInputBuffer(streamBuffer);
2579 if (res != OK) {
2580 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002581 " stream %d: %s (%d)", __FUNCTION__,
2582 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002583 }
2584 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002585 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2586 if (idx == NAME_NOT_FOUND) {
2587 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2588 continue;
2589 }
2590 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002591 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2592 }
2593 }
2594}
2595
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002596void Camera3Device::insertResultLocked(CaptureResult *result,
2597 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002598 if (result == nullptr) return;
2599
Emilian Peev71c73a22017-03-21 16:35:51 +00002600 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2601 result->mMetadata.getAndLock());
2602 set_camera_metadata_vendor_id(meta, mVendorTagId);
2603 result->mMetadata.unlock(meta);
2604
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002605 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2606 (int32_t*)&frameNumber, 1) != OK) {
2607 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2608 return;
2609 }
2610
2611 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2612 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2613 return;
2614 }
2615
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002616 // Valid result, insert into queue
2617 List<CaptureResult>::iterator queuedResult =
2618 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2619 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2620 ", burstId = %" PRId32, __FUNCTION__,
2621 queuedResult->mResultExtras.requestId,
2622 queuedResult->mResultExtras.frameNumber,
2623 queuedResult->mResultExtras.burstId);
2624
2625 mResultSignal.signal();
2626}
2627
2628
2629void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002630 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002631 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002632 Mutex::Autolock l(mOutputLock);
2633
2634 CaptureResult captureResult;
2635 captureResult.mResultExtras = resultExtras;
2636 captureResult.mMetadata = partialResult;
2637
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002638 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002639}
2640
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002641
2642void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2643 CaptureResultExtras &resultExtras,
2644 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002645 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002646 bool reprocess) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002647 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002648 if (pendingMetadata.isEmpty())
2649 return;
2650
2651 Mutex::Autolock l(mOutputLock);
2652
2653 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002654 if (reprocess) {
2655 if (frameNumber < mNextReprocessResultFrameNumber) {
2656 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002657 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002658 frameNumber, mNextReprocessResultFrameNumber);
2659 return;
2660 }
2661 mNextReprocessResultFrameNumber = frameNumber + 1;
2662 } else {
2663 if (frameNumber < mNextResultFrameNumber) {
2664 SET_ERR("Out-of-order capture result metadata submitted! "
2665 "(got frame number %d, expecting %d)",
2666 frameNumber, mNextResultFrameNumber);
2667 return;
2668 }
2669 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002670 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002671
2672 CaptureResult captureResult;
2673 captureResult.mResultExtras = resultExtras;
2674 captureResult.mMetadata = pendingMetadata;
2675
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002676 // Append any previous partials to form a complete result
2677 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2678 captureResult.mMetadata.append(collectedPartialResult);
2679 }
2680
2681 captureResult.mMetadata.sort();
2682
2683 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002684 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2685 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002686 SET_ERR("No timestamp provided by HAL for frame %d!",
2687 frameNumber);
2688 return;
2689 }
2690
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002691 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2692 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2693
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002694 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002695}
2696
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002697/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 * Camera HAL device callback methods
2699 */
2700
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002701void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002702 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002703
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002704 status_t res;
2705
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002706 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002707 if (result->result == NULL && result->num_output_buffers == 0 &&
2708 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002709 SET_ERR("No result data provided by HAL for frame %d",
2710 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002711 return;
2712 }
Zhijun He204e3292014-07-14 17:09:23 -07002713
Zhijun He204e3292014-07-14 17:09:23 -07002714 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002715 result->result != NULL &&
2716 result->partial_result != 1) {
2717 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2718 " if partial result is not supported",
2719 frameNumber, result->partial_result);
2720 return;
2721 }
2722
2723 bool isPartialResult = false;
2724 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002725 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002726 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002727
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002728 // Get shutter timestamp and resultExtras from list of in-flight requests,
2729 // where it was added by the shutter notification for this frame. If the
2730 // shutter timestamp isn't received yet, append the output buffers to the
2731 // in-flight request and they will be returned when the shutter timestamp
2732 // arrives. Update the in-flight status and remove the in-flight entry if
2733 // all result data and shutter timestamp have been received.
2734 nsecs_t shutterTimestamp = 0;
2735
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002736 {
2737 Mutex::Autolock l(mInFlightLock);
2738 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2739 if (idx == NAME_NOT_FOUND) {
2740 SET_ERR("Unknown frame number for capture result: %d",
2741 frameNumber);
2742 return;
2743 }
2744 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002745 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2746 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002747 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002748 __FUNCTION__, request.resultExtras.requestId,
2749 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002750 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002751 // Always update the partial count to the latest one if it's not 0
2752 // (buffers only). When framework aggregates adjacent partial results
2753 // into one, the latest partial count will be used.
2754 if (result->partial_result != 0)
2755 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002756
2757 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002758 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002759 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2760 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2761 " the range of [1, %d] when metadata is included in the result",
2762 frameNumber, result->partial_result, mNumPartialResults);
2763 return;
2764 }
2765 isPartialResult = (result->partial_result < mNumPartialResults);
2766 if (isPartialResult) {
2767 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002768 }
2769
Shuzhen Wang4a472662017-02-26 23:29:04 -08002770 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002771 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002772 sendPartialCaptureResult(result->result, request.resultExtras,
2773 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002774 }
2775 }
2776
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002777 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002778 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002779
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002780 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002781 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002782 if (request.haveResultMetadata) {
2783 SET_ERR("Called multiple times with metadata for frame %d",
2784 frameNumber);
2785 return;
2786 }
Zhijun He204e3292014-07-14 17:09:23 -07002787 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002788 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002789 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002790 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002791 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002792 request.haveResultMetadata = true;
2793 }
2794
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002795 uint32_t numBuffersReturned = result->num_output_buffers;
2796 if (result->input_buffer != NULL) {
2797 if (hasInputBufferInRequest) {
2798 numBuffersReturned += 1;
2799 } else {
2800 ALOGW("%s: Input buffer should be NULL if there is no input"
2801 " buffer sent in the request",
2802 __FUNCTION__);
2803 }
2804 }
2805 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002806 if (request.numBuffersLeft < 0) {
2807 SET_ERR("Too many buffers returned for frame %d",
2808 frameNumber);
2809 return;
2810 }
2811
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002812 camera_metadata_ro_entry_t entry;
2813 res = find_camera_metadata_ro_entry(result->result,
2814 ANDROID_SENSOR_TIMESTAMP, &entry);
2815 if (res == OK && entry.count == 1) {
2816 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002817 }
2818
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002819 // If shutter event isn't received yet, append the output buffers to
2820 // the in-flight request. Otherwise, return the output buffers to
2821 // streams.
2822 if (shutterTimestamp == 0) {
2823 request.pendingOutputBuffers.appendArray(result->output_buffers,
2824 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002825 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002826 returnOutputBuffers(result->output_buffers,
2827 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002828 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002829
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002830 if (result->result != NULL && !isPartialResult) {
2831 if (shutterTimestamp == 0) {
2832 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002833 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002834 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002835 CameraMetadata metadata;
2836 metadata = result->result;
2837 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002838 collectedPartialResult, frameNumber,
2839 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002840 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002841 }
2842
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002843 removeInFlightRequestIfReadyLocked(idx);
2844 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002845
Zhijun Hef0d962a2014-06-30 10:24:11 -07002846 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002847 if (hasInputBufferInRequest) {
2848 Camera3Stream *stream =
2849 Camera3Stream::cast(result->input_buffer->stream);
2850 res = stream->returnInputBuffer(*(result->input_buffer));
2851 // Note: stream may be deallocated at this point, if this buffer was the
2852 // last reference to it.
2853 if (res != OK) {
2854 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2855 " its stream:%s (%d)", __FUNCTION__,
2856 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002857 }
2858 } else {
2859 ALOGW("%s: Input buffer should be NULL if there is no input"
2860 " buffer sent in the request, skipping input buffer return.",
2861 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002862 }
2863 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002864}
2865
2866void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002867 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002868 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002869 {
2870 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002871 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002872 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002873
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002874 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002875 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002876 return;
2877 }
2878
2879 switch (msg->type) {
2880 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002881 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002882 break;
2883 }
2884 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002886 break;
2887 }
2888 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002889 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002890 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002891 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002892}
2893
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002894void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002895 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002896 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002897 // Map camera HAL error codes to ICameraDeviceCallback error codes
2898 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002899 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002900 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002902 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002903 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002904 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002905 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002906 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002907 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002908 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002909 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002910 };
2911
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002912 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002913 ((msg.error_code >= 0) &&
2914 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2915 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002916 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002917
2918 int streamId = 0;
2919 if (msg.error_stream != NULL) {
2920 Camera3Stream *stream =
2921 Camera3Stream::cast(msg.error_stream);
2922 streamId = stream->getId();
2923 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002924 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2925 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002926 streamId, msg.error_code);
2927
2928 CaptureResultExtras resultExtras;
2929 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002930 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931 // SET_ERR calls notifyError
2932 SET_ERR("Camera HAL reported serious device error");
2933 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002934 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2935 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2936 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002937 {
2938 Mutex::Autolock l(mInFlightLock);
2939 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2940 if (idx >= 0) {
2941 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2942 r.requestStatus = msg.error_code;
2943 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002944 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2945 errorCode) {
2946 // In case of missing result check whether the buffers
2947 // returned. If they returned, then remove inflight
2948 // request.
2949 removeInFlightRequestIfReadyLocked(idx);
2950 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002951 } else {
2952 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953 ALOGE("Camera %s: %s: cannot find in-flight request on "
2954 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002955 resultExtras.frameNumber);
2956 }
2957 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002958 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959 if (listener != NULL) {
2960 listener->notifyError(errorCode, resultExtras);
2961 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002962 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002963 }
2964 break;
2965 default:
2966 // SET_ERR calls notifyError
2967 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2968 break;
2969 }
2970}
2971
2972void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002973 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002974 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002975 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002976
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002977 // Set timestamp for the request in the in-flight tracking
2978 // and get the request ID to send upstream
2979 {
2980 Mutex::Autolock l(mInFlightLock);
2981 idx = mInFlightMap.indexOfKey(msg.frame_number);
2982 if (idx >= 0) {
2983 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002984
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002985 // Verify ordering of shutter notifications
2986 {
2987 Mutex::Autolock l(mOutputLock);
2988 // TODO: need to track errors for tighter bounds on expected frame number.
2989 if (r.hasInputBuffer) {
2990 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2991 SET_ERR("Shutter notification out-of-order. Expected "
2992 "notification for frame %d, got frame %d",
2993 mNextReprocessShutterFrameNumber, msg.frame_number);
2994 return;
2995 }
2996 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2997 } else {
2998 if (msg.frame_number < mNextShutterFrameNumber) {
2999 SET_ERR("Shutter notification out-of-order. Expected "
3000 "notification for frame %d, got frame %d",
3001 mNextShutterFrameNumber, msg.frame_number);
3002 return;
3003 }
3004 mNextShutterFrameNumber = msg.frame_number + 1;
3005 }
3006 }
3007
Shuzhen Wang4a472662017-02-26 23:29:04 -08003008 r.shutterTimestamp = msg.timestamp;
3009 if (r.hasCallback) {
3010 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003011 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003013 // Call listener, if any
3014 if (listener != NULL) {
3015 listener->notifyShutter(r.resultExtras, msg.timestamp);
3016 }
3017 // send pending result and buffers
3018 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3019 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003020 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003021 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003022 returnOutputBuffers(r.pendingOutputBuffers.array(),
3023 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3024 r.pendingOutputBuffers.clear();
3025
3026 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003027 }
3028 }
3029 if (idx < 0) {
3030 SET_ERR("Shutter notification for non-existent frame number %d",
3031 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003032 }
3033}
3034
3035
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003036CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003037 ALOGV("%s", __FUNCTION__);
3038
Igor Murashkin1e479c02013-09-06 16:55:14 -07003039 CameraMetadata retVal;
3040
3041 if (mRequestThread != NULL) {
3042 retVal = mRequestThread->getLatestRequest();
3043 }
3044
Igor Murashkin1e479c02013-09-06 16:55:14 -07003045 return retVal;
3046}
3047
Jianing Weicb0652e2014-03-12 18:29:36 -07003048
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003049void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3050 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3051 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3052}
3053
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003054/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003055 * HalInterface inner class methods
3056 */
3057
Yifan Hongf79b5542017-04-11 14:44:25 -07003058Camera3Device::HalInterface::HalInterface(
3059 sp<ICameraDeviceSession> &session,
3060 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003061 mHidlSession(session),
3062 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003063
Emilian Peev31abd0a2017-05-11 18:37:46 +01003064Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003065
3066Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003067 mHidlSession(other.mHidlSession),
3068 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003069
3070bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003071 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003072}
3073
3074void Camera3Device::HalInterface::clear() {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003075 mHidlSession.clear();
3076}
3077
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003078bool Camera3Device::HalInterface::supportBatchRequest() {
3079 return mHidlSession != nullptr;
3080}
3081
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003082status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3083 camera3_request_template_t templateId,
3084 /*out*/ camera_metadata_t **requestTemplate) {
3085 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3086 if (!valid()) return INVALID_OPERATION;
3087 status_t res = OK;
3088
Emilian Peev31abd0a2017-05-11 18:37:46 +01003089 common::V1_0::Status status;
3090 RequestTemplate id;
3091 switch (templateId) {
3092 case CAMERA3_TEMPLATE_PREVIEW:
3093 id = RequestTemplate::PREVIEW;
3094 break;
3095 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3096 id = RequestTemplate::STILL_CAPTURE;
3097 break;
3098 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3099 id = RequestTemplate::VIDEO_RECORD;
3100 break;
3101 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3102 id = RequestTemplate::VIDEO_SNAPSHOT;
3103 break;
3104 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3105 id = RequestTemplate::ZERO_SHUTTER_LAG;
3106 break;
3107 case CAMERA3_TEMPLATE_MANUAL:
3108 id = RequestTemplate::MANUAL;
3109 break;
3110 default:
3111 // Unknown template ID
3112 return BAD_VALUE;
3113 }
3114 auto err = mHidlSession->constructDefaultRequestSettings(id,
3115 [&status, &requestTemplate]
3116 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3117 status = s;
3118 if (status == common::V1_0::Status::OK) {
3119 const camera_metadata *r =
3120 reinterpret_cast<const camera_metadata_t*>(request.data());
3121 size_t expectedSize = request.size();
3122 int ret = validate_camera_metadata_structure(r, &expectedSize);
3123 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3124 *requestTemplate = clone_camera_metadata(r);
3125 if (*requestTemplate == nullptr) {
3126 ALOGE("%s: Unable to clone camera metadata received from HAL",
3127 __FUNCTION__);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128 status = common::V1_0::Status::INTERNAL_ERROR;
3129 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003130 } else {
3131 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3132 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003134 }
3135 });
3136 if (!err.isOk()) {
3137 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3138 res = DEAD_OBJECT;
3139 } else {
3140 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003141 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003142
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 return res;
3144}
3145
3146status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3147 ATRACE_NAME("CameraHal::configureStreams");
3148 if (!valid()) return INVALID_OPERATION;
3149 status_t res = OK;
3150
Emilian Peev31abd0a2017-05-11 18:37:46 +01003151 // Convert stream config to HIDL
3152 std::set<int> activeStreams;
3153 StreamConfiguration requestedConfiguration;
3154 requestedConfiguration.streams.resize(config->num_streams);
3155 for (size_t i = 0; i < config->num_streams; i++) {
3156 Stream &dst = requestedConfiguration.streams[i];
3157 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003158
Emilian Peev31abd0a2017-05-11 18:37:46 +01003159 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3160 cam3stream->setBufferFreedListener(this);
3161 int streamId = cam3stream->getId();
3162 StreamType streamType;
3163 switch (src->stream_type) {
3164 case CAMERA3_STREAM_OUTPUT:
3165 streamType = StreamType::OUTPUT;
3166 break;
3167 case CAMERA3_STREAM_INPUT:
3168 streamType = StreamType::INPUT;
3169 break;
3170 default:
3171 ALOGE("%s: Stream %d: Unsupported stream type %d",
3172 __FUNCTION__, streamId, config->streams[i]->stream_type);
3173 return BAD_VALUE;
3174 }
3175 dst.id = streamId;
3176 dst.streamType = streamType;
3177 dst.width = src->width;
3178 dst.height = src->height;
3179 dst.format = mapToPixelFormat(src->format);
Emilian Peev050f5dc2017-05-18 14:43:56 +01003180 dst.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peev31abd0a2017-05-11 18:37:46 +01003181 dst.dataSpace = mapToHidlDataspace(src->data_space);
3182 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3183
3184 activeStreams.insert(streamId);
3185 // Create Buffer ID map if necessary
3186 if (mBufferIdMaps.count(streamId) == 0) {
3187 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3188 }
3189 }
3190 // remove BufferIdMap for deleted streams
3191 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3192 int streamId = it->first;
3193 bool active = activeStreams.count(streamId) > 0;
3194 if (!active) {
3195 it = mBufferIdMaps.erase(it);
3196 } else {
3197 ++it;
3198 }
3199 }
3200
3201 res = mapToStreamConfigurationMode(
3202 (camera3_stream_configuration_mode_t) config->operation_mode,
3203 /*out*/ &requestedConfiguration.operationMode);
3204 if (res != OK) {
3205 return res;
3206 }
3207
3208 // Invoke configureStreams
3209
3210 HalStreamConfiguration finalConfiguration;
3211 common::V1_0::Status status;
3212 auto err = mHidlSession->configureStreams(requestedConfiguration,
3213 [&status, &finalConfiguration]
3214 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3215 finalConfiguration = halConfiguration;
3216 status = s;
3217 });
3218 if (!err.isOk()) {
3219 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3220 return DEAD_OBJECT;
3221 }
3222
3223 if (status != common::V1_0::Status::OK ) {
3224 return CameraProviderManager::mapToStatusT(status);
3225 }
3226
3227 // And convert output stream configuration from HIDL
3228
3229 for (size_t i = 0; i < config->num_streams; i++) {
3230 camera3_stream_t *dst = config->streams[i];
3231 int streamId = Camera3Stream::cast(dst)->getId();
3232
3233 // Start scan at i, with the assumption that the stream order matches
3234 size_t realIdx = i;
3235 bool found = false;
3236 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3237 if (finalConfiguration.streams[realIdx].id == streamId) {
3238 found = true;
3239 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003240 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003241 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3242 }
3243 if (!found) {
3244 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3245 __FUNCTION__, streamId);
3246 return INVALID_OPERATION;
3247 }
3248 HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003249
Emilian Peev31abd0a2017-05-11 18:37:46 +01003250 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3251 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3252 if (dst->format != overrideFormat) {
3253 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3254 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003255 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003256 } else {
3257 // Override allowed with IMPLEMENTATION_DEFINED
3258 dst->format = overrideFormat;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003259 }
3260
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3262 if (src.producerUsage != 0) {
3263 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003264 __FUNCTION__, streamId);
3265 return INVALID_OPERATION;
3266 }
Emilian Peev050f5dc2017-05-18 14:43:56 +01003267 Camera3Stream::cast(dst)->setUsage(
3268 mapConsumerToFrameworkUsage(src.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003269 } else {
3270 // OUTPUT
3271 if (src.consumerUsage != 0) {
3272 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3273 __FUNCTION__, streamId);
3274 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003275 }
Emilian Peev050f5dc2017-05-18 14:43:56 +01003276 Camera3Stream::cast(dst)->setUsage(
3277 mapProducerToFrameworkUsage(src.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003278 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003279 dst->max_buffers = src.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003280 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003281
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003282 return res;
3283}
3284
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003285void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3286 /*out*/device::V3_2::CaptureRequest* captureRequest,
3287 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003288 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003289 if (captureRequest == nullptr || handlesCreated == nullptr) {
3290 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3291 __FUNCTION__, captureRequest, handlesCreated);
3292 return;
3293 }
3294
3295 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003296
3297 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003298
3299 {
3300 std::lock_guard<std::mutex> lock(mInflightLock);
3301 if (request->input_buffer != nullptr) {
3302 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3303 buffer_handle_t buf = *(request->input_buffer->buffer);
3304 auto pair = getBufferId(buf, streamId);
3305 bool isNewBuffer = pair.first;
3306 uint64_t bufferId = pair.second;
3307 captureRequest->inputBuffer.streamId = streamId;
3308 captureRequest->inputBuffer.bufferId = bufferId;
3309 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3310 captureRequest->inputBuffer.status = BufferStatus::OK;
3311 native_handle_t *acquireFence = nullptr;
3312 if (request->input_buffer->acquire_fence != -1) {
3313 acquireFence = native_handle_create(1,0);
3314 acquireFence->data[0] = request->input_buffer->acquire_fence;
3315 handlesCreated->push_back(acquireFence);
3316 }
3317 captureRequest->inputBuffer.acquireFence = acquireFence;
3318 captureRequest->inputBuffer.releaseFence = nullptr;
3319
3320 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3321 request->input_buffer->buffer,
3322 request->input_buffer->acquire_fence);
3323 } else {
3324 captureRequest->inputBuffer.streamId = -1;
3325 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3326 }
3327
3328 captureRequest->outputBuffers.resize(request->num_output_buffers);
3329 for (size_t i = 0; i < request->num_output_buffers; i++) {
3330 const camera3_stream_buffer_t *src = request->output_buffers + i;
3331 StreamBuffer &dst = captureRequest->outputBuffers[i];
3332 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3333 buffer_handle_t buf = *(src->buffer);
3334 auto pair = getBufferId(buf, streamId);
3335 bool isNewBuffer = pair.first;
3336 dst.streamId = streamId;
3337 dst.bufferId = pair.second;
3338 dst.buffer = isNewBuffer ? buf : nullptr;
3339 dst.status = BufferStatus::OK;
3340 native_handle_t *acquireFence = nullptr;
3341 if (src->acquire_fence != -1) {
3342 acquireFence = native_handle_create(1,0);
3343 acquireFence->data[0] = src->acquire_fence;
3344 handlesCreated->push_back(acquireFence);
3345 }
3346 dst.acquireFence = acquireFence;
3347 dst.releaseFence = nullptr;
3348
3349 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3350 src->buffer, src->acquire_fence);
3351 }
3352 }
3353}
3354
3355status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3356 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3357 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3358 if (!valid()) return INVALID_OPERATION;
3359
3360 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3361 size_t batchSize = requests.size();
3362 captureRequests.resize(batchSize);
3363 std::vector<native_handle_t*> handlesCreated;
3364
3365 for (size_t i = 0; i < batchSize; i++) {
3366 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3367 }
3368
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003369 std::vector<device::V3_2::BufferCache> cachesToRemove;
3370 {
3371 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3372 for (auto& pair : mFreedBuffers) {
3373 // The stream might have been removed since onBufferFreed
3374 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3375 cachesToRemove.push_back({pair.first, pair.second});
3376 }
3377 }
3378 mFreedBuffers.clear();
3379 }
3380
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003381 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3382 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003383
3384 // Write metadata to FMQ.
3385 for (size_t i = 0; i < batchSize; i++) {
3386 camera3_capture_request_t* request = requests[i];
3387 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3388
3389 if (request->settings != nullptr) {
3390 size_t settingsSize = get_camera_metadata_size(request->settings);
3391 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3392 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3393 captureRequest->settings.resize(0);
3394 captureRequest->fmqSettingsSize = settingsSize;
3395 } else {
3396 if (mRequestMetadataQueue != nullptr) {
3397 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3398 }
3399 captureRequest->settings.setToExternal(
3400 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3401 get_camera_metadata_size(request->settings));
3402 captureRequest->fmqSettingsSize = 0u;
3403 }
3404 } else {
3405 // A null request settings maps to a size-0 CameraMetadata
3406 captureRequest->settings.resize(0);
3407 captureRequest->fmqSettingsSize = 0u;
3408 }
3409 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003410 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003411 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3412 status = s;
3413 *numRequestProcessed = n;
3414 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003415 if (!err.isOk()) {
3416 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3417 return DEAD_OBJECT;
3418 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003419 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3420 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3421 __FUNCTION__, *numRequestProcessed, batchSize);
3422 status = common::V1_0::Status::INTERNAL_ERROR;
3423 }
3424
3425 for (auto& handle : handlesCreated) {
3426 native_handle_delete(handle);
3427 }
3428 return CameraProviderManager::mapToStatusT(status);
3429}
3430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003431status_t Camera3Device::HalInterface::processCaptureRequest(
3432 camera3_capture_request_t *request) {
3433 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003434 if (!valid()) return INVALID_OPERATION;
3435 status_t res = OK;
3436
Emilian Peev31abd0a2017-05-11 18:37:46 +01003437 uint32_t numRequestProcessed = 0;
3438 std::vector<camera3_capture_request_t*> requests(1);
3439 requests[0] = request;
3440 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3441
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003442 return res;
3443}
3444
3445status_t Camera3Device::HalInterface::flush() {
3446 ATRACE_NAME("CameraHal::flush");
3447 if (!valid()) return INVALID_OPERATION;
3448 status_t res = OK;
3449
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 auto err = mHidlSession->flush();
3451 if (!err.isOk()) {
3452 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3453 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003454 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003455 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003456 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003457
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003458 return res;
3459}
3460
Emilian Peev31abd0a2017-05-11 18:37:46 +01003461status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003462 ATRACE_NAME("CameraHal::dump");
3463 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003464
Emilian Peev31abd0a2017-05-11 18:37:46 +01003465 // Handled by CameraProviderManager::dump
3466
3467 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003468}
3469
3470status_t Camera3Device::HalInterface::close() {
3471 ATRACE_NAME("CameraHal::close()");
3472 if (!valid()) return INVALID_OPERATION;
3473 status_t res = OK;
3474
Emilian Peev31abd0a2017-05-11 18:37:46 +01003475 auto err = mHidlSession->close();
3476 // Interface will be dead shortly anyway, so don't log errors
3477 if (!err.isOk()) {
3478 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003479 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003480
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003481 return res;
3482}
3483
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003484void Camera3Device::HalInterface::getInflightBufferKeys(
3485 std::vector<std::pair<int32_t, int32_t>>* out) {
3486 std::lock_guard<std::mutex> lock(mInflightLock);
3487 out->clear();
3488 out->reserve(mInflightBufferMap.size());
3489 for (auto& pair : mInflightBufferMap) {
3490 uint64_t key = pair.first;
3491 int32_t streamId = key & 0xFFFFFFFF;
3492 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3493 out->push_back(std::make_pair(frameNumber, streamId));
3494 }
3495 return;
3496}
3497
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003498status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003499 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003500 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003501 auto pair = std::make_pair(buffer, acquireFence);
3502 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003503 return OK;
3504}
3505
3506status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003507 int32_t frameNumber, int32_t streamId,
3508 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003509 std::lock_guard<std::mutex> lock(mInflightLock);
3510
3511 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3512 auto it = mInflightBufferMap.find(key);
3513 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003514 auto pair = it->second;
3515 *buffer = pair.first;
3516 int acquireFence = pair.second;
3517 if (acquireFence > 0) {
3518 ::close(acquireFence);
3519 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003520 mInflightBufferMap.erase(it);
3521 return OK;
3522}
3523
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003524std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3525 const buffer_handle_t& buf, int streamId) {
3526 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3527
3528 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3529 auto it = bIdMap.find(buf);
3530 if (it == bIdMap.end()) {
3531 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003532 ALOGV("stream %d now have %zu buffer caches, buf %p",
3533 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003534 return std::make_pair(true, mNextBufferId - 1);
3535 } else {
3536 return std::make_pair(false, it->second);
3537 }
3538}
3539
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003540void Camera3Device::HalInterface::onBufferFreed(
3541 int streamId, const native_handle_t* handle) {
3542 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3543 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3544 auto mapIt = mBufferIdMaps.find(streamId);
3545 if (mapIt == mBufferIdMaps.end()) {
3546 // streamId might be from a deleted stream here
3547 ALOGI("%s: stream %d has been removed",
3548 __FUNCTION__, streamId);
3549 return;
3550 }
3551 BufferIdMap& bIdMap = mapIt->second;
3552 auto it = bIdMap.find(handle);
3553 if (it == bIdMap.end()) {
3554 ALOGW("%s: cannot find buffer %p in stream %d",
3555 __FUNCTION__, handle, streamId);
3556 return;
3557 } else {
3558 bufferId = it->second;
3559 bIdMap.erase(it);
3560 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3561 __FUNCTION__, streamId, bIdMap.size(), handle);
3562 }
3563 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3564}
3565
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003566/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003567 * RequestThread inner class methods
3568 */
3569
3570Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003571 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003572 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003573 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003574 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003575 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003576 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003577 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003578 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003579 mReconfigured(false),
3580 mDoPause(false),
3581 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003582 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003583 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003584 mCurrentAfTriggerId(0),
3585 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003586 mRepeatingLastFrameNumber(
3587 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003588 mPrepareVideoStream(false),
3589 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003590 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003591}
3592
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003593Camera3Device::RequestThread::~RequestThread() {}
3594
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003595void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003596 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003597 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003598 Mutex::Autolock l(mRequestLock);
3599 mListener = listener;
3600}
3601
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003602void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003603 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003604 Mutex::Autolock l(mRequestLock);
3605 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003606 // Prepare video stream for high speed recording.
3607 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003608}
3609
Jianing Wei90e59c92014-03-12 18:29:36 -07003610status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003611 List<sp<CaptureRequest> > &requests,
3612 /*out*/
3613 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003614 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003615 Mutex::Autolock l(mRequestLock);
3616 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3617 ++it) {
3618 mRequestQueue.push_back(*it);
3619 }
3620
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003621 if (lastFrameNumber != NULL) {
3622 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3623 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3624 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3625 *lastFrameNumber);
3626 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003627
Jianing Wei90e59c92014-03-12 18:29:36 -07003628 unpauseForNewRequests();
3629
3630 return OK;
3631}
3632
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003633
3634status_t Camera3Device::RequestThread::queueTrigger(
3635 RequestTrigger trigger[],
3636 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003637 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003638 Mutex::Autolock l(mTriggerMutex);
3639 status_t ret;
3640
3641 for (size_t i = 0; i < count; ++i) {
3642 ret = queueTriggerLocked(trigger[i]);
3643
3644 if (ret != OK) {
3645 return ret;
3646 }
3647 }
3648
3649 return OK;
3650}
3651
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003652const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3653 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003654 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003655 if (d != nullptr) return d->mId;
3656 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003657}
3658
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003659status_t Camera3Device::RequestThread::queueTriggerLocked(
3660 RequestTrigger trigger) {
3661
3662 uint32_t tag = trigger.metadataTag;
3663 ssize_t index = mTriggerMap.indexOfKey(tag);
3664
3665 switch (trigger.getTagType()) {
3666 case TYPE_BYTE:
3667 // fall-through
3668 case TYPE_INT32:
3669 break;
3670 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003671 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3672 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003673 return INVALID_OPERATION;
3674 }
3675
3676 /**
3677 * Collect only the latest trigger, since we only have 1 field
3678 * in the request settings per trigger tag, and can't send more than 1
3679 * trigger per request.
3680 */
3681 if (index != NAME_NOT_FOUND) {
3682 mTriggerMap.editValueAt(index) = trigger;
3683 } else {
3684 mTriggerMap.add(tag, trigger);
3685 }
3686
3687 return OK;
3688}
3689
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003690status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003691 const RequestList &requests,
3692 /*out*/
3693 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003694 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003695 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003696 if (lastFrameNumber != NULL) {
3697 *lastFrameNumber = mRepeatingLastFrameNumber;
3698 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003699 mRepeatingRequests.clear();
3700 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3701 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003702
3703 unpauseForNewRequests();
3704
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003705 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003706 return OK;
3707}
3708
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003709bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003710 if (mRepeatingRequests.empty()) {
3711 return false;
3712 }
3713 int32_t requestId = requestIn->mResultExtras.requestId;
3714 const RequestList &repeatRequests = mRepeatingRequests;
3715 // All repeating requests are guaranteed to have same id so only check first quest
3716 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3717 return (firstRequest->mResultExtras.requestId == requestId);
3718}
3719
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003720status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003721 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003722 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003723 return clearRepeatingRequestsLocked(lastFrameNumber);
3724
3725}
3726
3727status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003728 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003729 if (lastFrameNumber != NULL) {
3730 *lastFrameNumber = mRepeatingLastFrameNumber;
3731 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003732 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003733 return OK;
3734}
3735
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003736status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003737 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003738 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003739 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003740 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003741
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003742 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003743
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003744 // Send errors for all requests pending in the request queue, including
3745 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003746 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003747 if (listener != NULL) {
3748 for (RequestList::iterator it = mRequestQueue.begin();
3749 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003750 // Abort the input buffers for reprocess requests.
3751 if ((*it)->mInputStream != NULL) {
3752 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003753 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3754 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003755 if (res != OK) {
3756 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3757 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3758 } else {
3759 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3760 if (res != OK) {
3761 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3762 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3763 }
3764 }
3765 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003766 // Set the frame number this request would have had, if it
3767 // had been submitted; this frame number will not be reused.
3768 // The requestId and burstId fields were set when the request was
3769 // submitted originally (in convertMetadataListToRequestListLocked)
3770 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003771 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003772 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003773 }
3774 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003775 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003776
3777 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003778 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003779 if (lastFrameNumber != NULL) {
3780 *lastFrameNumber = mRepeatingLastFrameNumber;
3781 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003782 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003783 return OK;
3784}
3785
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003786status_t Camera3Device::RequestThread::flush() {
3787 ATRACE_CALL();
3788 Mutex::Autolock l(mFlushLock);
3789
Emilian Peev08dd2452017-04-06 16:55:14 +01003790 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003791}
3792
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003793void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003794 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003795 Mutex::Autolock l(mPauseLock);
3796 mDoPause = paused;
3797 mDoPauseSignal.signal();
3798}
3799
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003800status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3801 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003802 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003803 Mutex::Autolock l(mLatestRequestMutex);
3804 status_t res;
3805 while (mLatestRequestId != requestId) {
3806 nsecs_t startTime = systemTime();
3807
3808 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3809 if (res != OK) return res;
3810
3811 timeout -= (systemTime() - startTime);
3812 }
3813
3814 return OK;
3815}
3816
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003817void Camera3Device::RequestThread::requestExit() {
3818 // Call parent to set up shutdown
3819 Thread::requestExit();
3820 // The exit from any possible waits
3821 mDoPauseSignal.signal();
3822 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003823
3824 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3825 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003826}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003827
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003828void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003829 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003830 bool surfaceAbandoned = false;
3831 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003832 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003833 {
3834 Mutex::Autolock l(mRequestLock);
3835 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3836 // repeating requests.
3837 for (const auto& request : mRepeatingRequests) {
3838 for (const auto& s : request->mOutputStreams) {
3839 if (s->isAbandoned()) {
3840 surfaceAbandoned = true;
3841 clearRepeatingRequestsLocked(&lastFrameNumber);
3842 break;
3843 }
3844 }
3845 if (surfaceAbandoned) {
3846 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003847 }
3848 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003849 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003850 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003851
3852 if (listener != NULL && surfaceAbandoned) {
3853 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003854 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003855}
3856
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003857bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003858 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003859 status_t res;
3860 size_t batchSize = mNextRequests.size();
3861 std::vector<camera3_capture_request_t*> requests(batchSize);
3862 uint32_t numRequestProcessed = 0;
3863 for (size_t i = 0; i < batchSize; i++) {
3864 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3865 }
3866
3867 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3868 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3869
3870 bool triggerRemoveFailed = false;
3871 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3872 for (size_t i = 0; i < numRequestProcessed; i++) {
3873 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3874 nextRequest.submitted = true;
3875
3876
3877 // Update the latest request sent to HAL
3878 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3879 Mutex::Autolock al(mLatestRequestMutex);
3880
3881 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3882 mLatestRequest.acquire(cloned);
3883
3884 sp<Camera3Device> parent = mParent.promote();
3885 if (parent != NULL) {
3886 parent->monitorMetadata(TagMonitor::REQUEST,
3887 nextRequest.halRequest.frame_number,
3888 0, mLatestRequest);
3889 }
3890 }
3891
3892 if (nextRequest.halRequest.settings != NULL) {
3893 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3894 }
3895
3896 if (!triggerRemoveFailed) {
3897 // Remove any previously queued triggers (after unlock)
3898 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3899 if (removeTriggerRes != OK) {
3900 triggerRemoveFailed = true;
3901 triggerFailedRequest = nextRequest;
3902 }
3903 }
3904 }
3905
3906 if (triggerRemoveFailed) {
3907 SET_ERR("RequestThread: Unable to remove triggers "
3908 "(capture request %d, HAL device: %s (%d)",
3909 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3910 cleanUpFailedRequests(/*sendRequestError*/ false);
3911 return false;
3912 }
3913
3914 if (res != OK) {
3915 // Should only get a failure here for malformed requests or device-level
3916 // errors, so consider all errors fatal. Bad metadata failures should
3917 // come through notify.
3918 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3919 mNextRequests[numRequestProcessed].halRequest.frame_number,
3920 strerror(-res), res);
3921 cleanUpFailedRequests(/*sendRequestError*/ false);
3922 return false;
3923 }
3924 return true;
3925}
3926
3927bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3928 status_t res;
3929
3930 for (auto& nextRequest : mNextRequests) {
3931 // Submit request and block until ready for next one
3932 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3933 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3934
3935 if (res != OK) {
3936 // Should only get a failure here for malformed requests or device-level
3937 // errors, so consider all errors fatal. Bad metadata failures should
3938 // come through notify.
3939 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3940 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3941 res);
3942 cleanUpFailedRequests(/*sendRequestError*/ false);
3943 return false;
3944 }
3945
3946 // Mark that the request has be submitted successfully.
3947 nextRequest.submitted = true;
3948
3949 // Update the latest request sent to HAL
3950 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3951 Mutex::Autolock al(mLatestRequestMutex);
3952
3953 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3954 mLatestRequest.acquire(cloned);
3955
3956 sp<Camera3Device> parent = mParent.promote();
3957 if (parent != NULL) {
3958 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3959 0, mLatestRequest);
3960 }
3961 }
3962
3963 if (nextRequest.halRequest.settings != NULL) {
3964 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3965 }
3966
3967 // Remove any previously queued triggers (after unlock)
3968 res = removeTriggers(mPrevRequest);
3969 if (res != OK) {
3970 SET_ERR("RequestThread: Unable to remove triggers "
3971 "(capture request %d, HAL device: %s (%d)",
3972 nextRequest.halRequest.frame_number, strerror(-res), res);
3973 cleanUpFailedRequests(/*sendRequestError*/ false);
3974 return false;
3975 }
3976 }
3977 return true;
3978}
3979
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003980nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3981 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3982 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3983 find_camera_metadata_ro_entry(request,
3984 ANDROID_CONTROL_AE_MODE,
3985 &e);
3986 if (e.count == 0) return maxExpectedDuration;
3987
3988 switch (e.data.u8[0]) {
3989 case ANDROID_CONTROL_AE_MODE_OFF:
3990 find_camera_metadata_ro_entry(request,
3991 ANDROID_SENSOR_EXPOSURE_TIME,
3992 &e);
3993 if (e.count > 0) {
3994 maxExpectedDuration = e.data.i64[0];
3995 }
3996 find_camera_metadata_ro_entry(request,
3997 ANDROID_SENSOR_FRAME_DURATION,
3998 &e);
3999 if (e.count > 0) {
4000 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4001 }
4002 break;
4003 default:
4004 find_camera_metadata_ro_entry(request,
4005 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4006 &e);
4007 if (e.count > 1) {
4008 maxExpectedDuration = 1e9 / e.data.u8[0];
4009 }
4010 break;
4011 }
4012
4013 return maxExpectedDuration;
4014}
4015
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004016bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004017 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004018 status_t res;
4019
4020 // Handle paused state.
4021 if (waitIfPaused()) {
4022 return true;
4023 }
4024
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004025 // Wait for the next batch of requests.
4026 waitForNextRequestBatch();
4027 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004028 return true;
4029 }
4030
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004031 // Get the latest request ID, if any
4032 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004033 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004034 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004035 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004036 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004037 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004038 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4039 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004040 }
4041
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004042 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004043 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004044 if (res == TIMED_OUT) {
4045 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004046 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004047 // Check if any stream is abandoned.
4048 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004049 return true;
4050 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004051 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004052 return false;
4053 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004054
Zhijun Hecc27e112013-10-03 16:12:43 -07004055 // Inform waitUntilRequestProcessed thread of a new request ID
4056 {
4057 Mutex::Autolock al(mLatestRequestMutex);
4058
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004060 mLatestRequestSignal.signal();
4061 }
4062
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004063 // Submit a batch of requests to HAL.
4064 // Use flush lock only when submitting multilple requests in a batch.
4065 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4066 // which may take a long time to finish so synchronizing flush() and
4067 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4068 // For now, only synchronize for high speed recording and we should figure something out for
4069 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004070 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004071
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072 if (useFlushLock) {
4073 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004074 }
4075
Zhijun Hef0645c12016-08-02 00:58:11 -07004076 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004077 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004078
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004079 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004080 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004081 if (mInterface->supportBatchRequest()) {
4082 submitRequestSuccess = sendRequestsBatch();
4083 } else {
4084 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004085 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004086 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4087 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004088
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004089 if (useFlushLock) {
4090 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004091 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004092
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004093 // Unset as current request
4094 {
4095 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004096 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004097 }
4098
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004099 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004100}
4101
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004102status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004103 ATRACE_CALL();
4104
Shuzhen Wang4a472662017-02-26 23:29:04 -08004105 for (size_t i = 0; i < mNextRequests.size(); i++) {
4106 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004107 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4108 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4109 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4110
4111 // Prepare a request to HAL
4112 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4113
4114 // Insert any queued triggers (before metadata is locked)
4115 status_t res = insertTriggers(captureRequest);
4116
4117 if (res < 0) {
4118 SET_ERR("RequestThread: Unable to insert triggers "
4119 "(capture request %d, HAL device: %s (%d)",
4120 halRequest->frame_number, strerror(-res), res);
4121 return INVALID_OPERATION;
4122 }
4123 int triggerCount = res;
4124 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4125 mPrevTriggers = triggerCount;
4126
4127 // If the request is the same as last, or we had triggers last time
4128 if (mPrevRequest != captureRequest || triggersMixedIn) {
4129 /**
4130 * HAL workaround:
4131 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4132 */
4133 res = addDummyTriggerIds(captureRequest);
4134 if (res != OK) {
4135 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4136 "(capture request %d, HAL device: %s (%d)",
4137 halRequest->frame_number, strerror(-res), res);
4138 return INVALID_OPERATION;
4139 }
4140
4141 /**
4142 * The request should be presorted so accesses in HAL
4143 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4144 */
4145 captureRequest->mSettings.sort();
4146 halRequest->settings = captureRequest->mSettings.getAndLock();
4147 mPrevRequest = captureRequest;
4148 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4149
4150 IF_ALOGV() {
4151 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4152 find_camera_metadata_ro_entry(
4153 halRequest->settings,
4154 ANDROID_CONTROL_AF_TRIGGER,
4155 &e
4156 );
4157 if (e.count > 0) {
4158 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4159 __FUNCTION__,
4160 halRequest->frame_number,
4161 e.data.u8[0]);
4162 }
4163 }
4164 } else {
4165 // leave request.settings NULL to indicate 'reuse latest given'
4166 ALOGVV("%s: Request settings are REUSED",
4167 __FUNCTION__);
4168 }
4169
4170 uint32_t totalNumBuffers = 0;
4171
4172 // Fill in buffers
4173 if (captureRequest->mInputStream != NULL) {
4174 halRequest->input_buffer = &captureRequest->mInputBuffer;
4175 totalNumBuffers += 1;
4176 } else {
4177 halRequest->input_buffer = NULL;
4178 }
4179
4180 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4181 captureRequest->mOutputStreams.size());
4182 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004183 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4184 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004185
4186 // Prepare video buffers for high speed recording on the first video request.
4187 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4188 // Only try to prepare video stream on the first video request.
4189 mPrepareVideoStream = false;
4190
4191 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4192 while (res == NOT_ENOUGH_DATA) {
4193 res = outputStream->prepareNextBuffer();
4194 }
4195 if (res != OK) {
4196 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4197 __FUNCTION__, strerror(-res), res);
4198 outputStream->cancelPrepare();
4199 }
4200 }
4201
Shuzhen Wang4a472662017-02-26 23:29:04 -08004202 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4203 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004204 if (res != OK) {
4205 // Can't get output buffer from gralloc queue - this could be due to
4206 // abandoned queue or other consumer misbehavior, so not a fatal
4207 // error
4208 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4209 " %s (%d)", strerror(-res), res);
4210
4211 return TIMED_OUT;
4212 }
4213 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004214
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004215 }
4216 totalNumBuffers += halRequest->num_output_buffers;
4217
4218 // Log request in the in-flight queue
4219 sp<Camera3Device> parent = mParent.promote();
4220 if (parent == NULL) {
4221 // Should not happen, and nowhere to send errors to, so just log it
4222 CLOGE("RequestThread: Parent is gone");
4223 return INVALID_OPERATION;
4224 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004225
4226 // If this request list is for constrained high speed recording (not
4227 // preview), and the current request is not the last one in the batch,
4228 // do not send callback to the app.
4229 bool hasCallback = true;
4230 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4231 hasCallback = false;
4232 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004233 res = parent->registerInFlight(halRequest->frame_number,
4234 totalNumBuffers, captureRequest->mResultExtras,
4235 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004236 hasCallback,
4237 calculateMaxExpectedDuration(halRequest->settings));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004238 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4239 ", burstId = %" PRId32 ".",
4240 __FUNCTION__,
4241 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4242 captureRequest->mResultExtras.burstId);
4243 if (res != OK) {
4244 SET_ERR("RequestThread: Unable to register new in-flight request:"
4245 " %s (%d)", strerror(-res), res);
4246 return INVALID_OPERATION;
4247 }
4248 }
4249
4250 return OK;
4251}
4252
Igor Murashkin1e479c02013-09-06 16:55:14 -07004253CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004254 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004255 Mutex::Autolock al(mLatestRequestMutex);
4256
4257 ALOGV("RequestThread::%s", __FUNCTION__);
4258
4259 return mLatestRequest;
4260}
4261
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004262bool Camera3Device::RequestThread::isStreamPending(
4263 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004264 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004265 Mutex::Autolock l(mRequestLock);
4266
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004267 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004268 if (!nextRequest.submitted) {
4269 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4270 if (stream == s) return true;
4271 }
4272 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004273 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004274 }
4275
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004276 for (const auto& request : mRequestQueue) {
4277 for (const auto& s : request->mOutputStreams) {
4278 if (stream == s) return true;
4279 }
4280 if (stream == request->mInputStream) return true;
4281 }
4282
4283 for (const auto& request : mRepeatingRequests) {
4284 for (const auto& s : request->mOutputStreams) {
4285 if (stream == s) return true;
4286 }
4287 if (stream == request->mInputStream) return true;
4288 }
4289
4290 return false;
4291}
Jianing Weicb0652e2014-03-12 18:29:36 -07004292
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004293nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004294 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004295 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004296 return mExpectedInflightDuration > kMinInflightDuration ?
4297 mExpectedInflightDuration : kMinInflightDuration;
4298}
4299
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004300void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4301 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004302 return;
4303 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004304
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004305 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004306 // Skip the ones that have been submitted successfully.
4307 if (nextRequest.submitted) {
4308 continue;
4309 }
4310
4311 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4312 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4313 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4314
4315 if (halRequest->settings != NULL) {
4316 captureRequest->mSettings.unlock(halRequest->settings);
4317 }
4318
4319 if (captureRequest->mInputStream != NULL) {
4320 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4321 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4322 }
4323
4324 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004325 //Buffers that failed processing could still have
4326 //valid acquire fence.
4327 int acquireFence = (*outputBuffers)[i].acquire_fence;
4328 if (0 <= acquireFence) {
4329 close(acquireFence);
4330 outputBuffers->editItemAt(i).acquire_fence = -1;
4331 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004332 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4333 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4334 }
4335
4336 if (sendRequestError) {
4337 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004338 sp<NotificationListener> listener = mListener.promote();
4339 if (listener != NULL) {
4340 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004341 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004342 captureRequest->mResultExtras);
4343 }
4344 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004345
4346 // Remove yet-to-be submitted inflight request from inflightMap
4347 {
4348 sp<Camera3Device> parent = mParent.promote();
4349 if (parent != NULL) {
4350 Mutex::Autolock l(parent->mInFlightLock);
4351 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4352 if (idx >= 0) {
4353 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4354 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4355 parent->removeInFlightMapEntryLocked(idx);
4356 }
4357 }
4358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004359 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004360
4361 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004362 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363}
4364
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004365void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004366 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367 // Optimized a bit for the simple steady-state case (single repeating
4368 // request), to avoid putting that request in the queue temporarily.
4369 Mutex::Autolock l(mRequestLock);
4370
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004371 assert(mNextRequests.empty());
4372
4373 NextRequest nextRequest;
4374 nextRequest.captureRequest = waitForNextRequestLocked();
4375 if (nextRequest.captureRequest == nullptr) {
4376 return;
4377 }
4378
4379 nextRequest.halRequest = camera3_capture_request_t();
4380 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004381 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004382
4383 // Wait for additional requests
4384 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4385
4386 for (size_t i = 1; i < batchSize; i++) {
4387 NextRequest additionalRequest;
4388 additionalRequest.captureRequest = waitForNextRequestLocked();
4389 if (additionalRequest.captureRequest == nullptr) {
4390 break;
4391 }
4392
4393 additionalRequest.halRequest = camera3_capture_request_t();
4394 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004395 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004396 }
4397
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004398 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004399 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004400 mNextRequests.size(), batchSize);
4401 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004402 }
4403
4404 return;
4405}
4406
4407sp<Camera3Device::CaptureRequest>
4408 Camera3Device::RequestThread::waitForNextRequestLocked() {
4409 status_t res;
4410 sp<CaptureRequest> nextRequest;
4411
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004412 while (mRequestQueue.empty()) {
4413 if (!mRepeatingRequests.empty()) {
4414 // Always atomically enqueue all requests in a repeating request
4415 // list. Guarantees a complete in-sequence set of captures to
4416 // application.
4417 const RequestList &requests = mRepeatingRequests;
4418 RequestList::const_iterator firstRequest =
4419 requests.begin();
4420 nextRequest = *firstRequest;
4421 mRequestQueue.insert(mRequestQueue.end(),
4422 ++firstRequest,
4423 requests.end());
4424 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004425
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004426 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004427
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004428 break;
4429 }
4430
4431 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4432
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004433 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4434 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004435 Mutex::Autolock pl(mPauseLock);
4436 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004437 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004438 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004439 // Let the tracker know
4440 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4441 if (statusTracker != 0) {
4442 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4443 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004444 }
4445 // Stop waiting for now and let thread management happen
4446 return NULL;
4447 }
4448 }
4449
4450 if (nextRequest == NULL) {
4451 // Don't have a repeating request already in hand, so queue
4452 // must have an entry now.
4453 RequestList::iterator firstRequest =
4454 mRequestQueue.begin();
4455 nextRequest = *firstRequest;
4456 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004457 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4458 sp<NotificationListener> listener = mListener.promote();
4459 if (listener != NULL) {
4460 listener->notifyRequestQueueEmpty();
4461 }
4462 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004463 }
4464
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004465 // In case we've been unpaused by setPaused clearing mDoPause, need to
4466 // update internal pause state (capture/setRepeatingRequest unpause
4467 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004468 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004469 if (mPaused) {
4470 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4471 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4472 if (statusTracker != 0) {
4473 statusTracker->markComponentActive(mStatusId);
4474 }
4475 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004476 mPaused = false;
4477
4478 // Check if we've reconfigured since last time, and reset the preview
4479 // request if so. Can't use 'NULL request == repeat' across configure calls.
4480 if (mReconfigured) {
4481 mPrevRequest.clear();
4482 mReconfigured = false;
4483 }
4484
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004485 if (nextRequest != NULL) {
4486 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004487 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4488 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004489
4490 // Since RequestThread::clear() removes buffers from the input stream,
4491 // get the right buffer here before unlocking mRequestLock
4492 if (nextRequest->mInputStream != NULL) {
4493 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4494 if (res != OK) {
4495 // Can't get input buffer from gralloc queue - this could be due to
4496 // disconnected queue or other producer misbehavior, so not a fatal
4497 // error
4498 ALOGE("%s: Can't get input buffer, skipping request:"
4499 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004500
4501 sp<NotificationListener> listener = mListener.promote();
4502 if (listener != NULL) {
4503 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004504 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004505 nextRequest->mResultExtras);
4506 }
4507 return NULL;
4508 }
4509 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004510 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004511
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004512 return nextRequest;
4513}
4514
4515bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004516 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004517 status_t res;
4518 Mutex::Autolock l(mPauseLock);
4519 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004520 if (mPaused == false) {
4521 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004522 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4523 // Let the tracker know
4524 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4525 if (statusTracker != 0) {
4526 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4527 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004528 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004529
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004530 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004531 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004532 return true;
4533 }
4534 }
4535 // We don't set mPaused to false here, because waitForNextRequest needs
4536 // to further manage the paused state in case of starvation.
4537 return false;
4538}
4539
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004540void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004541 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004542 // With work to do, mark thread as unpaused.
4543 // If paused by request (setPaused), don't resume, to avoid
4544 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004545 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004546 Mutex::Autolock p(mPauseLock);
4547 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004548 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4549 if (mPaused) {
4550 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4551 if (statusTracker != 0) {
4552 statusTracker->markComponentActive(mStatusId);
4553 }
4554 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004555 mPaused = false;
4556 }
4557}
4558
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004559void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4560 sp<Camera3Device> parent = mParent.promote();
4561 if (parent != NULL) {
4562 va_list args;
4563 va_start(args, fmt);
4564
4565 parent->setErrorStateV(fmt, args);
4566
4567 va_end(args);
4568 }
4569}
4570
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004571status_t Camera3Device::RequestThread::insertTriggers(
4572 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004573 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004574 Mutex::Autolock al(mTriggerMutex);
4575
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004576 sp<Camera3Device> parent = mParent.promote();
4577 if (parent == NULL) {
4578 CLOGE("RequestThread: Parent is gone");
4579 return DEAD_OBJECT;
4580 }
4581
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004582 CameraMetadata &metadata = request->mSettings;
4583 size_t count = mTriggerMap.size();
4584
4585 for (size_t i = 0; i < count; ++i) {
4586 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004587 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004588
4589 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4590 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4591 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004592 if (isAeTrigger) {
4593 request->mResultExtras.precaptureTriggerId = triggerId;
4594 mCurrentPreCaptureTriggerId = triggerId;
4595 } else {
4596 request->mResultExtras.afTriggerId = triggerId;
4597 mCurrentAfTriggerId = triggerId;
4598 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004599 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004600 }
4601
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004602 camera_metadata_entry entry = metadata.find(tag);
4603
4604 if (entry.count > 0) {
4605 /**
4606 * Already has an entry for this trigger in the request.
4607 * Rewrite it with our requested trigger value.
4608 */
4609 RequestTrigger oldTrigger = trigger;
4610
4611 oldTrigger.entryValue = entry.data.u8[0];
4612
4613 mTriggerReplacedMap.add(tag, oldTrigger);
4614 } else {
4615 /**
4616 * More typical, no trigger entry, so we just add it
4617 */
4618 mTriggerRemovedMap.add(tag, trigger);
4619 }
4620
4621 status_t res;
4622
4623 switch (trigger.getTagType()) {
4624 case TYPE_BYTE: {
4625 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4626 res = metadata.update(tag,
4627 &entryValue,
4628 /*count*/1);
4629 break;
4630 }
4631 case TYPE_INT32:
4632 res = metadata.update(tag,
4633 &trigger.entryValue,
4634 /*count*/1);
4635 break;
4636 default:
4637 ALOGE("%s: Type not supported: 0x%x",
4638 __FUNCTION__,
4639 trigger.getTagType());
4640 return INVALID_OPERATION;
4641 }
4642
4643 if (res != OK) {
4644 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4645 ", value %d", __FUNCTION__, trigger.getTagName(),
4646 trigger.entryValue);
4647 return res;
4648 }
4649
4650 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4651 trigger.getTagName(),
4652 trigger.entryValue);
4653 }
4654
4655 mTriggerMap.clear();
4656
4657 return count;
4658}
4659
4660status_t Camera3Device::RequestThread::removeTriggers(
4661 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004662 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004663 Mutex::Autolock al(mTriggerMutex);
4664
4665 CameraMetadata &metadata = request->mSettings;
4666
4667 /**
4668 * Replace all old entries with their old values.
4669 */
4670 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4671 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4672
4673 status_t res;
4674
4675 uint32_t tag = trigger.metadataTag;
4676 switch (trigger.getTagType()) {
4677 case TYPE_BYTE: {
4678 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4679 res = metadata.update(tag,
4680 &entryValue,
4681 /*count*/1);
4682 break;
4683 }
4684 case TYPE_INT32:
4685 res = metadata.update(tag,
4686 &trigger.entryValue,
4687 /*count*/1);
4688 break;
4689 default:
4690 ALOGE("%s: Type not supported: 0x%x",
4691 __FUNCTION__,
4692 trigger.getTagType());
4693 return INVALID_OPERATION;
4694 }
4695
4696 if (res != OK) {
4697 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4698 ", trigger value %d", __FUNCTION__,
4699 trigger.getTagName(), trigger.entryValue);
4700 return res;
4701 }
4702 }
4703 mTriggerReplacedMap.clear();
4704
4705 /**
4706 * Remove all new entries.
4707 */
4708 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4709 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4710 status_t res = metadata.erase(trigger.metadataTag);
4711
4712 if (res != OK) {
4713 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4714 ", trigger value %d", __FUNCTION__,
4715 trigger.getTagName(), trigger.entryValue);
4716 return res;
4717 }
4718 }
4719 mTriggerRemovedMap.clear();
4720
4721 return OK;
4722}
4723
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004724status_t Camera3Device::RequestThread::addDummyTriggerIds(
4725 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004726 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004727 static const int32_t dummyTriggerId = 1;
4728 status_t res;
4729
4730 CameraMetadata &metadata = request->mSettings;
4731
4732 // If AF trigger is active, insert a dummy AF trigger ID if none already
4733 // exists
4734 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4735 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4736 if (afTrigger.count > 0 &&
4737 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4738 afId.count == 0) {
4739 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4740 if (res != OK) return res;
4741 }
4742
4743 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4744 // if none already exists
4745 camera_metadata_entry pcTrigger =
4746 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4747 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4748 if (pcTrigger.count > 0 &&
4749 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4750 pcId.count == 0) {
4751 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4752 &dummyTriggerId, 1);
4753 if (res != OK) return res;
4754 }
4755
4756 return OK;
4757}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004758
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004759/**
4760 * PreparerThread inner class methods
4761 */
4762
4763Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004764 Thread(/*canCallJava*/false), mListener(nullptr),
4765 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004766}
4767
4768Camera3Device::PreparerThread::~PreparerThread() {
4769 Thread::requestExitAndWait();
4770 if (mCurrentStream != nullptr) {
4771 mCurrentStream->cancelPrepare();
4772 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4773 mCurrentStream.clear();
4774 }
4775 clear();
4776}
4777
Ruben Brunkc78ac262015-08-13 17:58:46 -07004778status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004779 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004780 status_t res;
4781
4782 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004783 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004784
Ruben Brunkc78ac262015-08-13 17:58:46 -07004785 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004786 if (res == OK) {
4787 // No preparation needed, fire listener right off
4788 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004789 if (listener != NULL) {
4790 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004791 }
4792 return OK;
4793 } else if (res != NOT_ENOUGH_DATA) {
4794 return res;
4795 }
4796
4797 // Need to prepare, start up thread if necessary
4798 if (!mActive) {
4799 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4800 // isn't running
4801 Thread::requestExitAndWait();
4802 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4803 if (res != OK) {
4804 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004805 if (listener != NULL) {
4806 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004807 }
4808 return res;
4809 }
4810 mCancelNow = false;
4811 mActive = true;
4812 ALOGV("%s: Preparer stream started", __FUNCTION__);
4813 }
4814
4815 // queue up the work
4816 mPendingStreams.push_back(stream);
4817 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4818
4819 return OK;
4820}
4821
4822status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004823 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004824 Mutex::Autolock l(mLock);
4825
4826 for (const auto& stream : mPendingStreams) {
4827 stream->cancelPrepare();
4828 }
4829 mPendingStreams.clear();
4830 mCancelNow = true;
4831
4832 return OK;
4833}
4834
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004835void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004836 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004837 Mutex::Autolock l(mLock);
4838 mListener = listener;
4839}
4840
4841bool Camera3Device::PreparerThread::threadLoop() {
4842 status_t res;
4843 {
4844 Mutex::Autolock l(mLock);
4845 if (mCurrentStream == nullptr) {
4846 // End thread if done with work
4847 if (mPendingStreams.empty()) {
4848 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4849 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4850 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4851 mActive = false;
4852 return false;
4853 }
4854
4855 // Get next stream to prepare
4856 auto it = mPendingStreams.begin();
4857 mCurrentStream = *it;
4858 mPendingStreams.erase(it);
4859 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4860 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4861 } else if (mCancelNow) {
4862 mCurrentStream->cancelPrepare();
4863 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4864 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4865 mCurrentStream.clear();
4866 mCancelNow = false;
4867 return true;
4868 }
4869 }
4870
4871 res = mCurrentStream->prepareNextBuffer();
4872 if (res == NOT_ENOUGH_DATA) return true;
4873 if (res != OK) {
4874 // Something bad happened; try to recover by cancelling prepare and
4875 // signalling listener anyway
4876 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4877 mCurrentStream->getId(), res, strerror(-res));
4878 mCurrentStream->cancelPrepare();
4879 }
4880
4881 // This stream has finished, notify listener
4882 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004883 sp<NotificationListener> listener = mListener.promote();
4884 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004885 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4886 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004887 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004888 }
4889
4890 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4891 mCurrentStream.clear();
4892
4893 return true;
4894}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004895
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004896/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004897 * Static callback forwarding methods from HAL to instance
4898 */
4899
4900void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4901 const camera3_capture_result *result) {
4902 Camera3Device *d =
4903 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004904
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004905 d->processCaptureResult(result);
4906}
4907
4908void Camera3Device::sNotify(const camera3_callback_ops *cb,
4909 const camera3_notify_msg *msg) {
4910 Camera3Device *d =
4911 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4912 d->notify(msg);
4913}
4914
4915}; // namespace android