blob: 0807c0a11b1cb0a9026ea6a265ae4bacf4d2cf1a [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000077 mListener(NULL),
78 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080079{
80 ATRACE_CALL();
81 camera3_callback_ops::notify = &sNotify;
82 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080083 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084}
85
86Camera3Device::~Camera3Device()
87{
88 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080089 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080090 disconnect();
91}
92
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080094 return mId;
95}
96
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080097status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
98 ATRACE_CALL();
99 Mutex::Autolock il(mInterfaceLock);
100 Mutex::Autolock l(mLock);
101
102 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
103 if (mStatus != STATUS_UNINITIALIZED) {
104 CLOGE("Already initialized!");
105 return INVALID_OPERATION;
106 }
107 if (manager == nullptr) return INVALID_OPERATION;
108
109 sp<ICameraDeviceSession> session;
110 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800111 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112 /*out*/ &session);
113 ATRACE_END();
114 if (res != OK) {
115 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
116 return res;
117 }
118
Steven Moreland5ff9c912017-03-09 23:13:00 -0800119 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 if (res != OK) {
121 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
122 session->close();
123 return res;
124 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800125
Yifan Hongf79b5542017-04-11 14:44:25 -0700126 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700127 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
128 [&queue](const auto& descriptor) {
129 queue = std::make_shared<RequestMetadataQueue>(descriptor);
130 if (!queue->isValid() || queue->availableToWrite() <= 0) {
131 ALOGE("HAL returns empty request metadata fmq, not use it");
132 queue = nullptr;
133 // don't use the queue onwards.
134 }
135 });
136 if (!requestQueueRet.isOk()) {
137 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
138 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700139 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700140 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700141
142 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700144 [&resQueue](const auto& descriptor) {
145 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
146 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700147 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700148 resQueue = nullptr;
149 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700150 }
151 });
152 if (!resultQueueRet.isOk()) {
153 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
154 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700156 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700157
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700158 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000159 std::string providerType;
160 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800161
162 return initializeCommonLocked();
163}
164
165status_t Camera3Device::initializeCommonLocked() {
166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700167 /** Start up status tracker thread */
168 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800169 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700170 if (res != OK) {
171 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
172 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700174 mStatusTracker.clear();
175 return res;
176 }
177
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700178 /** Register in-flight map to the status tracker */
179 mInFlightStatusId = mStatusTracker->addComponent();
180
Zhijun He125684a2015-12-26 15:07:30 -0800181 /** Create buffer manager */
182 mBufferManager = new Camera3BufferManager();
183
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 mTagMonitor.initialize(mVendorTagId);
185
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700186 /** Start up request queue thread */
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700187 mRequestThread = new RequestThread(this, mStatusTracker, mInterface);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700190 SET_ERR_L("Unable to start request queue thread: %s (%d)",
191 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800192 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800193 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800194 return res;
195 }
196
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700197 mPreparerThread = new PreparerThread();
198
Ruben Brunk183f0562015-08-12 12:55:02 -0700199 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800200 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700201 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700202 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800204
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800205 // Measure the clock domain offset between camera and video/hw_composer
206 camera_metadata_entry timestampSource =
207 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
208 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
209 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
210 mTimestampOffset = getMonoToBoottimeOffset();
211 }
212
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700213 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100214 camera_metadata_entry partialResultsCount =
215 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
216 if (partialResultsCount.count > 0) {
217 mNumPartialResults = partialResultsCount.data.i32[0];
218 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700219 }
220
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700221 camera_metadata_entry configs =
222 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
223 for (uint32_t i = 0; i < configs.count; i += 4) {
224 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
225 configs.data.i32[i + 3] ==
226 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
227 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
228 configs.data.i32[i + 2]));
229 }
230 }
231
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800232 return OK;
233}
234
235status_t Camera3Device::disconnect() {
236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800238
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700239 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800240
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700241 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700242 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700243 {
244 Mutex::Autolock l(mLock);
245 if (mStatus == STATUS_UNINITIALIZED) return res;
246
247 if (mStatus == STATUS_ACTIVE ||
248 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
249 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 } else {
254 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
255 if (res != OK) {
256 SET_ERR_L("Timeout waiting for HAL to drain");
257 // Continue to close device even in case of error
258 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700259 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800260 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 if (mStatus == STATUS_ERROR) {
263 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700264 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265
266 if (mStatusTracker != NULL) {
267 mStatusTracker->requestExit();
268 }
269
270 if (mRequestThread != NULL) {
271 mRequestThread->requestExit();
272 }
273
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700274 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
275 for (size_t i = 0; i < mOutputStreams.size(); i++) {
276 streams.push_back(mOutputStreams[i]);
277 }
278 if (mInputStream != nullptr) {
279 streams.push_back(mInputStream);
280 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 }
282
283 // Joining done without holding mLock, otherwise deadlocks may ensue
284 // as the threads try to access parent state
285 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
286 // HAL may be in a bad state, so waiting for request thread
287 // (which may be stuck in the HAL processCaptureRequest call)
288 // could be dangerous.
289 mRequestThread->join();
290 }
291
292 if (mStatusTracker != NULL) {
293 mStatusTracker->join();
294 }
295
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800296 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 {
298 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800299 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800301 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700304 // Call close without internal mutex held, as the HAL close may need to
305 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800306 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700307
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700308 flushInflightRequests();
309
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700310 {
311 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800312 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700313 mOutputStreams.clear();
314 mInputStream.clear();
315 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700316 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800318
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700319 for (auto& weakStream : streams) {
320 sp<Camera3StreamInterface> stream = weakStream.promote();
321 if (stream != nullptr) {
322 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
323 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
324 }
325 }
326
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700327 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800329}
330
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331// For dumping/debugging only -
332// try to acquire a lock a few times, eventually give up to proceed with
333// debug/dump operations
334bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
335 bool gotLock = false;
336 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
337 if (lock.tryLock() == NO_ERROR) {
338 gotLock = true;
339 break;
340 } else {
341 usleep(kDumpSleepDuration);
342 }
343 }
344 return gotLock;
345}
346
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700347Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
348 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100349 const int STREAM_CONFIGURATION_SIZE = 4;
350 const int STREAM_FORMAT_OFFSET = 0;
351 const int STREAM_WIDTH_OFFSET = 1;
352 const int STREAM_HEIGHT_OFFSET = 2;
353 const int STREAM_IS_INPUT_OFFSET = 3;
354 camera_metadata_ro_entry_t availableStreamConfigs =
355 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
356 if (availableStreamConfigs.count == 0 ||
357 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
358 return Size(0, 0);
359 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700360
Emilian Peev08dd2452017-04-06 16:55:14 +0100361 // Get max jpeg size (area-wise).
362 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
363 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
364 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
365 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
366 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
367 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
368 && format == HAL_PIXEL_FORMAT_BLOB &&
369 (width * height > maxJpegWidth * maxJpegHeight)) {
370 maxJpegWidth = width;
371 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700372 }
373 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100374
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700375 return Size(maxJpegWidth, maxJpegHeight);
376}
377
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800378nsecs_t Camera3Device::getMonoToBoottimeOffset() {
379 // try three times to get the clock offset, choose the one
380 // with the minimum gap in measurements.
381 const int tries = 3;
382 nsecs_t bestGap, measured;
383 for (int i = 0; i < tries; ++i) {
384 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
385 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
386 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
387 const nsecs_t gap = tmono2 - tmono;
388 if (i == 0 || gap < bestGap) {
389 bestGap = gap;
390 measured = tbase - ((tmono + tmono2) >> 1);
391 }
392 }
393 return measured;
394}
395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800396hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
397 int frameworkFormat) {
398 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
399}
400
401DataspaceFlags Camera3Device::mapToHidlDataspace(
402 android_dataspace dataSpace) {
403 return dataSpace;
404}
405
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700406BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700407 uint32_t usage) {
408 return usage;
409}
410
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800411StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
412 switch (rotation) {
413 case CAMERA3_STREAM_ROTATION_0:
414 return StreamRotation::ROTATION_0;
415 case CAMERA3_STREAM_ROTATION_90:
416 return StreamRotation::ROTATION_90;
417 case CAMERA3_STREAM_ROTATION_180:
418 return StreamRotation::ROTATION_180;
419 case CAMERA3_STREAM_ROTATION_270:
420 return StreamRotation::ROTATION_270;
421 }
422 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
423 return StreamRotation::ROTATION_0;
424}
425
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800426status_t Camera3Device::mapToStreamConfigurationMode(
427 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
428 if (mode == nullptr) return BAD_VALUE;
429 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
430 switch(operationMode) {
431 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
432 *mode = StreamConfigurationMode::NORMAL_MODE;
433 break;
434 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
435 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
436 break;
437 default:
438 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
439 return BAD_VALUE;
440 }
441 } else {
442 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800443 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800444 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800445}
446
447camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
448 switch (status) {
449 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
450 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
451 }
452 return CAMERA3_BUFFER_STATUS_ERROR;
453}
454
455int Camera3Device::mapToFrameworkFormat(
456 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
457 return static_cast<uint32_t>(pixelFormat);
458}
459
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700460uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700461 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700462 return usage;
463}
464
465uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700466 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700467 return usage;
468}
469
Zhijun Hef7da0962014-04-24 13:27:56 -0700470ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700471 // Get max jpeg size (area-wise).
472 Size maxJpegResolution = getMaxJpegResolution();
473 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800474 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
475 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700476 return BAD_VALUE;
477 }
478
Zhijun Hef7da0962014-04-24 13:27:56 -0700479 // Get max jpeg buffer size
480 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700481 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
482 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800483 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
484 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700485 return BAD_VALUE;
486 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700487 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800488 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700489
490 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700491 float scaleFactor = ((float) (width * height)) /
492 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800493 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
494 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700495 if (jpegBufferSize > maxJpegBufferSize) {
496 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700497 }
498
499 return jpegBufferSize;
500}
501
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700502ssize_t Camera3Device::getPointCloudBufferSize() const {
503 const int FLOATS_PER_POINT=4;
504 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
505 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800506 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
507 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700508 return BAD_VALUE;
509 }
510 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
511 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
512 return maxBytesForPointCloud;
513}
514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800515ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800516 const int PER_CONFIGURATION_SIZE = 3;
517 const int WIDTH_OFFSET = 0;
518 const int HEIGHT_OFFSET = 1;
519 const int SIZE_OFFSET = 2;
520 camera_metadata_ro_entry rawOpaqueSizes =
521 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800522 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800523 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800524 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
525 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800526 return BAD_VALUE;
527 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700528
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800529 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
530 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
531 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
532 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
533 }
534 }
535
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
537 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800538 return BAD_VALUE;
539}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700540
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800541status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
542 ATRACE_CALL();
543 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700544
545 // Try to lock, but continue in case of failure (to avoid blocking in
546 // deadlocks)
547 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
548 bool gotLock = tryLockSpinRightRound(mLock);
549
550 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
552 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700553 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
555 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700556
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800557 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700558
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800559 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700560 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800561 int n = args.size();
562 for (int i = 0; i < n; i++) {
563 if (args[i] == templatesOption) {
564 dumpTemplates = true;
565 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700566 if (args[i] == monitorOption) {
567 if (i + 1 < n) {
568 String8 monitorTags = String8(args[i + 1]);
569 if (monitorTags == "off") {
570 mTagMonitor.disableMonitoring();
571 } else {
572 mTagMonitor.parseTagsToMonitor(monitorTags);
573 }
574 } else {
575 mTagMonitor.disableMonitoring();
576 }
577 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800578 }
579
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800580 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800581
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800582 const char *status =
583 mStatus == STATUS_ERROR ? "ERROR" :
584 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700585 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
586 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800587 mStatus == STATUS_ACTIVE ? "ACTIVE" :
588 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800590 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700591 if (mStatus == STATUS_ERROR) {
592 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
593 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800594 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800595 const char *mode =
596 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
597 mOperatingMode == static_cast<int>(
598 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
599 "CUSTOM";
600 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800601
602 if (mInputStream != NULL) {
603 write(fd, lines.string(), lines.size());
604 mInputStream->dump(fd, args);
605 } else {
606 lines.appendFormat(" No input stream.\n");
607 write(fd, lines.string(), lines.size());
608 }
609 for (size_t i = 0; i < mOutputStreams.size(); i++) {
610 mOutputStreams[i]->dump(fd,args);
611 }
612
Zhijun He431503c2016-03-07 17:30:16 -0800613 if (mBufferManager != NULL) {
614 lines = String8(" Camera3 Buffer Manager:\n");
615 write(fd, lines.string(), lines.size());
616 mBufferManager->dump(fd, args);
617 }
Zhijun He125684a2015-12-26 15:07:30 -0800618
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700619 lines = String8(" In-flight requests:\n");
620 if (mInFlightMap.size() == 0) {
621 lines.append(" None\n");
622 } else {
623 for (size_t i = 0; i < mInFlightMap.size(); i++) {
624 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700625 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700626 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800627 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700628 r.numBuffersLeft);
629 }
630 }
631 write(fd, lines.string(), lines.size());
632
Shuzhen Wang686f6442017-06-20 16:16:04 -0700633 if (mRequestThread != NULL) {
634 mRequestThread->dumpCaptureRequestLatency(fd,
635 " ProcessCaptureRequest latency histogram:");
636 }
637
Igor Murashkin1e479c02013-09-06 16:55:14 -0700638 {
639 lines = String8(" Last request sent:\n");
640 write(fd, lines.string(), lines.size());
641
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700642 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700643 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
644 }
645
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800646 if (dumpTemplates) {
647 const char *templateNames[] = {
648 "TEMPLATE_PREVIEW",
649 "TEMPLATE_STILL_CAPTURE",
650 "TEMPLATE_VIDEO_RECORD",
651 "TEMPLATE_VIDEO_SNAPSHOT",
652 "TEMPLATE_ZERO_SHUTTER_LAG",
653 "TEMPLATE_MANUAL"
654 };
655
656 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800657 camera_metadata_t *templateRequest = nullptr;
658 mInterface->constructDefaultRequestSettings(
659 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800660 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800661 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800662 lines.append(" Not supported\n");
663 write(fd, lines.string(), lines.size());
664 } else {
665 write(fd, lines.string(), lines.size());
666 dump_indented_camera_metadata(templateRequest,
667 fd, /*verbosity*/2, /*indentation*/8);
668 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800669 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800670 }
671 }
672
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700673 mTagMonitor.dumpMonitoredMetadata(fd);
674
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800675 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800676 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800678 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800679 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800680
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700681 if (gotLock) mLock.unlock();
682 if (gotInterfaceLock) mInterfaceLock.unlock();
683
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800684 return OK;
685}
686
687const CameraMetadata& Camera3Device::info() const {
688 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800689 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
690 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700691 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800692 mStatus == STATUS_ERROR ?
693 "when in error state" : "before init");
694 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800695 return mDeviceInfo;
696}
697
Jianing Wei90e59c92014-03-12 18:29:36 -0700698status_t Camera3Device::checkStatusOkToCaptureLocked() {
699 switch (mStatus) {
700 case STATUS_ERROR:
701 CLOGE("Device has encountered a serious error");
702 return INVALID_OPERATION;
703 case STATUS_UNINITIALIZED:
704 CLOGE("Device not initialized");
705 return INVALID_OPERATION;
706 case STATUS_UNCONFIGURED:
707 case STATUS_CONFIGURED:
708 case STATUS_ACTIVE:
709 // OK
710 break;
711 default:
712 SET_ERR_L("Unexpected status: %d", mStatus);
713 return INVALID_OPERATION;
714 }
715 return OK;
716}
717
718status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700719 const List<const CameraMetadata> &metadataList,
720 const std::list<const SurfaceMap> &surfaceMaps,
721 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700722 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700723 if (requestList == NULL) {
724 CLOGE("requestList cannot be NULL.");
725 return BAD_VALUE;
726 }
727
Jianing Weicb0652e2014-03-12 18:29:36 -0700728 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700729 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
730 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
731 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
732 ++metadataIt, ++surfaceMapIt) {
733 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700734 if (newRequest == 0) {
735 CLOGE("Can't create capture request");
736 return BAD_VALUE;
737 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700738
Shuzhen Wang9d066012016-09-30 11:30:20 -0700739 newRequest->mRepeating = repeating;
740
Jianing Weicb0652e2014-03-12 18:29:36 -0700741 // Setup burst Id and request Id
742 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700743 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
744 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700745 CLOGE("RequestID entry exists; but must not be empty in metadata");
746 return BAD_VALUE;
747 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700748 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700749 } else {
750 CLOGE("RequestID does not exist in metadata");
751 return BAD_VALUE;
752 }
753
Jianing Wei90e59c92014-03-12 18:29:36 -0700754 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700755
756 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700758 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
759 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
760 return BAD_VALUE;
761 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700762
763 // Setup batch size if this is a high speed video recording request.
764 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
765 auto firstRequest = requestList->begin();
766 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
767 if (outputStream->isVideoStream()) {
768 (*firstRequest)->mBatchSize = requestList->size();
769 break;
770 }
771 }
772 }
773
Jianing Wei90e59c92014-03-12 18:29:36 -0700774 return OK;
775}
776
Jianing Weicb0652e2014-03-12 18:29:36 -0700777status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800778 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800779
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700780 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700781 std::list<const SurfaceMap> surfaceMaps;
782 convertToRequestList(requests, surfaceMaps, request);
783
784 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
785}
786
787void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
788 std::list<const SurfaceMap>& surfaceMaps,
789 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700790 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700791
792 SurfaceMap surfaceMap;
793 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
794 // With no surface list passed in, stream and surface will have 1-to-1
795 // mapping. So the surface index is 0 for each stream in the surfaceMap.
796 for (size_t i = 0; i < streams.count; i++) {
797 surfaceMap[streams.data.i32[i]].push_back(0);
798 }
799 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800800}
801
Jianing Wei90e59c92014-03-12 18:29:36 -0700802status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700803 const List<const CameraMetadata> &requests,
804 const std::list<const SurfaceMap> &surfaceMaps,
805 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700806 /*out*/
807 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700808 ATRACE_CALL();
809 Mutex::Autolock il(mInterfaceLock);
810 Mutex::Autolock l(mLock);
811
812 status_t res = checkStatusOkToCaptureLocked();
813 if (res != OK) {
814 // error logged by previous call
815 return res;
816 }
817
818 RequestList requestList;
819
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
821 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700822 if (res != OK) {
823 // error logged by previous call
824 return res;
825 }
826
827 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700828 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700829 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700830 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 }
832
833 if (res == OK) {
834 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
835 if (res != OK) {
836 SET_ERR_L("Can't transition to active in %f seconds!",
837 kActiveTimeout/1e9);
838 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800839 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700840 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 } else {
842 CLOGE("Cannot queue request. Impossible.");
843 return BAD_VALUE;
844 }
845
846 return res;
847}
848
Yifan Honga640c5a2017-04-12 16:30:31 -0700849// Only one processCaptureResult should be called at a time, so
850// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800851hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800852 const hardware::hidl_vec<
853 hardware::camera::device::V3_2::CaptureResult>& results) {
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700854 {
855 Mutex::Autolock l(mLock);
856 if (mStatus == STATUS_ERROR) {
857 // Per API contract, HAL should act as closed after device error
858 ALOGW("%s: received capture result in error state!", __FUNCTION__);
859 }
860 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700861
862 if (mProcessCaptureResultLock.tryLock() != OK) {
863 // This should never happen; it indicates a wrong client implementation
864 // that doesn't follow the contract. But, we can be tolerant here.
865 ALOGE("%s: callback overlapped! waiting 1s...",
866 __FUNCTION__);
867 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
868 ALOGE("%s: cannot acquire lock in 1s, dropping results",
869 __FUNCTION__);
870 // really don't know what to do, so bail out.
871 return hardware::Void();
872 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800873 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700874 for (const auto& result : results) {
875 processOneCaptureResultLocked(result);
876 }
877 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800878 return hardware::Void();
879}
880
Yifan Honga640c5a2017-04-12 16:30:31 -0700881void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800882 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800883 camera3_capture_result r;
884 status_t res;
885 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700886
887 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
888 if (result.fmqResultSize > 0) {
889 resultMetadata.resize(result.fmqResultSize);
890 if (mResultMetadataQueue == nullptr) {
891 return; // logged in initialize()
892 }
893 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
894 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
895 __FUNCTION__, result.frameNumber, result.fmqResultSize);
896 return;
897 }
898 } else {
899 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
900 result.result.size());
901 }
902
903 if (resultMetadata.size() != 0) {
904 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
905 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800906 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
907 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
908 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800909 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800910 }
911 } else {
912 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800913 }
914
915 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
916 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
917 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
918 auto& bDst = outputBuffers[i];
919 const StreamBuffer &bSrc = result.outputBuffers[i];
920
921 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100922 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800923 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
924 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800925 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926 }
927 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
928
929 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800930 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 if (res != OK) {
932 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
933 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800934 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800935 }
936 bDst.buffer = buffer;
937 bDst.status = mapHidlBufferStatus(bSrc.status);
938 bDst.acquire_fence = -1;
939 if (bSrc.releaseFence == nullptr) {
940 bDst.release_fence = -1;
941 } else if (bSrc.releaseFence->numFds == 1) {
942 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
943 } else {
944 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
945 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800946 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800947 }
948 }
949 r.num_output_buffers = outputBuffers.size();
950 r.output_buffers = outputBuffers.data();
951
952 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800953 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800954 r.input_buffer = nullptr;
955 } else {
956 if (mInputStream->getId() != result.inputBuffer.streamId) {
957 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
958 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800959 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800960 }
961 inputBuffer.stream = mInputStream->asHalStream();
962 buffer_handle_t *buffer;
963 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
964 &buffer);
965 if (res != OK) {
966 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
967 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800968 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800969 }
970 inputBuffer.buffer = buffer;
971 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
972 inputBuffer.acquire_fence = -1;
973 if (result.inputBuffer.releaseFence == nullptr) {
974 inputBuffer.release_fence = -1;
975 } else if (result.inputBuffer.releaseFence->numFds == 1) {
976 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
977 } else {
978 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
979 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800980 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 }
982 r.input_buffer = &inputBuffer;
983 }
984
985 r.partial_result = result.partialResult;
986
987 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800988}
989
990hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800991 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700992 {
993 Mutex::Autolock l(mLock);
994 if (mStatus == STATUS_ERROR) {
995 // Per API contract, HAL should act as closed after device error
996 ALOGW("%s: received notify message in error state!", __FUNCTION__);
997 }
998 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800999 for (const auto& msg : msgs) {
1000 notify(msg);
1001 }
1002 return hardware::Void();
1003}
1004
1005void Camera3Device::notify(
1006 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1007
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001008 camera3_notify_msg m;
1009 switch (msg.type) {
1010 case MsgType::ERROR:
1011 m.type = CAMERA3_MSG_ERROR;
1012 m.message.error.frame_number = msg.msg.error.frameNumber;
1013 if (msg.msg.error.errorStreamId >= 0) {
1014 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001015 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 ALOGE("%s: Frame %d: Invalid error stream id %d",
1017 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001018 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001019 }
1020 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1021 } else {
1022 m.message.error.error_stream = nullptr;
1023 }
1024 switch (msg.msg.error.errorCode) {
1025 case ErrorCode::ERROR_DEVICE:
1026 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1027 break;
1028 case ErrorCode::ERROR_REQUEST:
1029 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1030 break;
1031 case ErrorCode::ERROR_RESULT:
1032 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1033 break;
1034 case ErrorCode::ERROR_BUFFER:
1035 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1036 break;
1037 }
1038 break;
1039 case MsgType::SHUTTER:
1040 m.type = CAMERA3_MSG_SHUTTER;
1041 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1042 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1043 break;
1044 }
1045 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001046}
1047
Jianing Weicb0652e2014-03-12 18:29:36 -07001048status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001049 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001050 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001051 ATRACE_CALL();
1052
Shuzhen Wang0129d522016-10-30 22:43:41 -07001053 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001054}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001055
Jianing Weicb0652e2014-03-12 18:29:36 -07001056status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1057 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001058 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001059
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001060 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 std::list<const SurfaceMap> surfaceMaps;
1062 convertToRequestList(requests, surfaceMaps, request);
1063
1064 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1065 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066}
1067
Jianing Weicb0652e2014-03-12 18:29:36 -07001068status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001069 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001070 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001071 ATRACE_CALL();
1072
Shuzhen Wang0129d522016-10-30 22:43:41 -07001073 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001074}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001075
1076sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001078 status_t res;
1079
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001080 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001081 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1082 // so unilaterally select normal operating mode.
1083 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001084 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001085 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001086 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001087 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001088 } else if (mStatus == STATUS_UNCONFIGURED) {
1089 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001090 CLOGE("No streams configured");
1091 return NULL;
1092 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 }
1094
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001097}
1098
Jianing Weicb0652e2014-03-12 18:29:36 -07001099status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001100 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001101 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001102 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001103
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 switch (mStatus) {
1105 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001106 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 return INVALID_OPERATION;
1108 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001109 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001110 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001111 case STATUS_UNCONFIGURED:
1112 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001113 case STATUS_ACTIVE:
1114 // OK
1115 break;
1116 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001117 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 return INVALID_OPERATION;
1119 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001120 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001121
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001122 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001123}
1124
1125status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1126 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001127 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001128
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001129 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001130}
1131
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001132status_t Camera3Device::createInputStream(
1133 uint32_t width, uint32_t height, int format, int *id) {
1134 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001136 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001137 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1138 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001139
1140 status_t res;
1141 bool wasActive = false;
1142
1143 switch (mStatus) {
1144 case STATUS_ERROR:
1145 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1146 return INVALID_OPERATION;
1147 case STATUS_UNINITIALIZED:
1148 ALOGE("%s: Device not initialized", __FUNCTION__);
1149 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001150 case STATUS_UNCONFIGURED:
1151 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001152 // OK
1153 break;
1154 case STATUS_ACTIVE:
1155 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001156 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001157 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001158 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001159 return res;
1160 }
1161 wasActive = true;
1162 break;
1163 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001164 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001165 return INVALID_OPERATION;
1166 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001167 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001168
1169 if (mInputStream != 0) {
1170 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1171 return INVALID_OPERATION;
1172 }
1173
1174 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1175 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001176 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001177
1178 mInputStream = newStream;
1179
1180 *id = mNextStreamId++;
1181
1182 // Continue captures if active at start
1183 if (wasActive) {
1184 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001185 // Reuse current operating mode for new stream config
1186 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001187 if (res != OK) {
1188 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1189 __FUNCTION__, mNextStreamId, strerror(-res), res);
1190 return res;
1191 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001192 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001193 }
1194
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001195 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196 return OK;
1197}
1198
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001199status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001200 uint32_t width, uint32_t height, int format,
1201 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001202 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001203 ATRACE_CALL();
1204
1205 if (consumer == nullptr) {
1206 ALOGE("%s: consumer must not be null", __FUNCTION__);
1207 return BAD_VALUE;
1208 }
1209
1210 std::vector<sp<Surface>> consumers;
1211 consumers.push_back(consumer);
1212
1213 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001214 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215}
1216
1217status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1218 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1219 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001220 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001222 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001224 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001225 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1226 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001227
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 status_t res;
1229 bool wasActive = false;
1230
1231 switch (mStatus) {
1232 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
1235 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001236 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001238 case STATUS_UNCONFIGURED:
1239 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 // OK
1241 break;
1242 case STATUS_ACTIVE:
1243 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return res;
1248 }
1249 wasActive = true;
1250 break;
1251 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001252 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 return INVALID_OPERATION;
1254 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001255 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256
1257 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001258
Shuzhen Wang0129d522016-10-30 22:43:41 -07001259 if (consumers.size() == 0 && !hasDeferredConsumer) {
1260 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1261 return BAD_VALUE;
1262 }
Zhijun He5d677d12016-05-29 16:52:39 -07001263
Shuzhen Wang0129d522016-10-30 22:43:41 -07001264 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001265 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1266 return BAD_VALUE;
1267 }
1268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001270 ssize_t blobBufferSize;
1271 if (dataSpace != HAL_DATASPACE_DEPTH) {
1272 blobBufferSize = getJpegBufferSize(width, height);
1273 if (blobBufferSize <= 0) {
1274 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1275 return BAD_VALUE;
1276 }
1277 } else {
1278 blobBufferSize = getPointCloudBufferSize();
1279 if (blobBufferSize <= 0) {
1280 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1281 return BAD_VALUE;
1282 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001283 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001284 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001285 width, height, blobBufferSize, format, dataSpace, rotation,
1286 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001287 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1288 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1289 if (rawOpaqueBufferSize <= 0) {
1290 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1291 return BAD_VALUE;
1292 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001293 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001294 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1295 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001296 } else if (isShared) {
1297 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1298 width, height, format, consumerUsage, dataSpace, rotation,
1299 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001300 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001301 newStream = new Camera3OutputStream(mNextStreamId,
1302 width, height, format, consumerUsage, dataSpace, rotation,
1303 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001305 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001306 width, height, format, dataSpace, rotation,
1307 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001309 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310
Emilian Peev08dd2452017-04-06 16:55:14 +01001311 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001312
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001313 res = mOutputStreams.add(mNextStreamId, newStream);
1314 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001315 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001316 return res;
1317 }
1318
1319 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001320 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001321
1322 // Continue captures if active at start
1323 if (wasActive) {
1324 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001325 // Reuse current operating mode for new stream config
1326 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001327 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001328 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1329 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001330 return res;
1331 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001332 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001334 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001336}
1337
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001338status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001339 uint32_t *width, uint32_t *height,
1340 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001342 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 switch (mStatus) {
1346 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001347 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 return INVALID_OPERATION;
1349 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001350 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001352 case STATUS_UNCONFIGURED:
1353 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 case STATUS_ACTIVE:
1355 // OK
1356 break;
1357 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001358 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 return INVALID_OPERATION;
1360 }
1361
1362 ssize_t idx = mOutputStreams.indexOfKey(id);
1363 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001364 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 return idx;
1366 }
1367
1368 if (width) *width = mOutputStreams[idx]->getWidth();
1369 if (height) *height = mOutputStreams[idx]->getHeight();
1370 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001371 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001373}
1374
1375status_t Camera3Device::setStreamTransform(int id,
1376 int transform) {
1377 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001380
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 switch (mStatus) {
1382 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001383 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 return INVALID_OPERATION;
1385 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001386 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 case STATUS_UNCONFIGURED:
1389 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 case STATUS_ACTIVE:
1391 // OK
1392 break;
1393 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001394 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 return INVALID_OPERATION;
1396 }
1397
1398 ssize_t idx = mOutputStreams.indexOfKey(id);
1399 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001400 CLOGE("Stream %d does not exist",
1401 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return BAD_VALUE;
1403 }
1404
1405 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001406}
1407
1408status_t Camera3Device::deleteStream(int id) {
1409 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001410 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 Mutex::Autolock l(mLock);
1412 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001413
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001414 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001415
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 // CameraDevice semantics require device to already be idle before
1417 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001418 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001419 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001420 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 }
1422
Igor Murashkin2fba5842013-04-22 14:03:54 -07001423 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001424 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 if (mInputStream != NULL && id == mInputStream->getId()) {
1426 deletedStream = mInputStream;
1427 mInputStream.clear();
1428 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001429 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001430 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 return BAD_VALUE;
1432 }
Zhijun He5f446352014-01-22 09:49:33 -08001433 }
1434
1435 // Delete output stream or the output part of a bi-directional stream.
1436 if (outputStreamIdx != NAME_NOT_FOUND) {
1437 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 mOutputStreams.removeItem(id);
1439 }
1440
1441 // Free up the stream endpoint so that it can be used by some other stream
1442 res = deletedStream->disconnect();
1443 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001444 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 // fall through since we want to still list the stream as deleted.
1446 }
1447 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001448 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449
1450 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001451}
1452
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001453status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001454 ATRACE_CALL();
1455 ALOGV("%s: E", __FUNCTION__);
1456
1457 Mutex::Autolock il(mInterfaceLock);
1458 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001459
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001460 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001461}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001462
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001463status_t Camera3Device::getInputBufferProducer(
1464 sp<IGraphicBufferProducer> *producer) {
1465 Mutex::Autolock il(mInterfaceLock);
1466 Mutex::Autolock l(mLock);
1467
1468 if (producer == NULL) {
1469 return BAD_VALUE;
1470 } else if (mInputStream == NULL) {
1471 return INVALID_OPERATION;
1472 }
1473
1474 return mInputStream->getInputBufferProducer(producer);
1475}
1476
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477status_t Camera3Device::createDefaultRequest(int templateId,
1478 CameraMetadata *request) {
1479 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001480 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001481
1482 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1483 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1484 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1485 return BAD_VALUE;
1486 }
1487
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 Mutex::Autolock l(mLock);
1490
1491 switch (mStatus) {
1492 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001493 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 return INVALID_OPERATION;
1495 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001496 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001498 case STATUS_UNCONFIGURED:
1499 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 case STATUS_ACTIVE:
1501 // OK
1502 break;
1503 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return INVALID_OPERATION;
1506 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507
Zhijun Hea1530f12014-09-14 12:44:20 -07001508 if (!mRequestTemplateCache[templateId].isEmpty()) {
1509 *request = mRequestTemplateCache[templateId];
1510 return OK;
1511 }
1512
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001513 camera_metadata_t *rawRequest;
1514 status_t res = mInterface->constructDefaultRequestSettings(
1515 (camera3_request_template_t) templateId, &rawRequest);
1516 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001517 ALOGI("%s: template %d is not supported on this camera device",
1518 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001519 return res;
1520 } else if (res != OK) {
1521 CLOGE("Unable to construct request template %d: %s (%d)",
1522 templateId, strerror(-res), res);
1523 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001524 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001525
Emilian Peev71c73a22017-03-21 16:35:51 +00001526 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001527 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001528
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001529 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001530 return OK;
1531}
1532
1533status_t Camera3Device::waitUntilDrained() {
1534 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001537
Zhijun He69a37482014-03-23 18:44:49 -07001538 return waitUntilDrainedLocked();
1539}
1540
1541status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 switch (mStatus) {
1543 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 ALOGV("%s: Already idle", __FUNCTION__);
1546 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 case STATUS_CONFIGURED:
1548 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 case STATUS_ERROR:
1550 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 break;
1553 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001554 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 return INVALID_OPERATION;
1556 }
1557
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001558 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001560 if (res != OK) {
1561 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1562 res);
1563 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564 return res;
1565}
1566
Ruben Brunk183f0562015-08-12 12:55:02 -07001567
1568void Camera3Device::internalUpdateStatusLocked(Status status) {
1569 mStatus = status;
1570 mRecentStatusUpdates.add(mStatus);
1571 mStatusChanged.broadcast();
1572}
1573
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574// Pause to reconfigure
1575status_t Camera3Device::internalPauseAndWaitLocked() {
1576 mRequestThread->setPaused(true);
1577 mPauseStateNotify = true;
1578
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001579 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001580 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1581 if (res != OK) {
1582 SET_ERR_L("Can't idle device in %f seconds!",
1583 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 }
1585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 return res;
1587}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589// Resume after internalPauseAndWaitLocked
1590status_t Camera3Device::internalResumeLocked() {
1591 status_t res;
1592
1593 mRequestThread->setPaused(false);
1594
1595 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1596 if (res != OK) {
1597 SET_ERR_L("Can't transition to active in %f seconds!",
1598 kActiveTimeout/1e9);
1599 }
1600 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001602}
1603
Ruben Brunk183f0562015-08-12 12:55:02 -07001604status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001606
1607 size_t startIndex = 0;
1608 if (mStatusWaiters == 0) {
1609 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1610 // this status list
1611 mRecentStatusUpdates.clear();
1612 } else {
1613 // If other threads are waiting on updates to this status list, set the position of the
1614 // first element that this list will check rather than clearing the list.
1615 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 }
1617
Ruben Brunk183f0562015-08-12 12:55:02 -07001618 mStatusWaiters++;
1619
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 bool stateSeen = false;
1621 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001622 if (active == (mStatus == STATUS_ACTIVE)) {
1623 // Desired state is current
1624 break;
1625 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001626
1627 res = mStatusChanged.waitRelative(mLock, timeout);
1628 if (res != OK) break;
1629
Ruben Brunk183f0562015-08-12 12:55:02 -07001630 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1631 // transitions.
1632 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1633 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1634 __FUNCTION__);
1635
1636 // Encountered desired state since we began waiting
1637 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1639 stateSeen = true;
1640 break;
1641 }
1642 }
1643 } while (!stateSeen);
1644
Ruben Brunk183f0562015-08-12 12:55:02 -07001645 mStatusWaiters--;
1646
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001647 return res;
1648}
1649
1650
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001651status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001653 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001654
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001655 if (listener != NULL && mListener != NULL) {
1656 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1657 }
1658 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001659 mRequestThread->setNotificationListener(listener);
1660 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001661
1662 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663}
1664
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001665bool Camera3Device::willNotify3A() {
1666 return false;
1667}
1668
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001669status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001670 status_t res;
1671 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001673 while (mResultQueue.empty()) {
1674 res = mResultSignal.waitRelative(mOutputLock, timeout);
1675 if (res == TIMED_OUT) {
1676 return res;
1677 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001678 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1679 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001680 return res;
1681 }
1682 }
1683 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001684}
1685
Jianing Weicb0652e2014-03-12 18:29:36 -07001686status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001687 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001688 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001690 if (mResultQueue.empty()) {
1691 return NOT_ENOUGH_DATA;
1692 }
1693
Jianing Weicb0652e2014-03-12 18:29:36 -07001694 if (frame == NULL) {
1695 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1696 return BAD_VALUE;
1697 }
1698
1699 CaptureResult &result = *(mResultQueue.begin());
1700 frame->mResultExtras = result.mResultExtras;
1701 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001702 mResultQueue.erase(mResultQueue.begin());
1703
1704 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001705}
1706
1707status_t Camera3Device::triggerAutofocus(uint32_t id) {
1708 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001709 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001711 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1712 // Mix-in this trigger into the next request and only the next request.
1713 RequestTrigger trigger[] = {
1714 {
1715 ANDROID_CONTROL_AF_TRIGGER,
1716 ANDROID_CONTROL_AF_TRIGGER_START
1717 },
1718 {
1719 ANDROID_CONTROL_AF_TRIGGER_ID,
1720 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001721 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001722 };
1723
1724 return mRequestThread->queueTrigger(trigger,
1725 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001726}
1727
1728status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1729 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001730 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001732 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1733 // Mix-in this trigger into the next request and only the next request.
1734 RequestTrigger trigger[] = {
1735 {
1736 ANDROID_CONTROL_AF_TRIGGER,
1737 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1738 },
1739 {
1740 ANDROID_CONTROL_AF_TRIGGER_ID,
1741 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001742 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001743 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001745 return mRequestThread->queueTrigger(trigger,
1746 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001747}
1748
1749status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1750 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001751 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001753 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1754 // Mix-in this trigger into the next request and only the next request.
1755 RequestTrigger trigger[] = {
1756 {
1757 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1758 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1759 },
1760 {
1761 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1762 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001763 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001764 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001766 return mRequestThread->queueTrigger(trigger,
1767 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001768}
1769
Jianing Weicb0652e2014-03-12 18:29:36 -07001770status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001771 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001772 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001774
Zhijun He7ef20392014-04-21 16:04:17 -07001775 {
1776 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001777 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001778 }
1779
Emilian Peev08dd2452017-04-06 16:55:14 +01001780 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001781}
1782
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001783status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001784 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1785}
1786
1787status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001788 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001789 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001790 Mutex::Autolock il(mInterfaceLock);
1791 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001792
1793 sp<Camera3StreamInterface> stream;
1794 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1795 if (outputStreamIdx == NAME_NOT_FOUND) {
1796 CLOGE("Stream %d does not exist", streamId);
1797 return BAD_VALUE;
1798 }
1799
1800 stream = mOutputStreams.editValueAt(outputStreamIdx);
1801
1802 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001803 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001804 return BAD_VALUE;
1805 }
1806
1807 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001808 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001809 return BAD_VALUE;
1810 }
1811
Ruben Brunkc78ac262015-08-13 17:58:46 -07001812 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001813}
1814
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001815status_t Camera3Device::tearDown(int streamId) {
1816 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001817 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001818 Mutex::Autolock il(mInterfaceLock);
1819 Mutex::Autolock l(mLock);
1820
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001821 sp<Camera3StreamInterface> stream;
1822 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1823 if (outputStreamIdx == NAME_NOT_FOUND) {
1824 CLOGE("Stream %d does not exist", streamId);
1825 return BAD_VALUE;
1826 }
1827
1828 stream = mOutputStreams.editValueAt(outputStreamIdx);
1829
1830 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1831 CLOGE("Stream %d is a target of a in-progress request", streamId);
1832 return BAD_VALUE;
1833 }
1834
1835 return stream->tearDown();
1836}
1837
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001838status_t Camera3Device::addBufferListenerForStream(int streamId,
1839 wp<Camera3StreamBufferListener> listener) {
1840 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001841 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001842 Mutex::Autolock il(mInterfaceLock);
1843 Mutex::Autolock l(mLock);
1844
1845 sp<Camera3StreamInterface> stream;
1846 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1847 if (outputStreamIdx == NAME_NOT_FOUND) {
1848 CLOGE("Stream %d does not exist", streamId);
1849 return BAD_VALUE;
1850 }
1851
1852 stream = mOutputStreams.editValueAt(outputStreamIdx);
1853 stream->addBufferListener(listener);
1854
1855 return OK;
1856}
1857
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001858/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001859 * Methods called by subclasses
1860 */
1861
1862void Camera3Device::notifyStatus(bool idle) {
1863 {
1864 // Need mLock to safely update state and synchronize to current
1865 // state of methods in flight.
1866 Mutex::Autolock l(mLock);
1867 // We can get various system-idle notices from the status tracker
1868 // while starting up. Only care about them if we've actually sent
1869 // in some requests recently.
1870 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1871 return;
1872 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001873 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001875 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876
1877 // Skip notifying listener if we're doing some user-transparent
1878 // state changes
1879 if (mPauseStateNotify) return;
1880 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001881
1882 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001883 {
1884 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001885 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001886 }
1887 if (idle && listener != NULL) {
1888 listener->notifyIdle();
1889 }
1890}
1891
Shuzhen Wang758c2152017-01-10 18:26:18 -08001892status_t Camera3Device::setConsumerSurfaces(int streamId,
1893 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001894 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001895 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1896 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001897 Mutex::Autolock il(mInterfaceLock);
1898 Mutex::Autolock l(mLock);
1899
Shuzhen Wang758c2152017-01-10 18:26:18 -08001900 if (consumers.size() == 0) {
1901 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001902 return BAD_VALUE;
1903 }
1904
1905 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1906 if (idx == NAME_NOT_FOUND) {
1907 CLOGE("Stream %d is unknown", streamId);
1908 return idx;
1909 }
1910 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001911 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001912 if (res != OK) {
1913 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1914 return res;
1915 }
1916
Shuzhen Wang0129d522016-10-30 22:43:41 -07001917 if (stream->isConsumerConfigurationDeferred()) {
1918 if (!stream->isConfiguring()) {
1919 CLOGE("Stream %d was already fully configured.", streamId);
1920 return INVALID_OPERATION;
1921 }
Zhijun He5d677d12016-05-29 16:52:39 -07001922
Shuzhen Wang0129d522016-10-30 22:43:41 -07001923 res = stream->finishConfiguration();
1924 if (res != OK) {
1925 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1926 stream->getId(), strerror(-res), res);
1927 return res;
1928 }
Zhijun He5d677d12016-05-29 16:52:39 -07001929 }
1930
1931 return OK;
1932}
1933
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001934/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001935 * Camera3Device private methods
1936 */
1937
1938sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001939 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001940 ATRACE_CALL();
1941 status_t res;
1942
1943 sp<CaptureRequest> newRequest = new CaptureRequest;
1944 newRequest->mSettings = request;
1945
1946 camera_metadata_entry_t inputStreams =
1947 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1948 if (inputStreams.count > 0) {
1949 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001950 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001951 CLOGE("Request references unknown input stream %d",
1952 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001953 return NULL;
1954 }
1955 // Lazy completion of stream configuration (allocation/registration)
1956 // on first use
1957 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001958 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001959 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001960 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001961 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001962 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001963 return NULL;
1964 }
1965 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001966 // Check if stream is being prepared
1967 if (mInputStream->isPreparing()) {
1968 CLOGE("Request references an input stream that's being prepared!");
1969 return NULL;
1970 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001971
1972 newRequest->mInputStream = mInputStream;
1973 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1974 }
1975
1976 camera_metadata_entry_t streams =
1977 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1978 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001979 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980 return NULL;
1981 }
1982
1983 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001984 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001985 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001986 CLOGE("Request references unknown stream %d",
1987 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988 return NULL;
1989 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001990 sp<Camera3OutputStreamInterface> stream =
1991 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992
Zhijun He5d677d12016-05-29 16:52:39 -07001993 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07001994 auto iter = surfaceMap.find(streams.data.i32[i]);
1995 if (iter != surfaceMap.end()) {
1996 const std::vector<size_t>& surfaces = iter->second;
1997 for (const auto& surface : surfaces) {
1998 if (stream->isConsumerConfigurationDeferred(surface)) {
1999 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2000 "due to deferred consumer", stream->getId(), surface);
2001 return NULL;
2002 }
2003 }
2004 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002005 }
2006
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002007 // Lazy completion of stream configuration (allocation/registration)
2008 // on first use
2009 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002010 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002011 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002012 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2013 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002014 return NULL;
2015 }
2016 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002017 // Check if stream is being prepared
2018 if (stream->isPreparing()) {
2019 CLOGE("Request references an output stream that's being prepared!");
2020 return NULL;
2021 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022
2023 newRequest->mOutputStreams.push(stream);
2024 }
2025 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002026 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027
2028 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029}
2030
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002031bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2032 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2033 Size size = mSupportedOpaqueInputSizes[i];
2034 if (size.width == width && size.height == height) {
2035 return true;
2036 }
2037 }
2038
2039 return false;
2040}
2041
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002042void Camera3Device::cancelStreamsConfigurationLocked() {
2043 int res = OK;
2044 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2045 res = mInputStream->cancelConfiguration();
2046 if (res != OK) {
2047 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2048 mInputStream->getId(), strerror(-res), res);
2049 }
2050 }
2051
2052 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2053 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2054 if (outputStream->isConfiguring()) {
2055 res = outputStream->cancelConfiguration();
2056 if (res != OK) {
2057 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2058 outputStream->getId(), strerror(-res), res);
2059 }
2060 }
2061 }
2062
2063 // Return state to that at start of call, so that future configures
2064 // properly clean things up
2065 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2066 mNeedConfig = true;
2067}
2068
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002069status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002070 ATRACE_CALL();
2071 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002072
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002073 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002074 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 return INVALID_OPERATION;
2076 }
2077
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002078 if (operatingMode < 0) {
2079 CLOGE("Invalid operating mode: %d", operatingMode);
2080 return BAD_VALUE;
2081 }
2082
2083 bool isConstrainedHighSpeed =
2084 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2085 operatingMode;
2086
2087 if (mOperatingMode != operatingMode) {
2088 mNeedConfig = true;
2089 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2090 mOperatingMode = operatingMode;
2091 }
2092
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002093 if (!mNeedConfig) {
2094 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2095 return OK;
2096 }
2097
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002098 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2099 // adding a dummy stream instead.
2100 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2101 if (mOutputStreams.size() == 0) {
2102 addDummyStreamLocked();
2103 } else {
2104 tryRemoveDummyStreamLocked();
2105 }
2106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002108 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109
2110 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002111 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2113
2114 Vector<camera3_stream_t*> streams;
2115 streams.setCapacity(config.num_streams);
2116
2117 if (mInputStream != NULL) {
2118 camera3_stream_t *inputStream;
2119 inputStream = mInputStream->startConfiguration();
2120 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002121 CLOGE("Can't start input stream configuration");
2122 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123 return INVALID_OPERATION;
2124 }
2125 streams.add(inputStream);
2126 }
2127
2128 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002129
2130 // Don't configure bidi streams twice, nor add them twice to the list
2131 if (mOutputStreams[i].get() ==
2132 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2133
2134 config.num_streams--;
2135 continue;
2136 }
2137
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138 camera3_stream_t *outputStream;
2139 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2140 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002141 CLOGE("Can't start output stream configuration");
2142 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143 return INVALID_OPERATION;
2144 }
2145 streams.add(outputStream);
2146 }
2147
2148 config.streams = streams.editArray();
2149
2150 // Do the HAL configuration; will potentially touch stream
2151 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002152
2153 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002154
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002155 if (res == BAD_VALUE) {
2156 // HAL rejected this set of streams as unsupported, clean up config
2157 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002158 CLOGE("Set of requested inputs/outputs not supported by HAL");
2159 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002160 return BAD_VALUE;
2161 } else if (res != OK) {
2162 // Some other kind of error from configure_streams - this is not
2163 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002164 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2165 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166 return res;
2167 }
2168
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002169 // Finish all stream configuration immediately.
2170 // TODO: Try to relax this later back to lazy completion, which should be
2171 // faster
2172
Igor Murashkin073f8572013-05-02 14:59:28 -07002173 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002174 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002175 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002176 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002177 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002178 cancelStreamsConfigurationLocked();
2179 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002180 }
2181 }
2182
2183 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002184 sp<Camera3OutputStreamInterface> outputStream =
2185 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002186 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002187 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002188 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002189 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002190 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002191 cancelStreamsConfigurationLocked();
2192 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002193 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002194 }
2195 }
2196
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002197 // Request thread needs to know to avoid using repeat-last-settings protocol
2198 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002199 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200
Zhijun He90f7c372016-08-16 16:19:43 -07002201 char value[PROPERTY_VALUE_MAX];
2202 property_get("camera.fifo.disable", value, "0");
2203 int32_t disableFifo = atoi(value);
2204 if (disableFifo != 1) {
2205 // Boost priority of request thread to SCHED_FIFO.
2206 pid_t requestThreadTid = mRequestThread->getTid();
2207 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002208 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002209 if (res != OK) {
2210 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2211 strerror(-res), res);
2212 } else {
2213 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2214 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002215 }
2216
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002218
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002219 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220
Ruben Brunk183f0562015-08-12 12:55:02 -07002221 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2222 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002223
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002224 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225
Zhijun He0a210512014-07-24 13:45:15 -07002226 // tear down the deleted streams after configure streams.
2227 mDeletedStreams.clear();
2228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002229 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002230}
2231
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002232status_t Camera3Device::addDummyStreamLocked() {
2233 ATRACE_CALL();
2234 status_t res;
2235
2236 if (mDummyStreamId != NO_STREAM) {
2237 // Should never be adding a second dummy stream when one is already
2238 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002239 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2240 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002241 return INVALID_OPERATION;
2242 }
2243
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002244 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002245
2246 sp<Camera3OutputStreamInterface> dummyStream =
2247 new Camera3DummyStream(mNextStreamId);
2248
2249 res = mOutputStreams.add(mNextStreamId, dummyStream);
2250 if (res < 0) {
2251 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2252 return res;
2253 }
2254
2255 mDummyStreamId = mNextStreamId;
2256 mNextStreamId++;
2257
2258 return OK;
2259}
2260
2261status_t Camera3Device::tryRemoveDummyStreamLocked() {
2262 ATRACE_CALL();
2263 status_t res;
2264
2265 if (mDummyStreamId == NO_STREAM) return OK;
2266 if (mOutputStreams.size() == 1) return OK;
2267
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002268 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002269
2270 // Ok, have a dummy stream and there's at least one other output stream,
2271 // so remove the dummy
2272
2273 sp<Camera3StreamInterface> deletedStream;
2274 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2275 if (outputStreamIdx == NAME_NOT_FOUND) {
2276 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2277 return INVALID_OPERATION;
2278 }
2279
2280 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2281 mOutputStreams.removeItemsAt(outputStreamIdx);
2282
2283 // Free up the stream endpoint so that it can be used by some other stream
2284 res = deletedStream->disconnect();
2285 if (res != OK) {
2286 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2287 // fall through since we want to still list the stream as deleted.
2288 }
2289 mDeletedStreams.add(deletedStream);
2290 mDummyStreamId = NO_STREAM;
2291
2292 return res;
2293}
2294
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002295void Camera3Device::setErrorState(const char *fmt, ...) {
2296 Mutex::Autolock l(mLock);
2297 va_list args;
2298 va_start(args, fmt);
2299
2300 setErrorStateLockedV(fmt, args);
2301
2302 va_end(args);
2303}
2304
2305void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2306 Mutex::Autolock l(mLock);
2307 setErrorStateLockedV(fmt, args);
2308}
2309
2310void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2311 va_list args;
2312 va_start(args, fmt);
2313
2314 setErrorStateLockedV(fmt, args);
2315
2316 va_end(args);
2317}
2318
2319void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002320 // Print out all error messages to log
2321 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002322 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002323
2324 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002325 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002326
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002327 mErrorCause = errorCause;
2328
2329 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002330 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002331
2332 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002333 sp<NotificationListener> listener = mListener.promote();
2334 if (listener != NULL) {
2335 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002336 CaptureResultExtras());
2337 }
2338
2339 // Save stack trace. View by dumping it later.
2340 CameraTraces::saveTrace();
2341 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002342}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343
2344/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002345 * In-flight request management
2346 */
2347
Jianing Weicb0652e2014-03-12 18:29:36 -07002348status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002349 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002350 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002351 ATRACE_CALL();
2352 Mutex::Autolock l(mInFlightLock);
2353
2354 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002355 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002356 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002357 if (res < 0) return res;
2358
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002359 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002360 // hold mLock to prevent race with disconnect
2361 Mutex::Autolock l(mLock);
2362 if (mStatusTracker != nullptr) {
2363 mStatusTracker->markComponentActive(mInFlightStatusId);
2364 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002365 }
2366
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002367 return OK;
2368}
2369
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002370void Camera3Device::returnOutputBuffers(
2371 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2372 nsecs_t timestamp) {
2373 for (size_t i = 0; i < numBuffers; i++)
2374 {
2375 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2376 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2377 // Note: stream may be deallocated at this point, if this buffer was
2378 // the last reference to it.
2379 if (res != OK) {
2380 ALOGE("Can't return buffer to its stream: %s (%d)",
2381 strerror(-res), res);
2382 }
2383 }
2384}
2385
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002386void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2387 mInFlightMap.removeItemsAt(idx, 1);
2388
2389 // Indicate idle inFlightMap to the status tracker
2390 if (mInFlightMap.size() == 0) {
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->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2395 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002396 }
2397}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002398
2399void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2400
2401 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2402 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2403
2404 nsecs_t sensorTimestamp = request.sensorTimestamp;
2405 nsecs_t shutterTimestamp = request.shutterTimestamp;
2406
Emilian Peevc6747862017-06-12 15:57:26 +01002407 bool skipResultMetadata = false;
2408 if (request.requestStatus != OK) {
2409 switch (request.requestStatus) {
2410 case CAMERA3_MSG_ERROR_DEVICE:
2411 case CAMERA3_MSG_ERROR_REQUEST:
2412 case CAMERA3_MSG_ERROR_RESULT:
2413 skipResultMetadata = true;
2414 break;
2415 case CAMERA3_MSG_ERROR_BUFFER:
2416 //Result metadata should return in this case.
2417 skipResultMetadata = false;
2418 break;
2419 default:
2420 SET_ERR("Unknown error message: %d", request.requestStatus);
2421 skipResultMetadata = false;
2422 break;
2423 }
2424 }
2425
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002426 // Check if it's okay to remove the request from InFlightMap:
2427 // In the case of a successful request:
2428 // all input and output buffers, all result metadata, shutter callback
2429 // arrived.
2430 // In the case of a unsuccessful request:
2431 // all input and output buffers arrived.
2432 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002433 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002434 (request.haveResultMetadata && shutterTimestamp != 0))) {
2435 ATRACE_ASYNC_END("frame capture", frameNumber);
2436
Shuzhen Wang403044a2017-02-26 23:29:04 -08002437 // Sanity check - if sensor timestamp matches shutter timestamp in the
2438 // case of request having callback.
2439 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002440 sensorTimestamp != shutterTimestamp) {
2441 SET_ERR("sensor timestamp (%" PRId64
2442 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2443 sensorTimestamp, frameNumber, shutterTimestamp);
2444 }
2445
2446 // for an unsuccessful request, it may have pending output buffers to
2447 // return.
2448 assert(request.requestStatus != OK ||
2449 request.pendingOutputBuffers.size() == 0);
2450 returnOutputBuffers(request.pendingOutputBuffers.array(),
2451 request.pendingOutputBuffers.size(), 0);
2452
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002453 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002454 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2455 }
2456
2457 // Sanity check - if we have too many in-flight frames, something has
2458 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002459 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002460 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002461 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2462 kInFlightWarnLimitHighSpeed) {
2463 CLOGE("In-flight list too large for high speed configuration: %zu",
2464 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002465 }
2466}
2467
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002468void Camera3Device::flushInflightRequests() {
2469 { // First return buffers cached in mInFlightMap
2470 Mutex::Autolock l(mInFlightLock);
2471 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2472 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2473 returnOutputBuffers(request.pendingOutputBuffers.array(),
2474 request.pendingOutputBuffers.size(), 0);
2475 }
2476 mInFlightMap.clear();
2477 }
2478
2479 // Then return all inflight buffers not returned by HAL
2480 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2481 mInterface->getInflightBufferKeys(&inflightKeys);
2482
2483 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2484 for (auto& pair : inflightKeys) {
2485 int32_t frameNumber = pair.first;
2486 int32_t streamId = pair.second;
2487 buffer_handle_t* buffer;
2488 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2489 if (res != OK) {
2490 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2491 __FUNCTION__, frameNumber, streamId);
2492 continue;
2493 }
2494
2495 camera3_stream_buffer_t streamBuffer;
2496 streamBuffer.buffer = buffer;
2497 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2498 streamBuffer.acquire_fence = -1;
2499 streamBuffer.release_fence = -1;
2500 if (streamId == inputStreamId) {
2501 streamBuffer.stream = mInputStream->asHalStream();
2502 res = mInputStream->returnInputBuffer(streamBuffer);
2503 if (res != OK) {
2504 ALOGE("%s: Can't return input buffer for frame %d to"
2505 " its stream:%s (%d)", __FUNCTION__,
2506 frameNumber, strerror(-res), res);
2507 }
2508 } else {
2509 streamBuffer.stream = mOutputStreams.valueFor(streamId)->asHalStream();
2510 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2511 }
2512 }
2513}
2514
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002515void Camera3Device::insertResultLocked(CaptureResult *result,
2516 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002517 if (result == nullptr) return;
2518
Emilian Peev71c73a22017-03-21 16:35:51 +00002519 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2520 result->mMetadata.getAndLock());
2521 set_camera_metadata_vendor_id(meta, mVendorTagId);
2522 result->mMetadata.unlock(meta);
2523
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002524 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2525 (int32_t*)&frameNumber, 1) != OK) {
2526 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2527 return;
2528 }
2529
2530 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2531 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2532 return;
2533 }
2534
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002535 // Valid result, insert into queue
2536 List<CaptureResult>::iterator queuedResult =
2537 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2538 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2539 ", burstId = %" PRId32, __FUNCTION__,
2540 queuedResult->mResultExtras.requestId,
2541 queuedResult->mResultExtras.frameNumber,
2542 queuedResult->mResultExtras.burstId);
2543
2544 mResultSignal.signal();
2545}
2546
2547
2548void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002549 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002550 Mutex::Autolock l(mOutputLock);
2551
2552 CaptureResult captureResult;
2553 captureResult.mResultExtras = resultExtras;
2554 captureResult.mMetadata = partialResult;
2555
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002556 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002557}
2558
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002559
2560void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2561 CaptureResultExtras &resultExtras,
2562 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002563 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002564 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002565 if (pendingMetadata.isEmpty())
2566 return;
2567
2568 Mutex::Autolock l(mOutputLock);
2569
2570 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002571 if (reprocess) {
2572 if (frameNumber < mNextReprocessResultFrameNumber) {
2573 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002574 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002575 frameNumber, mNextReprocessResultFrameNumber);
2576 return;
2577 }
2578 mNextReprocessResultFrameNumber = frameNumber + 1;
2579 } else {
2580 if (frameNumber < mNextResultFrameNumber) {
2581 SET_ERR("Out-of-order capture result metadata submitted! "
2582 "(got frame number %d, expecting %d)",
2583 frameNumber, mNextResultFrameNumber);
2584 return;
2585 }
2586 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002587 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002588
2589 CaptureResult captureResult;
2590 captureResult.mResultExtras = resultExtras;
2591 captureResult.mMetadata = pendingMetadata;
2592
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002593 // Append any previous partials to form a complete result
2594 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2595 captureResult.mMetadata.append(collectedPartialResult);
2596 }
2597
2598 captureResult.mMetadata.sort();
2599
2600 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002601 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2602 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002603 SET_ERR("No timestamp provided by HAL for frame %d!",
2604 frameNumber);
2605 return;
2606 }
2607
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002608 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2609 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2610
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002611 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002612}
2613
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002614/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002615 * Camera HAL device callback methods
2616 */
2617
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002618void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002619 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002620
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002621 status_t res;
2622
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002623 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002624 if (result->result == NULL && result->num_output_buffers == 0 &&
2625 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002626 SET_ERR("No result data provided by HAL for frame %d",
2627 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002628 return;
2629 }
Zhijun He204e3292014-07-14 17:09:23 -07002630
Zhijun He204e3292014-07-14 17:09:23 -07002631 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002632 result->result != NULL &&
2633 result->partial_result != 1) {
2634 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2635 " if partial result is not supported",
2636 frameNumber, result->partial_result);
2637 return;
2638 }
2639
2640 bool isPartialResult = false;
2641 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002642 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002643 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002644
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002645 // Get shutter timestamp and resultExtras from list of in-flight requests,
2646 // where it was added by the shutter notification for this frame. If the
2647 // shutter timestamp isn't received yet, append the output buffers to the
2648 // in-flight request and they will be returned when the shutter timestamp
2649 // arrives. Update the in-flight status and remove the in-flight entry if
2650 // all result data and shutter timestamp have been received.
2651 nsecs_t shutterTimestamp = 0;
2652
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002653 {
2654 Mutex::Autolock l(mInFlightLock);
2655 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2656 if (idx == NAME_NOT_FOUND) {
2657 SET_ERR("Unknown frame number for capture result: %d",
2658 frameNumber);
2659 return;
2660 }
2661 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002662 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2663 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002664 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002665 __FUNCTION__, request.resultExtras.requestId,
2666 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002667 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002668 // Always update the partial count to the latest one if it's not 0
2669 // (buffers only). When framework aggregates adjacent partial results
2670 // into one, the latest partial count will be used.
2671 if (result->partial_result != 0)
2672 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002673
2674 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002675 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002676 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2677 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2678 " the range of [1, %d] when metadata is included in the result",
2679 frameNumber, result->partial_result, mNumPartialResults);
2680 return;
2681 }
2682 isPartialResult = (result->partial_result < mNumPartialResults);
2683 if (isPartialResult) {
2684 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002685 }
2686
Shuzhen Wang4a472662017-02-26 23:29:04 -08002687 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002688 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002689 sendPartialCaptureResult(result->result, request.resultExtras,
2690 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002691 }
2692 }
2693
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002694 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002695 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002696
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002697 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002698 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002699 if (request.haveResultMetadata) {
2700 SET_ERR("Called multiple times with metadata for frame %d",
2701 frameNumber);
2702 return;
2703 }
Zhijun He204e3292014-07-14 17:09:23 -07002704 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002705 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002706 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002707 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002708 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002709 request.haveResultMetadata = true;
2710 }
2711
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002712 uint32_t numBuffersReturned = result->num_output_buffers;
2713 if (result->input_buffer != NULL) {
2714 if (hasInputBufferInRequest) {
2715 numBuffersReturned += 1;
2716 } else {
2717 ALOGW("%s: Input buffer should be NULL if there is no input"
2718 " buffer sent in the request",
2719 __FUNCTION__);
2720 }
2721 }
2722 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723 if (request.numBuffersLeft < 0) {
2724 SET_ERR("Too many buffers returned for frame %d",
2725 frameNumber);
2726 return;
2727 }
2728
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002729 camera_metadata_ro_entry_t entry;
2730 res = find_camera_metadata_ro_entry(result->result,
2731 ANDROID_SENSOR_TIMESTAMP, &entry);
2732 if (res == OK && entry.count == 1) {
2733 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002734 }
2735
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002736 // If shutter event isn't received yet, append the output buffers to
2737 // the in-flight request. Otherwise, return the output buffers to
2738 // streams.
2739 if (shutterTimestamp == 0) {
2740 request.pendingOutputBuffers.appendArray(result->output_buffers,
2741 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002742 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002743 returnOutputBuffers(result->output_buffers,
2744 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002745 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002746
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002747 if (result->result != NULL && !isPartialResult) {
2748 if (shutterTimestamp == 0) {
2749 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002750 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002751 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 CameraMetadata metadata;
2753 metadata = result->result;
2754 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002755 collectedPartialResult, frameNumber,
2756 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002758 }
2759
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002760 removeInFlightRequestIfReadyLocked(idx);
2761 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002762
Zhijun Hef0d962a2014-06-30 10:24:11 -07002763 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002764 if (hasInputBufferInRequest) {
2765 Camera3Stream *stream =
2766 Camera3Stream::cast(result->input_buffer->stream);
2767 res = stream->returnInputBuffer(*(result->input_buffer));
2768 // Note: stream may be deallocated at this point, if this buffer was the
2769 // last reference to it.
2770 if (res != OK) {
2771 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2772 " its stream:%s (%d)", __FUNCTION__,
2773 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002774 }
2775 } else {
2776 ALOGW("%s: Input buffer should be NULL if there is no input"
2777 " buffer sent in the request, skipping input buffer return.",
2778 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002779 }
2780 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002781}
2782
2783void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002784 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002785 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002786 {
2787 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002788 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002789 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002790
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002791 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002792 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002793 return;
2794 }
2795
2796 switch (msg->type) {
2797 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002798 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002799 break;
2800 }
2801 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002802 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002803 break;
2804 }
2805 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002806 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002807 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002808 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002809}
2810
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002811void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002812 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002813
2814 // Map camera HAL error codes to ICameraDeviceCallback error codes
2815 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002816 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002817 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002818 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002819 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002820 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002821 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002822 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002823 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002824 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002825 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002826 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002827 };
2828
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002829 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002830 ((msg.error_code >= 0) &&
2831 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2832 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002833 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002834
2835 int streamId = 0;
2836 if (msg.error_stream != NULL) {
2837 Camera3Stream *stream =
2838 Camera3Stream::cast(msg.error_stream);
2839 streamId = stream->getId();
2840 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002841 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2842 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002843 streamId, msg.error_code);
2844
2845 CaptureResultExtras resultExtras;
2846 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848 // SET_ERR calls notifyError
2849 SET_ERR("Camera HAL reported serious device error");
2850 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002851 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2852 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2853 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002854 {
2855 Mutex::Autolock l(mInFlightLock);
2856 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2857 if (idx >= 0) {
2858 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2859 r.requestStatus = msg.error_code;
2860 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002861 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2862 errorCode) {
2863 // In case of missing result check whether the buffers
2864 // returned. If they returned, then remove inflight
2865 // request.
2866 removeInFlightRequestIfReadyLocked(idx);
2867 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868 } else {
2869 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002870 ALOGE("Camera %s: %s: cannot find in-flight request on "
2871 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002872 resultExtras.frameNumber);
2873 }
2874 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002875 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002876 if (listener != NULL) {
2877 listener->notifyError(errorCode, resultExtras);
2878 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002879 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 }
2881 break;
2882 default:
2883 // SET_ERR calls notifyError
2884 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2885 break;
2886 }
2887}
2888
2889void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002890 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002891 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002892
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002893 // Set timestamp for the request in the in-flight tracking
2894 // and get the request ID to send upstream
2895 {
2896 Mutex::Autolock l(mInFlightLock);
2897 idx = mInFlightMap.indexOfKey(msg.frame_number);
2898 if (idx >= 0) {
2899 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002900
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002901 // Verify ordering of shutter notifications
2902 {
2903 Mutex::Autolock l(mOutputLock);
2904 // TODO: need to track errors for tighter bounds on expected frame number.
2905 if (r.hasInputBuffer) {
2906 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2907 SET_ERR("Shutter notification out-of-order. Expected "
2908 "notification for frame %d, got frame %d",
2909 mNextReprocessShutterFrameNumber, msg.frame_number);
2910 return;
2911 }
2912 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2913 } else {
2914 if (msg.frame_number < mNextShutterFrameNumber) {
2915 SET_ERR("Shutter notification out-of-order. Expected "
2916 "notification for frame %d, got frame %d",
2917 mNextShutterFrameNumber, msg.frame_number);
2918 return;
2919 }
2920 mNextShutterFrameNumber = msg.frame_number + 1;
2921 }
2922 }
2923
Shuzhen Wang4a472662017-02-26 23:29:04 -08002924 r.shutterTimestamp = msg.timestamp;
2925 if (r.hasCallback) {
2926 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002927 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002928 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002929 // Call listener, if any
2930 if (listener != NULL) {
2931 listener->notifyShutter(r.resultExtras, msg.timestamp);
2932 }
2933 // send pending result and buffers
2934 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2935 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002936 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002937 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002938 returnOutputBuffers(r.pendingOutputBuffers.array(),
2939 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2940 r.pendingOutputBuffers.clear();
2941
2942 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002943 }
2944 }
2945 if (idx < 0) {
2946 SET_ERR("Shutter notification for non-existent frame number %d",
2947 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002948 }
2949}
2950
2951
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002952CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002953 ALOGV("%s", __FUNCTION__);
2954
Igor Murashkin1e479c02013-09-06 16:55:14 -07002955 CameraMetadata retVal;
2956
2957 if (mRequestThread != NULL) {
2958 retVal = mRequestThread->getLatestRequest();
2959 }
2960
Igor Murashkin1e479c02013-09-06 16:55:14 -07002961 return retVal;
2962}
2963
Jianing Weicb0652e2014-03-12 18:29:36 -07002964
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002965void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2966 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2967 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2968}
2969
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002970/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002971 * HalInterface inner class methods
2972 */
2973
Yifan Hongf79b5542017-04-11 14:44:25 -07002974Camera3Device::HalInterface::HalInterface(
2975 sp<ICameraDeviceSession> &session,
2976 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002977 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002978 mHidlSession(session),
2979 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002980
2981Camera3Device::HalInterface::HalInterface() :
2982 mHal3Device(nullptr) {}
2983
2984Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002985 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002986 mHidlSession(other.mHidlSession),
2987 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002988
2989bool Camera3Device::HalInterface::valid() {
2990 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2991}
2992
2993void Camera3Device::HalInterface::clear() {
2994 mHal3Device = nullptr;
2995 mHidlSession.clear();
2996}
2997
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002998bool Camera3Device::HalInterface::supportBatchRequest() {
2999 return mHidlSession != nullptr;
3000}
3001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003002status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3003 camera3_request_template_t templateId,
3004 /*out*/ camera_metadata_t **requestTemplate) {
3005 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3006 if (!valid()) return INVALID_OPERATION;
3007 status_t res = OK;
3008
3009 if (mHal3Device != nullptr) {
3010 const camera_metadata *r;
3011 r = mHal3Device->ops->construct_default_request_settings(
3012 mHal3Device, templateId);
3013 if (r == nullptr) return BAD_VALUE;
3014 *requestTemplate = clone_camera_metadata(r);
3015 if (requestTemplate == nullptr) {
3016 ALOGE("%s: Unable to clone camera metadata received from HAL",
3017 __FUNCTION__);
3018 return INVALID_OPERATION;
3019 }
3020 } else {
3021 common::V1_0::Status status;
3022 RequestTemplate id;
3023 switch (templateId) {
3024 case CAMERA3_TEMPLATE_PREVIEW:
3025 id = RequestTemplate::PREVIEW;
3026 break;
3027 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3028 id = RequestTemplate::STILL_CAPTURE;
3029 break;
3030 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3031 id = RequestTemplate::VIDEO_RECORD;
3032 break;
3033 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3034 id = RequestTemplate::VIDEO_SNAPSHOT;
3035 break;
3036 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3037 id = RequestTemplate::ZERO_SHUTTER_LAG;
3038 break;
3039 case CAMERA3_TEMPLATE_MANUAL:
3040 id = RequestTemplate::MANUAL;
3041 break;
3042 default:
3043 // Unknown template ID
3044 return BAD_VALUE;
3045 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003046 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003047 [&status, &requestTemplate]
3048 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3049 status = s;
3050 if (status == common::V1_0::Status::OK) {
3051 const camera_metadata *r =
3052 reinterpret_cast<const camera_metadata_t*>(request.data());
3053 size_t expectedSize = request.size();
3054 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003055 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003056 *requestTemplate = clone_camera_metadata(r);
3057 if (*requestTemplate == nullptr) {
3058 ALOGE("%s: Unable to clone camera metadata received from HAL",
3059 __FUNCTION__);
3060 status = common::V1_0::Status::INTERNAL_ERROR;
3061 }
3062 } else {
3063 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3064 status = common::V1_0::Status::INTERNAL_ERROR;
3065 }
3066 }
3067 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003068 if (!err.isOk()) {
3069 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3070 res = DEAD_OBJECT;
3071 } else {
3072 res = CameraProviderManager::mapToStatusT(status);
3073 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003074 }
3075 return res;
3076}
3077
3078status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3079 ATRACE_NAME("CameraHal::configureStreams");
3080 if (!valid()) return INVALID_OPERATION;
3081 status_t res = OK;
3082
3083 if (mHal3Device != nullptr) {
3084 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3085 } else {
3086 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003087 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088 StreamConfiguration requestedConfiguration;
3089 requestedConfiguration.streams.resize(config->num_streams);
3090 for (size_t i = 0; i < config->num_streams; i++) {
3091 Stream &dst = requestedConfiguration.streams[i];
3092 camera3_stream_t *src = config->streams[i];
3093
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003094 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3095 cam3stream->setBufferFreedListener(this);
3096 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003097 StreamType streamType;
3098 switch (src->stream_type) {
3099 case CAMERA3_STREAM_OUTPUT:
3100 streamType = StreamType::OUTPUT;
3101 break;
3102 case CAMERA3_STREAM_INPUT:
3103 streamType = StreamType::INPUT;
3104 break;
3105 default:
3106 ALOGE("%s: Stream %d: Unsupported stream type %d",
3107 __FUNCTION__, streamId, config->streams[i]->stream_type);
3108 return BAD_VALUE;
3109 }
3110 dst.id = streamId;
3111 dst.streamType = streamType;
3112 dst.width = src->width;
3113 dst.height = src->height;
3114 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003115 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116 dst.dataSpace = mapToHidlDataspace(src->data_space);
3117 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003118
3119 activeStreams.insert(streamId);
3120 // Create Buffer ID map if necessary
3121 if (mBufferIdMaps.count(streamId) == 0) {
3122 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3123 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003124 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003125 // remove BufferIdMap for deleted streams
3126 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3127 int streamId = it->first;
3128 bool active = activeStreams.count(streamId) > 0;
3129 if (!active) {
3130 it = mBufferIdMaps.erase(it);
3131 } else {
3132 ++it;
3133 }
3134 }
3135
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003136 res = mapToStreamConfigurationMode(
3137 (camera3_stream_configuration_mode_t) config->operation_mode,
3138 /*out*/ &requestedConfiguration.operationMode);
3139 if (res != OK) {
3140 return res;
3141 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003142
3143 // Invoke configureStreams
3144
3145 HalStreamConfiguration finalConfiguration;
3146 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003147 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003148 [&status, &finalConfiguration]
3149 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3150 finalConfiguration = halConfiguration;
3151 status = s;
3152 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003153 if (!err.isOk()) {
3154 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3155 return DEAD_OBJECT;
3156 }
3157
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003158 if (status != common::V1_0::Status::OK ) {
3159 return CameraProviderManager::mapToStatusT(status);
3160 }
3161
3162 // And convert output stream configuration from HIDL
3163
3164 for (size_t i = 0; i < config->num_streams; i++) {
3165 camera3_stream_t *dst = config->streams[i];
3166 int streamId = Camera3Stream::cast(dst)->getId();
3167
3168 // Start scan at i, with the assumption that the stream order matches
3169 size_t realIdx = i;
3170 bool found = false;
3171 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3172 if (finalConfiguration.streams[realIdx].id == streamId) {
3173 found = true;
3174 break;
3175 }
3176 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3177 }
3178 if (!found) {
3179 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3180 __FUNCTION__, streamId);
3181 return INVALID_OPERATION;
3182 }
3183 HalStream &src = finalConfiguration.streams[realIdx];
3184
3185 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3186 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3187 if (dst->format != overrideFormat) {
3188 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3189 streamId, dst->format);
3190 }
3191 } else {
3192 // Override allowed with IMPLEMENTATION_DEFINED
3193 dst->format = overrideFormat;
3194 }
3195
3196 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3197 if (src.producerUsage != 0) {
3198 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3199 __FUNCTION__, streamId);
3200 return INVALID_OPERATION;
3201 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003202 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003203 } else {
3204 // OUTPUT
3205 if (src.consumerUsage != 0) {
3206 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3207 __FUNCTION__, streamId);
3208 return INVALID_OPERATION;
3209 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003210 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003211 }
3212 dst->max_buffers = src.maxBuffers;
3213 }
3214 }
3215 return res;
3216}
3217
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003218void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3219 /*out*/device::V3_2::CaptureRequest* captureRequest,
3220 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3221
3222 if (captureRequest == nullptr || handlesCreated == nullptr) {
3223 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3224 __FUNCTION__, captureRequest, handlesCreated);
3225 return;
3226 }
3227
3228 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003229
3230 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003231
3232 {
3233 std::lock_guard<std::mutex> lock(mInflightLock);
3234 if (request->input_buffer != nullptr) {
3235 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3236 buffer_handle_t buf = *(request->input_buffer->buffer);
3237 auto pair = getBufferId(buf, streamId);
3238 bool isNewBuffer = pair.first;
3239 uint64_t bufferId = pair.second;
3240 captureRequest->inputBuffer.streamId = streamId;
3241 captureRequest->inputBuffer.bufferId = bufferId;
3242 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3243 captureRequest->inputBuffer.status = BufferStatus::OK;
3244 native_handle_t *acquireFence = nullptr;
3245 if (request->input_buffer->acquire_fence != -1) {
3246 acquireFence = native_handle_create(1,0);
3247 acquireFence->data[0] = request->input_buffer->acquire_fence;
3248 handlesCreated->push_back(acquireFence);
3249 }
3250 captureRequest->inputBuffer.acquireFence = acquireFence;
3251 captureRequest->inputBuffer.releaseFence = nullptr;
3252
3253 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3254 request->input_buffer->buffer,
3255 request->input_buffer->acquire_fence);
3256 } else {
3257 captureRequest->inputBuffer.streamId = -1;
3258 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3259 }
3260
3261 captureRequest->outputBuffers.resize(request->num_output_buffers);
3262 for (size_t i = 0; i < request->num_output_buffers; i++) {
3263 const camera3_stream_buffer_t *src = request->output_buffers + i;
3264 StreamBuffer &dst = captureRequest->outputBuffers[i];
3265 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3266 buffer_handle_t buf = *(src->buffer);
3267 auto pair = getBufferId(buf, streamId);
3268 bool isNewBuffer = pair.first;
3269 dst.streamId = streamId;
3270 dst.bufferId = pair.second;
3271 dst.buffer = isNewBuffer ? buf : nullptr;
3272 dst.status = BufferStatus::OK;
3273 native_handle_t *acquireFence = nullptr;
3274 if (src->acquire_fence != -1) {
3275 acquireFence = native_handle_create(1,0);
3276 acquireFence->data[0] = src->acquire_fence;
3277 handlesCreated->push_back(acquireFence);
3278 }
3279 dst.acquireFence = acquireFence;
3280 dst.releaseFence = nullptr;
3281
3282 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3283 src->buffer, src->acquire_fence);
3284 }
3285 }
3286}
3287
3288status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3289 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3290 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3291 if (!valid()) return INVALID_OPERATION;
3292
3293 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3294 size_t batchSize = requests.size();
3295 captureRequests.resize(batchSize);
3296 std::vector<native_handle_t*> handlesCreated;
3297
3298 for (size_t i = 0; i < batchSize; i++) {
3299 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3300 }
3301
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003302 std::vector<device::V3_2::BufferCache> cachesToRemove;
3303 {
3304 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3305 for (auto& pair : mFreedBuffers) {
3306 // The stream might have been removed since onBufferFreed
3307 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3308 cachesToRemove.push_back({pair.first, pair.second});
3309 }
3310 }
3311 mFreedBuffers.clear();
3312 }
3313
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003314 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3315 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003316
3317 // Write metadata to FMQ.
3318 for (size_t i = 0; i < batchSize; i++) {
3319 camera3_capture_request_t* request = requests[i];
3320 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3321
3322 if (request->settings != nullptr) {
3323 size_t settingsSize = get_camera_metadata_size(request->settings);
3324 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3325 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3326 captureRequest->settings.resize(0);
3327 captureRequest->fmqSettingsSize = settingsSize;
3328 } else {
3329 if (mRequestMetadataQueue != nullptr) {
3330 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3331 }
3332 captureRequest->settings.setToExternal(
3333 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3334 get_camera_metadata_size(request->settings));
3335 captureRequest->fmqSettingsSize = 0u;
3336 }
3337 } else {
3338 // A null request settings maps to a size-0 CameraMetadata
3339 captureRequest->settings.resize(0);
3340 captureRequest->fmqSettingsSize = 0u;
3341 }
3342 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003343 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003344 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3345 status = s;
3346 *numRequestProcessed = n;
3347 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003348 if (!err.isOk()) {
3349 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3350 return DEAD_OBJECT;
3351 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003352 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3353 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3354 __FUNCTION__, *numRequestProcessed, batchSize);
3355 status = common::V1_0::Status::INTERNAL_ERROR;
3356 }
3357
3358 for (auto& handle : handlesCreated) {
3359 native_handle_delete(handle);
3360 }
3361 return CameraProviderManager::mapToStatusT(status);
3362}
3363
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003364status_t Camera3Device::HalInterface::processCaptureRequest(
3365 camera3_capture_request_t *request) {
3366 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003367 if (!valid()) return INVALID_OPERATION;
3368 status_t res = OK;
3369
3370 if (mHal3Device != nullptr) {
3371 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3372 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003373 uint32_t numRequestProcessed = 0;
3374 std::vector<camera3_capture_request_t*> requests(1);
3375 requests[0] = request;
3376 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003377 }
3378 return res;
3379}
3380
3381status_t Camera3Device::HalInterface::flush() {
3382 ATRACE_NAME("CameraHal::flush");
3383 if (!valid()) return INVALID_OPERATION;
3384 status_t res = OK;
3385
3386 if (mHal3Device != nullptr) {
3387 res = mHal3Device->ops->flush(mHal3Device);
3388 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003389 auto err = mHidlSession->flush();
3390 if (!err.isOk()) {
3391 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3392 res = DEAD_OBJECT;
3393 } else {
3394 res = CameraProviderManager::mapToStatusT(err);
3395 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003396 }
3397 return res;
3398}
3399
3400status_t Camera3Device::HalInterface::dump(int fd) {
3401 ATRACE_NAME("CameraHal::dump");
3402 if (!valid()) return INVALID_OPERATION;
3403 status_t res = OK;
3404
3405 if (mHal3Device != nullptr) {
3406 mHal3Device->ops->dump(mHal3Device, fd);
3407 } else {
3408 // Handled by CameraProviderManager::dump
3409 }
3410 return res;
3411}
3412
3413status_t Camera3Device::HalInterface::close() {
3414 ATRACE_NAME("CameraHal::close()");
3415 if (!valid()) return INVALID_OPERATION;
3416 status_t res = OK;
3417
3418 if (mHal3Device != nullptr) {
3419 mHal3Device->common.close(&mHal3Device->common);
3420 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003421 auto err = mHidlSession->close();
3422 // Interface will be dead shortly anyway, so don't log errors
3423 if (!err.isOk()) {
3424 res = DEAD_OBJECT;
3425 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003426 }
3427 return res;
3428}
3429
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003430void Camera3Device::HalInterface::getInflightBufferKeys(
3431 std::vector<std::pair<int32_t, int32_t>>* out) {
3432 std::lock_guard<std::mutex> lock(mInflightLock);
3433 out->clear();
3434 out->reserve(mInflightBufferMap.size());
3435 for (auto& pair : mInflightBufferMap) {
3436 uint64_t key = pair.first;
3437 int32_t streamId = key & 0xFFFFFFFF;
3438 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3439 out->push_back(std::make_pair(frameNumber, streamId));
3440 }
3441 return;
3442}
3443
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003444status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003445 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003446 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003447 auto pair = std::make_pair(buffer, acquireFence);
3448 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003449 return OK;
3450}
3451
3452status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003453 int32_t frameNumber, int32_t streamId,
3454 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003455 std::lock_guard<std::mutex> lock(mInflightLock);
3456
3457 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3458 auto it = mInflightBufferMap.find(key);
3459 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003460 auto pair = it->second;
3461 *buffer = pair.first;
3462 int acquireFence = pair.second;
3463 if (acquireFence > 0) {
3464 ::close(acquireFence);
3465 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003466 mInflightBufferMap.erase(it);
3467 return OK;
3468}
3469
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003470std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3471 const buffer_handle_t& buf, int streamId) {
3472 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3473
3474 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3475 auto it = bIdMap.find(buf);
3476 if (it == bIdMap.end()) {
3477 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003478 ALOGV("stream %d now have %zu buffer caches, buf %p",
3479 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003480 return std::make_pair(true, mNextBufferId - 1);
3481 } else {
3482 return std::make_pair(false, it->second);
3483 }
3484}
3485
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003486void Camera3Device::HalInterface::onBufferFreed(
3487 int streamId, const native_handle_t* handle) {
3488 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3489 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3490 auto mapIt = mBufferIdMaps.find(streamId);
3491 if (mapIt == mBufferIdMaps.end()) {
3492 // streamId might be from a deleted stream here
3493 ALOGI("%s: stream %d has been removed",
3494 __FUNCTION__, streamId);
3495 return;
3496 }
3497 BufferIdMap& bIdMap = mapIt->second;
3498 auto it = bIdMap.find(handle);
3499 if (it == bIdMap.end()) {
3500 ALOGW("%s: cannot find buffer %p in stream %d",
3501 __FUNCTION__, handle, streamId);
3502 return;
3503 } else {
3504 bufferId = it->second;
3505 bIdMap.erase(it);
3506 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3507 __FUNCTION__, streamId, bIdMap.size(), handle);
3508 }
3509 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3510}
3511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003512/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003513 * RequestThread inner class methods
3514 */
3515
3516Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003517 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003518 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003519 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003520 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003521 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003522 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003523 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003524 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003525 mReconfigured(false),
3526 mDoPause(false),
3527 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003528 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003529 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003530 mCurrentAfTriggerId(0),
3531 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003532 mRepeatingLastFrameNumber(
3533 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003534 mPrepareVideoStream(false),
3535 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003536 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003537}
3538
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003539Camera3Device::RequestThread::~RequestThread() {}
3540
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003541void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003542 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003543 Mutex::Autolock l(mRequestLock);
3544 mListener = listener;
3545}
3546
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003547void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003548 Mutex::Autolock l(mRequestLock);
3549 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003550 // Prepare video stream for high speed recording.
3551 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003552}
3553
Jianing Wei90e59c92014-03-12 18:29:36 -07003554status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003555 List<sp<CaptureRequest> > &requests,
3556 /*out*/
3557 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003558 Mutex::Autolock l(mRequestLock);
3559 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3560 ++it) {
3561 mRequestQueue.push_back(*it);
3562 }
3563
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003564 if (lastFrameNumber != NULL) {
3565 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3566 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3567 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3568 *lastFrameNumber);
3569 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003570
Jianing Wei90e59c92014-03-12 18:29:36 -07003571 unpauseForNewRequests();
3572
3573 return OK;
3574}
3575
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003576
3577status_t Camera3Device::RequestThread::queueTrigger(
3578 RequestTrigger trigger[],
3579 size_t count) {
3580
3581 Mutex::Autolock l(mTriggerMutex);
3582 status_t ret;
3583
3584 for (size_t i = 0; i < count; ++i) {
3585 ret = queueTriggerLocked(trigger[i]);
3586
3587 if (ret != OK) {
3588 return ret;
3589 }
3590 }
3591
3592 return OK;
3593}
3594
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003595const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3596 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003597 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003598 if (d != nullptr) return d->mId;
3599 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003600}
3601
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003602status_t Camera3Device::RequestThread::queueTriggerLocked(
3603 RequestTrigger trigger) {
3604
3605 uint32_t tag = trigger.metadataTag;
3606 ssize_t index = mTriggerMap.indexOfKey(tag);
3607
3608 switch (trigger.getTagType()) {
3609 case TYPE_BYTE:
3610 // fall-through
3611 case TYPE_INT32:
3612 break;
3613 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003614 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3615 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003616 return INVALID_OPERATION;
3617 }
3618
3619 /**
3620 * Collect only the latest trigger, since we only have 1 field
3621 * in the request settings per trigger tag, and can't send more than 1
3622 * trigger per request.
3623 */
3624 if (index != NAME_NOT_FOUND) {
3625 mTriggerMap.editValueAt(index) = trigger;
3626 } else {
3627 mTriggerMap.add(tag, trigger);
3628 }
3629
3630 return OK;
3631}
3632
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003633status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003634 const RequestList &requests,
3635 /*out*/
3636 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003637 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003638 if (lastFrameNumber != NULL) {
3639 *lastFrameNumber = mRepeatingLastFrameNumber;
3640 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003641 mRepeatingRequests.clear();
3642 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3643 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003644
3645 unpauseForNewRequests();
3646
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003647 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003648 return OK;
3649}
3650
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003651bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003652 if (mRepeatingRequests.empty()) {
3653 return false;
3654 }
3655 int32_t requestId = requestIn->mResultExtras.requestId;
3656 const RequestList &repeatRequests = mRepeatingRequests;
3657 // All repeating requests are guaranteed to have same id so only check first quest
3658 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3659 return (firstRequest->mResultExtras.requestId == requestId);
3660}
3661
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003662status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003663 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003664 return clearRepeatingRequestsLocked(lastFrameNumber);
3665
3666}
3667
3668status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003669 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003670 if (lastFrameNumber != NULL) {
3671 *lastFrameNumber = mRepeatingLastFrameNumber;
3672 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003673 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003674 return OK;
3675}
3676
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003677status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003678 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003679 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003680 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003681
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003682 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003683
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003684 // Send errors for all requests pending in the request queue, including
3685 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003686 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003687 if (listener != NULL) {
3688 for (RequestList::iterator it = mRequestQueue.begin();
3689 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003690 // Abort the input buffers for reprocess requests.
3691 if ((*it)->mInputStream != NULL) {
3692 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003693 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3694 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003695 if (res != OK) {
3696 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3697 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3698 } else {
3699 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3700 if (res != OK) {
3701 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3702 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3703 }
3704 }
3705 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003706 // Set the frame number this request would have had, if it
3707 // had been submitted; this frame number will not be reused.
3708 // The requestId and burstId fields were set when the request was
3709 // submitted originally (in convertMetadataListToRequestListLocked)
3710 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003713 }
3714 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003715 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003716
3717 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003718 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003719 if (lastFrameNumber != NULL) {
3720 *lastFrameNumber = mRepeatingLastFrameNumber;
3721 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003722 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003723 return OK;
3724}
3725
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003726status_t Camera3Device::RequestThread::flush() {
3727 ATRACE_CALL();
3728 Mutex::Autolock l(mFlushLock);
3729
Emilian Peev08dd2452017-04-06 16:55:14 +01003730 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003731}
3732
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003733void Camera3Device::RequestThread::setPaused(bool paused) {
3734 Mutex::Autolock l(mPauseLock);
3735 mDoPause = paused;
3736 mDoPauseSignal.signal();
3737}
3738
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003739status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3740 int32_t requestId, nsecs_t timeout) {
3741 Mutex::Autolock l(mLatestRequestMutex);
3742 status_t res;
3743 while (mLatestRequestId != requestId) {
3744 nsecs_t startTime = systemTime();
3745
3746 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3747 if (res != OK) return res;
3748
3749 timeout -= (systemTime() - startTime);
3750 }
3751
3752 return OK;
3753}
3754
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003755void Camera3Device::RequestThread::requestExit() {
3756 // Call parent to set up shutdown
3757 Thread::requestExit();
3758 // The exit from any possible waits
3759 mDoPauseSignal.signal();
3760 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003761
3762 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3763 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003764}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003765
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003766void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003767 bool surfaceAbandoned = false;
3768 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003769 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003770 {
3771 Mutex::Autolock l(mRequestLock);
3772 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3773 // repeating requests.
3774 for (const auto& request : mRepeatingRequests) {
3775 for (const auto& s : request->mOutputStreams) {
3776 if (s->isAbandoned()) {
3777 surfaceAbandoned = true;
3778 clearRepeatingRequestsLocked(&lastFrameNumber);
3779 break;
3780 }
3781 }
3782 if (surfaceAbandoned) {
3783 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003784 }
3785 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003786 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003787 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003788
3789 if (listener != NULL && surfaceAbandoned) {
3790 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003791 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003792}
3793
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003794bool Camera3Device::RequestThread::sendRequestsBatch() {
3795 status_t res;
3796 size_t batchSize = mNextRequests.size();
3797 std::vector<camera3_capture_request_t*> requests(batchSize);
3798 uint32_t numRequestProcessed = 0;
3799 for (size_t i = 0; i < batchSize; i++) {
3800 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3801 }
3802
3803 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3804 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3805
3806 bool triggerRemoveFailed = false;
3807 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3808 for (size_t i = 0; i < numRequestProcessed; i++) {
3809 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3810 nextRequest.submitted = true;
3811
3812
3813 // Update the latest request sent to HAL
3814 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3815 Mutex::Autolock al(mLatestRequestMutex);
3816
3817 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3818 mLatestRequest.acquire(cloned);
3819
3820 sp<Camera3Device> parent = mParent.promote();
3821 if (parent != NULL) {
3822 parent->monitorMetadata(TagMonitor::REQUEST,
3823 nextRequest.halRequest.frame_number,
3824 0, mLatestRequest);
3825 }
3826 }
3827
3828 if (nextRequest.halRequest.settings != NULL) {
3829 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3830 }
3831
3832 if (!triggerRemoveFailed) {
3833 // Remove any previously queued triggers (after unlock)
3834 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3835 if (removeTriggerRes != OK) {
3836 triggerRemoveFailed = true;
3837 triggerFailedRequest = nextRequest;
3838 }
3839 }
3840 }
3841
3842 if (triggerRemoveFailed) {
3843 SET_ERR("RequestThread: Unable to remove triggers "
3844 "(capture request %d, HAL device: %s (%d)",
3845 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3846 cleanUpFailedRequests(/*sendRequestError*/ false);
3847 return false;
3848 }
3849
3850 if (res != OK) {
3851 // Should only get a failure here for malformed requests or device-level
3852 // errors, so consider all errors fatal. Bad metadata failures should
3853 // come through notify.
3854 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3855 mNextRequests[numRequestProcessed].halRequest.frame_number,
3856 strerror(-res), res);
3857 cleanUpFailedRequests(/*sendRequestError*/ false);
3858 return false;
3859 }
3860 return true;
3861}
3862
3863bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3864 status_t res;
3865
3866 for (auto& nextRequest : mNextRequests) {
3867 // Submit request and block until ready for next one
3868 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3869 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3870
3871 if (res != OK) {
3872 // Should only get a failure here for malformed requests or device-level
3873 // errors, so consider all errors fatal. Bad metadata failures should
3874 // come through notify.
3875 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3876 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3877 res);
3878 cleanUpFailedRequests(/*sendRequestError*/ false);
3879 return false;
3880 }
3881
3882 // Mark that the request has be submitted successfully.
3883 nextRequest.submitted = true;
3884
3885 // Update the latest request sent to HAL
3886 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3887 Mutex::Autolock al(mLatestRequestMutex);
3888
3889 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3890 mLatestRequest.acquire(cloned);
3891
3892 sp<Camera3Device> parent = mParent.promote();
3893 if (parent != NULL) {
3894 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3895 0, mLatestRequest);
3896 }
3897 }
3898
3899 if (nextRequest.halRequest.settings != NULL) {
3900 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3901 }
3902
3903 // Remove any previously queued triggers (after unlock)
3904 res = removeTriggers(mPrevRequest);
3905 if (res != OK) {
3906 SET_ERR("RequestThread: Unable to remove triggers "
3907 "(capture request %d, HAL device: %s (%d)",
3908 nextRequest.halRequest.frame_number, strerror(-res), res);
3909 cleanUpFailedRequests(/*sendRequestError*/ false);
3910 return false;
3911 }
3912 }
3913 return true;
3914}
3915
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003916bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003917 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003918 status_t res;
3919
3920 // Handle paused state.
3921 if (waitIfPaused()) {
3922 return true;
3923 }
3924
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003925 // Wait for the next batch of requests.
3926 waitForNextRequestBatch();
3927 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003928 return true;
3929 }
3930
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003931 // Get the latest request ID, if any
3932 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003933 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003934 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003935 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003936 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003937 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003938 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3939 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003940 }
3941
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003942 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003943 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003944 if (res == TIMED_OUT) {
3945 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003946 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003947 // Check if any stream is abandoned.
3948 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003949 return true;
3950 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003951 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003952 return false;
3953 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003954
Zhijun Hecc27e112013-10-03 16:12:43 -07003955 // Inform waitUntilRequestProcessed thread of a new request ID
3956 {
3957 Mutex::Autolock al(mLatestRequestMutex);
3958
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003959 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003960 mLatestRequestSignal.signal();
3961 }
3962
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003963 // Submit a batch of requests to HAL.
3964 // Use flush lock only when submitting multilple requests in a batch.
3965 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3966 // which may take a long time to finish so synchronizing flush() and
3967 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3968 // For now, only synchronize for high speed recording and we should figure something out for
3969 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003970 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003971
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003972 if (useFlushLock) {
3973 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003974 }
3975
Zhijun Hef0645c12016-08-02 00:58:11 -07003976 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003977 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003978
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003979 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003980 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003981 if (mInterface->supportBatchRequest()) {
3982 submitRequestSuccess = sendRequestsBatch();
3983 } else {
3984 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003985 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07003986 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3987 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003988
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003989 if (useFlushLock) {
3990 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003991 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003992
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003993 // Unset as current request
3994 {
3995 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003996 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003997 }
3998
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003999 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004000}
4001
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004002status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004003 ATRACE_CALL();
4004
Shuzhen Wang4a472662017-02-26 23:29:04 -08004005 for (size_t i = 0; i < mNextRequests.size(); i++) {
4006 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004007 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4008 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4009 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4010
4011 // Prepare a request to HAL
4012 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4013
4014 // Insert any queued triggers (before metadata is locked)
4015 status_t res = insertTriggers(captureRequest);
4016
4017 if (res < 0) {
4018 SET_ERR("RequestThread: Unable to insert triggers "
4019 "(capture request %d, HAL device: %s (%d)",
4020 halRequest->frame_number, strerror(-res), res);
4021 return INVALID_OPERATION;
4022 }
4023 int triggerCount = res;
4024 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4025 mPrevTriggers = triggerCount;
4026
4027 // If the request is the same as last, or we had triggers last time
4028 if (mPrevRequest != captureRequest || triggersMixedIn) {
4029 /**
4030 * HAL workaround:
4031 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4032 */
4033 res = addDummyTriggerIds(captureRequest);
4034 if (res != OK) {
4035 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4036 "(capture request %d, HAL device: %s (%d)",
4037 halRequest->frame_number, strerror(-res), res);
4038 return INVALID_OPERATION;
4039 }
4040
4041 /**
4042 * The request should be presorted so accesses in HAL
4043 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4044 */
4045 captureRequest->mSettings.sort();
4046 halRequest->settings = captureRequest->mSettings.getAndLock();
4047 mPrevRequest = captureRequest;
4048 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4049
4050 IF_ALOGV() {
4051 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4052 find_camera_metadata_ro_entry(
4053 halRequest->settings,
4054 ANDROID_CONTROL_AF_TRIGGER,
4055 &e
4056 );
4057 if (e.count > 0) {
4058 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4059 __FUNCTION__,
4060 halRequest->frame_number,
4061 e.data.u8[0]);
4062 }
4063 }
4064 } else {
4065 // leave request.settings NULL to indicate 'reuse latest given'
4066 ALOGVV("%s: Request settings are REUSED",
4067 __FUNCTION__);
4068 }
4069
4070 uint32_t totalNumBuffers = 0;
4071
4072 // Fill in buffers
4073 if (captureRequest->mInputStream != NULL) {
4074 halRequest->input_buffer = &captureRequest->mInputBuffer;
4075 totalNumBuffers += 1;
4076 } else {
4077 halRequest->input_buffer = NULL;
4078 }
4079
4080 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4081 captureRequest->mOutputStreams.size());
4082 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004083 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4084 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004085
4086 // Prepare video buffers for high speed recording on the first video request.
4087 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4088 // Only try to prepare video stream on the first video request.
4089 mPrepareVideoStream = false;
4090
4091 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4092 while (res == NOT_ENOUGH_DATA) {
4093 res = outputStream->prepareNextBuffer();
4094 }
4095 if (res != OK) {
4096 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4097 __FUNCTION__, strerror(-res), res);
4098 outputStream->cancelPrepare();
4099 }
4100 }
4101
Shuzhen Wang4a472662017-02-26 23:29:04 -08004102 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4103 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004104 if (res != OK) {
4105 // Can't get output buffer from gralloc queue - this could be due to
4106 // abandoned queue or other consumer misbehavior, so not a fatal
4107 // error
4108 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4109 " %s (%d)", strerror(-res), res);
4110
4111 return TIMED_OUT;
4112 }
4113 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004114
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004115 }
4116 totalNumBuffers += halRequest->num_output_buffers;
4117
4118 // Log request in the in-flight queue
4119 sp<Camera3Device> parent = mParent.promote();
4120 if (parent == NULL) {
4121 // Should not happen, and nowhere to send errors to, so just log it
4122 CLOGE("RequestThread: Parent is gone");
4123 return INVALID_OPERATION;
4124 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004125
4126 // If this request list is for constrained high speed recording (not
4127 // preview), and the current request is not the last one in the batch,
4128 // do not send callback to the app.
4129 bool hasCallback = true;
4130 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4131 hasCallback = false;
4132 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004133 res = parent->registerInFlight(halRequest->frame_number,
4134 totalNumBuffers, captureRequest->mResultExtras,
4135 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004136 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004137 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4138 ", burstId = %" PRId32 ".",
4139 __FUNCTION__,
4140 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4141 captureRequest->mResultExtras.burstId);
4142 if (res != OK) {
4143 SET_ERR("RequestThread: Unable to register new in-flight request:"
4144 " %s (%d)", strerror(-res), res);
4145 return INVALID_OPERATION;
4146 }
4147 }
4148
4149 return OK;
4150}
4151
Igor Murashkin1e479c02013-09-06 16:55:14 -07004152CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4153 Mutex::Autolock al(mLatestRequestMutex);
4154
4155 ALOGV("RequestThread::%s", __FUNCTION__);
4156
4157 return mLatestRequest;
4158}
4159
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004160bool Camera3Device::RequestThread::isStreamPending(
4161 sp<Camera3StreamInterface>& stream) {
4162 Mutex::Autolock l(mRequestLock);
4163
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004164 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004165 if (!nextRequest.submitted) {
4166 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4167 if (stream == s) return true;
4168 }
4169 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004170 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004171 }
4172
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004173 for (const auto& request : mRequestQueue) {
4174 for (const auto& s : request->mOutputStreams) {
4175 if (stream == s) return true;
4176 }
4177 if (stream == request->mInputStream) return true;
4178 }
4179
4180 for (const auto& request : mRepeatingRequests) {
4181 for (const auto& s : request->mOutputStreams) {
4182 if (stream == s) return true;
4183 }
4184 if (stream == request->mInputStream) return true;
4185 }
4186
4187 return false;
4188}
Jianing Weicb0652e2014-03-12 18:29:36 -07004189
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004190void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4191 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004192 return;
4193 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004194
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004195 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004196 // Skip the ones that have been submitted successfully.
4197 if (nextRequest.submitted) {
4198 continue;
4199 }
4200
4201 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4202 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4203 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4204
4205 if (halRequest->settings != NULL) {
4206 captureRequest->mSettings.unlock(halRequest->settings);
4207 }
4208
4209 if (captureRequest->mInputStream != NULL) {
4210 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4211 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4212 }
4213
4214 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004215 //Buffers that failed processing could still have
4216 //valid acquire fence.
4217 int acquireFence = (*outputBuffers)[i].acquire_fence;
4218 if (0 <= acquireFence) {
4219 close(acquireFence);
4220 outputBuffers->editItemAt(i).acquire_fence = -1;
4221 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4223 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4224 }
4225
4226 if (sendRequestError) {
4227 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004228 sp<NotificationListener> listener = mListener.promote();
4229 if (listener != NULL) {
4230 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004231 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004232 captureRequest->mResultExtras);
4233 }
4234 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004235
4236 // Remove yet-to-be submitted inflight request from inflightMap
4237 {
4238 sp<Camera3Device> parent = mParent.promote();
4239 if (parent != NULL) {
4240 Mutex::Autolock l(parent->mInFlightLock);
4241 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4242 if (idx >= 0) {
4243 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4244 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4245 parent->removeInFlightMapEntryLocked(idx);
4246 }
4247 }
4248 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004249 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004250
4251 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004252 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004253}
4254
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004255void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 // Optimized a bit for the simple steady-state case (single repeating
4257 // request), to avoid putting that request in the queue temporarily.
4258 Mutex::Autolock l(mRequestLock);
4259
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004260 assert(mNextRequests.empty());
4261
4262 NextRequest nextRequest;
4263 nextRequest.captureRequest = waitForNextRequestLocked();
4264 if (nextRequest.captureRequest == nullptr) {
4265 return;
4266 }
4267
4268 nextRequest.halRequest = camera3_capture_request_t();
4269 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004270 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271
4272 // Wait for additional requests
4273 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4274
4275 for (size_t i = 1; i < batchSize; i++) {
4276 NextRequest additionalRequest;
4277 additionalRequest.captureRequest = waitForNextRequestLocked();
4278 if (additionalRequest.captureRequest == nullptr) {
4279 break;
4280 }
4281
4282 additionalRequest.halRequest = camera3_capture_request_t();
4283 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004284 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004285 }
4286
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004287 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004288 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004289 mNextRequests.size(), batchSize);
4290 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004291 }
4292
4293 return;
4294}
4295
4296sp<Camera3Device::CaptureRequest>
4297 Camera3Device::RequestThread::waitForNextRequestLocked() {
4298 status_t res;
4299 sp<CaptureRequest> nextRequest;
4300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 while (mRequestQueue.empty()) {
4302 if (!mRepeatingRequests.empty()) {
4303 // Always atomically enqueue all requests in a repeating request
4304 // list. Guarantees a complete in-sequence set of captures to
4305 // application.
4306 const RequestList &requests = mRepeatingRequests;
4307 RequestList::const_iterator firstRequest =
4308 requests.begin();
4309 nextRequest = *firstRequest;
4310 mRequestQueue.insert(mRequestQueue.end(),
4311 ++firstRequest,
4312 requests.end());
4313 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004314
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004315 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004316
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 break;
4318 }
4319
4320 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4321
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004322 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4323 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004324 Mutex::Autolock pl(mPauseLock);
4325 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004326 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004327 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328 // Let the tracker know
4329 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4330 if (statusTracker != 0) {
4331 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4332 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 }
4334 // Stop waiting for now and let thread management happen
4335 return NULL;
4336 }
4337 }
4338
4339 if (nextRequest == NULL) {
4340 // Don't have a repeating request already in hand, so queue
4341 // must have an entry now.
4342 RequestList::iterator firstRequest =
4343 mRequestQueue.begin();
4344 nextRequest = *firstRequest;
4345 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004346 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4347 sp<NotificationListener> listener = mListener.promote();
4348 if (listener != NULL) {
4349 listener->notifyRequestQueueEmpty();
4350 }
4351 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352 }
4353
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004354 // In case we've been unpaused by setPaused clearing mDoPause, need to
4355 // update internal pause state (capture/setRepeatingRequest unpause
4356 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004358 if (mPaused) {
4359 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4360 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4361 if (statusTracker != 0) {
4362 statusTracker->markComponentActive(mStatusId);
4363 }
4364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004365 mPaused = false;
4366
4367 // Check if we've reconfigured since last time, and reset the preview
4368 // request if so. Can't use 'NULL request == repeat' across configure calls.
4369 if (mReconfigured) {
4370 mPrevRequest.clear();
4371 mReconfigured = false;
4372 }
4373
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004374 if (nextRequest != NULL) {
4375 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004376 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4377 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004378
4379 // Since RequestThread::clear() removes buffers from the input stream,
4380 // get the right buffer here before unlocking mRequestLock
4381 if (nextRequest->mInputStream != NULL) {
4382 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4383 if (res != OK) {
4384 // Can't get input buffer from gralloc queue - this could be due to
4385 // disconnected queue or other producer misbehavior, so not a fatal
4386 // error
4387 ALOGE("%s: Can't get input buffer, skipping request:"
4388 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004389
4390 sp<NotificationListener> listener = mListener.promote();
4391 if (listener != NULL) {
4392 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004393 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004394 nextRequest->mResultExtras);
4395 }
4396 return NULL;
4397 }
4398 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004399 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004400
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004401 return nextRequest;
4402}
4403
4404bool Camera3Device::RequestThread::waitIfPaused() {
4405 status_t res;
4406 Mutex::Autolock l(mPauseLock);
4407 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408 if (mPaused == false) {
4409 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004410 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4411 // Let the tracker know
4412 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4413 if (statusTracker != 0) {
4414 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4415 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004416 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004417
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004419 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004420 return true;
4421 }
4422 }
4423 // We don't set mPaused to false here, because waitForNextRequest needs
4424 // to further manage the paused state in case of starvation.
4425 return false;
4426}
4427
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004428void Camera3Device::RequestThread::unpauseForNewRequests() {
4429 // With work to do, mark thread as unpaused.
4430 // If paused by request (setPaused), don't resume, to avoid
4431 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004432 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004433 Mutex::Autolock p(mPauseLock);
4434 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004435 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4436 if (mPaused) {
4437 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4438 if (statusTracker != 0) {
4439 statusTracker->markComponentActive(mStatusId);
4440 }
4441 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004442 mPaused = false;
4443 }
4444}
4445
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004446void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4447 sp<Camera3Device> parent = mParent.promote();
4448 if (parent != NULL) {
4449 va_list args;
4450 va_start(args, fmt);
4451
4452 parent->setErrorStateV(fmt, args);
4453
4454 va_end(args);
4455 }
4456}
4457
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004458status_t Camera3Device::RequestThread::insertTriggers(
4459 const sp<CaptureRequest> &request) {
4460
4461 Mutex::Autolock al(mTriggerMutex);
4462
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004463 sp<Camera3Device> parent = mParent.promote();
4464 if (parent == NULL) {
4465 CLOGE("RequestThread: Parent is gone");
4466 return DEAD_OBJECT;
4467 }
4468
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004469 CameraMetadata &metadata = request->mSettings;
4470 size_t count = mTriggerMap.size();
4471
4472 for (size_t i = 0; i < count; ++i) {
4473 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004474 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004475
4476 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4477 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4478 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004479 if (isAeTrigger) {
4480 request->mResultExtras.precaptureTriggerId = triggerId;
4481 mCurrentPreCaptureTriggerId = triggerId;
4482 } else {
4483 request->mResultExtras.afTriggerId = triggerId;
4484 mCurrentAfTriggerId = triggerId;
4485 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004486 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004487 }
4488
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004489 camera_metadata_entry entry = metadata.find(tag);
4490
4491 if (entry.count > 0) {
4492 /**
4493 * Already has an entry for this trigger in the request.
4494 * Rewrite it with our requested trigger value.
4495 */
4496 RequestTrigger oldTrigger = trigger;
4497
4498 oldTrigger.entryValue = entry.data.u8[0];
4499
4500 mTriggerReplacedMap.add(tag, oldTrigger);
4501 } else {
4502 /**
4503 * More typical, no trigger entry, so we just add it
4504 */
4505 mTriggerRemovedMap.add(tag, trigger);
4506 }
4507
4508 status_t res;
4509
4510 switch (trigger.getTagType()) {
4511 case TYPE_BYTE: {
4512 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4513 res = metadata.update(tag,
4514 &entryValue,
4515 /*count*/1);
4516 break;
4517 }
4518 case TYPE_INT32:
4519 res = metadata.update(tag,
4520 &trigger.entryValue,
4521 /*count*/1);
4522 break;
4523 default:
4524 ALOGE("%s: Type not supported: 0x%x",
4525 __FUNCTION__,
4526 trigger.getTagType());
4527 return INVALID_OPERATION;
4528 }
4529
4530 if (res != OK) {
4531 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4532 ", value %d", __FUNCTION__, trigger.getTagName(),
4533 trigger.entryValue);
4534 return res;
4535 }
4536
4537 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4538 trigger.getTagName(),
4539 trigger.entryValue);
4540 }
4541
4542 mTriggerMap.clear();
4543
4544 return count;
4545}
4546
4547status_t Camera3Device::RequestThread::removeTriggers(
4548 const sp<CaptureRequest> &request) {
4549 Mutex::Autolock al(mTriggerMutex);
4550
4551 CameraMetadata &metadata = request->mSettings;
4552
4553 /**
4554 * Replace all old entries with their old values.
4555 */
4556 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4557 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4558
4559 status_t res;
4560
4561 uint32_t tag = trigger.metadataTag;
4562 switch (trigger.getTagType()) {
4563 case TYPE_BYTE: {
4564 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4565 res = metadata.update(tag,
4566 &entryValue,
4567 /*count*/1);
4568 break;
4569 }
4570 case TYPE_INT32:
4571 res = metadata.update(tag,
4572 &trigger.entryValue,
4573 /*count*/1);
4574 break;
4575 default:
4576 ALOGE("%s: Type not supported: 0x%x",
4577 __FUNCTION__,
4578 trigger.getTagType());
4579 return INVALID_OPERATION;
4580 }
4581
4582 if (res != OK) {
4583 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4584 ", trigger value %d", __FUNCTION__,
4585 trigger.getTagName(), trigger.entryValue);
4586 return res;
4587 }
4588 }
4589 mTriggerReplacedMap.clear();
4590
4591 /**
4592 * Remove all new entries.
4593 */
4594 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4595 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4596 status_t res = metadata.erase(trigger.metadataTag);
4597
4598 if (res != OK) {
4599 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4600 ", trigger value %d", __FUNCTION__,
4601 trigger.getTagName(), trigger.entryValue);
4602 return res;
4603 }
4604 }
4605 mTriggerRemovedMap.clear();
4606
4607 return OK;
4608}
4609
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004610status_t Camera3Device::RequestThread::addDummyTriggerIds(
4611 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004612 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004613 static const int32_t dummyTriggerId = 1;
4614 status_t res;
4615
4616 CameraMetadata &metadata = request->mSettings;
4617
4618 // If AF trigger is active, insert a dummy AF trigger ID if none already
4619 // exists
4620 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4621 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4622 if (afTrigger.count > 0 &&
4623 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4624 afId.count == 0) {
4625 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4626 if (res != OK) return res;
4627 }
4628
4629 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4630 // if none already exists
4631 camera_metadata_entry pcTrigger =
4632 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4633 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4634 if (pcTrigger.count > 0 &&
4635 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4636 pcId.count == 0) {
4637 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4638 &dummyTriggerId, 1);
4639 if (res != OK) return res;
4640 }
4641
4642 return OK;
4643}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004644
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004645/**
4646 * PreparerThread inner class methods
4647 */
4648
4649Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004650 Thread(/*canCallJava*/false), mListener(nullptr),
4651 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004652}
4653
4654Camera3Device::PreparerThread::~PreparerThread() {
4655 Thread::requestExitAndWait();
4656 if (mCurrentStream != nullptr) {
4657 mCurrentStream->cancelPrepare();
4658 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4659 mCurrentStream.clear();
4660 }
4661 clear();
4662}
4663
Ruben Brunkc78ac262015-08-13 17:58:46 -07004664status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004665 status_t res;
4666
4667 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004668 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004669
Ruben Brunkc78ac262015-08-13 17:58:46 -07004670 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004671 if (res == OK) {
4672 // No preparation needed, fire listener right off
4673 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004674 if (listener != NULL) {
4675 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004676 }
4677 return OK;
4678 } else if (res != NOT_ENOUGH_DATA) {
4679 return res;
4680 }
4681
4682 // Need to prepare, start up thread if necessary
4683 if (!mActive) {
4684 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4685 // isn't running
4686 Thread::requestExitAndWait();
4687 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4688 if (res != OK) {
4689 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004690 if (listener != NULL) {
4691 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004692 }
4693 return res;
4694 }
4695 mCancelNow = false;
4696 mActive = true;
4697 ALOGV("%s: Preparer stream started", __FUNCTION__);
4698 }
4699
4700 // queue up the work
4701 mPendingStreams.push_back(stream);
4702 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4703
4704 return OK;
4705}
4706
4707status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004708 Mutex::Autolock l(mLock);
4709
4710 for (const auto& stream : mPendingStreams) {
4711 stream->cancelPrepare();
4712 }
4713 mPendingStreams.clear();
4714 mCancelNow = true;
4715
4716 return OK;
4717}
4718
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004719void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004720 Mutex::Autolock l(mLock);
4721 mListener = listener;
4722}
4723
4724bool Camera3Device::PreparerThread::threadLoop() {
4725 status_t res;
4726 {
4727 Mutex::Autolock l(mLock);
4728 if (mCurrentStream == nullptr) {
4729 // End thread if done with work
4730 if (mPendingStreams.empty()) {
4731 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4732 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4733 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4734 mActive = false;
4735 return false;
4736 }
4737
4738 // Get next stream to prepare
4739 auto it = mPendingStreams.begin();
4740 mCurrentStream = *it;
4741 mPendingStreams.erase(it);
4742 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4743 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4744 } else if (mCancelNow) {
4745 mCurrentStream->cancelPrepare();
4746 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4747 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4748 mCurrentStream.clear();
4749 mCancelNow = false;
4750 return true;
4751 }
4752 }
4753
4754 res = mCurrentStream->prepareNextBuffer();
4755 if (res == NOT_ENOUGH_DATA) return true;
4756 if (res != OK) {
4757 // Something bad happened; try to recover by cancelling prepare and
4758 // signalling listener anyway
4759 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4760 mCurrentStream->getId(), res, strerror(-res));
4761 mCurrentStream->cancelPrepare();
4762 }
4763
4764 // This stream has finished, notify listener
4765 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004766 sp<NotificationListener> listener = mListener.promote();
4767 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004768 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4769 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004770 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004771 }
4772
4773 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4774 mCurrentStream.clear();
4775
4776 return true;
4777}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004778
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004779/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004780 * Static callback forwarding methods from HAL to instance
4781 */
4782
4783void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4784 const camera3_capture_result *result) {
4785 Camera3Device *d =
4786 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004787
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004788 d->processCaptureResult(result);
4789}
4790
4791void Camera3Device::sNotify(const camera3_callback_ops *cb,
4792 const camera3_notify_msg *msg) {
4793 Camera3Device *d =
4794 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4795 d->notify(msg);
4796}
4797
4798}; // namespace android