blob: 49423a0d7b4f943302dff0f335d301cfa0502922 [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 Yeh657c1872017-07-18 18:09:57 -0700854 // Ideally we should grab mLock, but that can lead to deadlock, and
855 // it's not super important to get up to date value of mStatus for this
856 // warning print, hence skipping the lock here
857 if (mStatus == STATUS_ERROR) {
858 // Per API contract, HAL should act as closed after device error
859 // But mStatus can be set to error by framework as well, so just log
860 // a warning here.
861 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700862 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700863
864 if (mProcessCaptureResultLock.tryLock() != OK) {
865 // This should never happen; it indicates a wrong client implementation
866 // that doesn't follow the contract. But, we can be tolerant here.
867 ALOGE("%s: callback overlapped! waiting 1s...",
868 __FUNCTION__);
869 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
870 ALOGE("%s: cannot acquire lock in 1s, dropping results",
871 __FUNCTION__);
872 // really don't know what to do, so bail out.
873 return hardware::Void();
874 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800875 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700876 for (const auto& result : results) {
877 processOneCaptureResultLocked(result);
878 }
879 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800880 return hardware::Void();
881}
882
Yifan Honga640c5a2017-04-12 16:30:31 -0700883void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800884 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800885 camera3_capture_result r;
886 status_t res;
887 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700888
889 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
890 if (result.fmqResultSize > 0) {
891 resultMetadata.resize(result.fmqResultSize);
892 if (mResultMetadataQueue == nullptr) {
893 return; // logged in initialize()
894 }
895 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
896 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
897 __FUNCTION__, result.frameNumber, result.fmqResultSize);
898 return;
899 }
900 } else {
901 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
902 result.result.size());
903 }
904
905 if (resultMetadata.size() != 0) {
906 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
907 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800908 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
909 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
910 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800911 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800912 }
913 } else {
914 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800915 }
916
917 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
918 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
919 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
920 auto& bDst = outputBuffers[i];
921 const StreamBuffer &bSrc = result.outputBuffers[i];
922
923 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100924 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800925 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
926 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800927 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800928 }
929 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
930
931 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800932 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800933 if (res != OK) {
934 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
935 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800936 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800937 }
938 bDst.buffer = buffer;
939 bDst.status = mapHidlBufferStatus(bSrc.status);
940 bDst.acquire_fence = -1;
941 if (bSrc.releaseFence == nullptr) {
942 bDst.release_fence = -1;
943 } else if (bSrc.releaseFence->numFds == 1) {
944 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
945 } else {
946 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
947 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800948 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800949 }
950 }
951 r.num_output_buffers = outputBuffers.size();
952 r.output_buffers = outputBuffers.data();
953
954 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800955 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800956 r.input_buffer = nullptr;
957 } else {
958 if (mInputStream->getId() != result.inputBuffer.streamId) {
959 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
960 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800961 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800962 }
963 inputBuffer.stream = mInputStream->asHalStream();
964 buffer_handle_t *buffer;
965 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
966 &buffer);
967 if (res != OK) {
968 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
969 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800970 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 }
972 inputBuffer.buffer = buffer;
973 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
974 inputBuffer.acquire_fence = -1;
975 if (result.inputBuffer.releaseFence == nullptr) {
976 inputBuffer.release_fence = -1;
977 } else if (result.inputBuffer.releaseFence->numFds == 1) {
978 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
979 } else {
980 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
981 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800982 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800983 }
984 r.input_buffer = &inputBuffer;
985 }
986
987 r.partial_result = result.partialResult;
988
989 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990}
991
992hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800993 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700994 // Ideally we should grab mLock, but that can lead to deadlock, and
995 // it's not super important to get up to date value of mStatus for this
996 // warning print, hence skipping the lock here
997 if (mStatus == STATUS_ERROR) {
998 // Per API contract, HAL should act as closed after device error
999 // But mStatus can be set to error by framework as well, so just log
1000 // a warning here.
1001 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001002 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001003
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001004 for (const auto& msg : msgs) {
1005 notify(msg);
1006 }
1007 return hardware::Void();
1008}
1009
1010void Camera3Device::notify(
1011 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1012
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001013 camera3_notify_msg m;
1014 switch (msg.type) {
1015 case MsgType::ERROR:
1016 m.type = CAMERA3_MSG_ERROR;
1017 m.message.error.frame_number = msg.msg.error.frameNumber;
1018 if (msg.msg.error.errorStreamId >= 0) {
1019 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001020 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001021 ALOGE("%s: Frame %d: Invalid error stream id %d",
1022 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001023 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001024 }
1025 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1026 } else {
1027 m.message.error.error_stream = nullptr;
1028 }
1029 switch (msg.msg.error.errorCode) {
1030 case ErrorCode::ERROR_DEVICE:
1031 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1032 break;
1033 case ErrorCode::ERROR_REQUEST:
1034 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1035 break;
1036 case ErrorCode::ERROR_RESULT:
1037 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1038 break;
1039 case ErrorCode::ERROR_BUFFER:
1040 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1041 break;
1042 }
1043 break;
1044 case MsgType::SHUTTER:
1045 m.type = CAMERA3_MSG_SHUTTER;
1046 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1047 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1048 break;
1049 }
1050 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001051}
1052
Jianing Weicb0652e2014-03-12 18:29:36 -07001053status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001054 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001055 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001056 ATRACE_CALL();
1057
Shuzhen Wang0129d522016-10-30 22:43:41 -07001058 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001059}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001060
Jianing Weicb0652e2014-03-12 18:29:36 -07001061status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1062 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001063 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001064
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001065 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001066 std::list<const SurfaceMap> surfaceMaps;
1067 convertToRequestList(requests, surfaceMaps, request);
1068
1069 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1070 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071}
1072
Jianing Weicb0652e2014-03-12 18:29:36 -07001073status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001074 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001075 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001076 ATRACE_CALL();
1077
Shuzhen Wang0129d522016-10-30 22:43:41 -07001078 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001079}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080
1081sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001082 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083 status_t res;
1084
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001085 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001086 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1087 // so unilaterally select normal operating mode.
1088 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001089 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001091 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001092 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001093 } else if (mStatus == STATUS_UNCONFIGURED) {
1094 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001095 CLOGE("No streams configured");
1096 return NULL;
1097 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001098 }
1099
Shuzhen Wang0129d522016-10-30 22:43:41 -07001100 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001101 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001102}
1103
Jianing Weicb0652e2014-03-12 18:29:36 -07001104status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001106 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001108
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001109 switch (mStatus) {
1110 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001111 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001112 return INVALID_OPERATION;
1113 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001114 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001116 case STATUS_UNCONFIGURED:
1117 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 case STATUS_ACTIVE:
1119 // OK
1120 break;
1121 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001122 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001123 return INVALID_OPERATION;
1124 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001126
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001127 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001128}
1129
1130status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1131 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001132 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001133
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001134 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001135}
1136
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001137status_t Camera3Device::createInputStream(
1138 uint32_t width, uint32_t height, int format, int *id) {
1139 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001140 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001141 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001142 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1143 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001144
1145 status_t res;
1146 bool wasActive = false;
1147
1148 switch (mStatus) {
1149 case STATUS_ERROR:
1150 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1151 return INVALID_OPERATION;
1152 case STATUS_UNINITIALIZED:
1153 ALOGE("%s: Device not initialized", __FUNCTION__);
1154 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001155 case STATUS_UNCONFIGURED:
1156 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001157 // OK
1158 break;
1159 case STATUS_ACTIVE:
1160 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001161 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001164 return res;
1165 }
1166 wasActive = true;
1167 break;
1168 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001169 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001170 return INVALID_OPERATION;
1171 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001173
1174 if (mInputStream != 0) {
1175 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1176 return INVALID_OPERATION;
1177 }
1178
1179 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1180 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001181 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001182
1183 mInputStream = newStream;
1184
1185 *id = mNextStreamId++;
1186
1187 // Continue captures if active at start
1188 if (wasActive) {
1189 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001190 // Reuse current operating mode for new stream config
1191 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001192 if (res != OK) {
1193 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1194 __FUNCTION__, mNextStreamId, strerror(-res), res);
1195 return res;
1196 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001197 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001198 }
1199
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001200 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001201 return OK;
1202}
1203
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001204status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001205 uint32_t width, uint32_t height, int format,
1206 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001207 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001208 ATRACE_CALL();
1209
1210 if (consumer == nullptr) {
1211 ALOGE("%s: consumer must not be null", __FUNCTION__);
1212 return BAD_VALUE;
1213 }
1214
1215 std::vector<sp<Surface>> consumers;
1216 consumers.push_back(consumer);
1217
1218 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001219 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001220}
1221
1222status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1223 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1224 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001225 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001229 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001230 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1231 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001232
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 status_t res;
1234 bool wasActive = false;
1235
1236 switch (mStatus) {
1237 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001238 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 return INVALID_OPERATION;
1240 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 case STATUS_UNCONFIGURED:
1244 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 // OK
1246 break;
1247 case STATUS_ACTIVE:
1248 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 return res;
1253 }
1254 wasActive = true;
1255 break;
1256 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001260 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261
1262 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001263
Shuzhen Wang0129d522016-10-30 22:43:41 -07001264 if (consumers.size() == 0 && !hasDeferredConsumer) {
1265 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1266 return BAD_VALUE;
1267 }
Zhijun He5d677d12016-05-29 16:52:39 -07001268
Shuzhen Wang0129d522016-10-30 22:43:41 -07001269 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001270 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1271 return BAD_VALUE;
1272 }
1273
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001275 ssize_t blobBufferSize;
1276 if (dataSpace != HAL_DATASPACE_DEPTH) {
1277 blobBufferSize = getJpegBufferSize(width, height);
1278 if (blobBufferSize <= 0) {
1279 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1280 return BAD_VALUE;
1281 }
1282 } else {
1283 blobBufferSize = getPointCloudBufferSize();
1284 if (blobBufferSize <= 0) {
1285 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1286 return BAD_VALUE;
1287 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001288 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001289 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001290 width, height, blobBufferSize, format, dataSpace, rotation,
1291 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001292 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1293 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1294 if (rawOpaqueBufferSize <= 0) {
1295 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1296 return BAD_VALUE;
1297 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001298 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001299 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1300 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001301 } else if (isShared) {
1302 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1303 width, height, format, consumerUsage, dataSpace, rotation,
1304 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001305 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001306 newStream = new Camera3OutputStream(mNextStreamId,
1307 width, height, format, consumerUsage, dataSpace, rotation,
1308 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001310 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001311 width, height, format, dataSpace, rotation,
1312 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001313 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001314 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001315
Emilian Peev08dd2452017-04-06 16:55:14 +01001316 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001317
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 res = mOutputStreams.add(mNextStreamId, newStream);
1319 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001320 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001321 return res;
1322 }
1323
1324 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001325 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001326
1327 // Continue captures if active at start
1328 if (wasActive) {
1329 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001330 // Reuse current operating mode for new stream config
1331 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001332 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001333 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1334 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 return res;
1336 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001337 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001339 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001340 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341}
1342
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001343status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001344 uint32_t *width, uint32_t *height,
1345 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001349
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350 switch (mStatus) {
1351 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001352 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 return INVALID_OPERATION;
1354 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 case STATUS_UNCONFIGURED:
1358 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 case STATUS_ACTIVE:
1360 // OK
1361 break;
1362 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001363 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return INVALID_OPERATION;
1365 }
1366
1367 ssize_t idx = mOutputStreams.indexOfKey(id);
1368 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001369 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return idx;
1371 }
1372
1373 if (width) *width = mOutputStreams[idx]->getWidth();
1374 if (height) *height = mOutputStreams[idx]->getHeight();
1375 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001376 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001378}
1379
1380status_t Camera3Device::setStreamTransform(int id,
1381 int transform) {
1382 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001383 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 switch (mStatus) {
1387 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001388 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return INVALID_OPERATION;
1390 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 case STATUS_UNCONFIGURED:
1394 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 case STATUS_ACTIVE:
1396 // OK
1397 break;
1398 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return INVALID_OPERATION;
1401 }
1402
1403 ssize_t idx = mOutputStreams.indexOfKey(id);
1404 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001405 CLOGE("Stream %d does not exist",
1406 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407 return BAD_VALUE;
1408 }
1409
1410 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001411}
1412
1413status_t Camera3Device::deleteStream(int id) {
1414 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001415 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 Mutex::Autolock l(mLock);
1417 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001418
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001419 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001420
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421 // CameraDevice semantics require device to already be idle before
1422 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001423 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001424 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001425 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 }
1427
Igor Murashkin2fba5842013-04-22 14:03:54 -07001428 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001429 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 if (mInputStream != NULL && id == mInputStream->getId()) {
1431 deletedStream = mInputStream;
1432 mInputStream.clear();
1433 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001434 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001435 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001436 return BAD_VALUE;
1437 }
Zhijun He5f446352014-01-22 09:49:33 -08001438 }
1439
1440 // Delete output stream or the output part of a bi-directional stream.
1441 if (outputStreamIdx != NAME_NOT_FOUND) {
1442 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 mOutputStreams.removeItem(id);
1444 }
1445
1446 // Free up the stream endpoint so that it can be used by some other stream
1447 res = deletedStream->disconnect();
1448 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001449 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 // fall through since we want to still list the stream as deleted.
1451 }
1452 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001453 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454
1455 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001456}
1457
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001458status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001459 ATRACE_CALL();
1460 ALOGV("%s: E", __FUNCTION__);
1461
1462 Mutex::Autolock il(mInterfaceLock);
1463 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001464
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001465 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001466}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001468status_t Camera3Device::getInputBufferProducer(
1469 sp<IGraphicBufferProducer> *producer) {
1470 Mutex::Autolock il(mInterfaceLock);
1471 Mutex::Autolock l(mLock);
1472
1473 if (producer == NULL) {
1474 return BAD_VALUE;
1475 } else if (mInputStream == NULL) {
1476 return INVALID_OPERATION;
1477 }
1478
1479 return mInputStream->getInputBufferProducer(producer);
1480}
1481
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001482status_t Camera3Device::createDefaultRequest(int templateId,
1483 CameraMetadata *request) {
1484 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001485 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001486
1487 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1488 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1489 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1490 return BAD_VALUE;
1491 }
1492
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 Mutex::Autolock l(mLock);
1495
1496 switch (mStatus) {
1497 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001501 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001503 case STATUS_UNCONFIGURED:
1504 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 case STATUS_ACTIVE:
1506 // OK
1507 break;
1508 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return INVALID_OPERATION;
1511 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001512
Zhijun Hea1530f12014-09-14 12:44:20 -07001513 if (!mRequestTemplateCache[templateId].isEmpty()) {
1514 *request = mRequestTemplateCache[templateId];
1515 return OK;
1516 }
1517
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001518 camera_metadata_t *rawRequest;
1519 status_t res = mInterface->constructDefaultRequestSettings(
1520 (camera3_request_template_t) templateId, &rawRequest);
1521 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001522 ALOGI("%s: template %d is not supported on this camera device",
1523 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001524 return res;
1525 } else if (res != OK) {
1526 CLOGE("Unable to construct request template %d: %s (%d)",
1527 templateId, strerror(-res), res);
1528 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001530
Emilian Peev71c73a22017-03-21 16:35:51 +00001531 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001532 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001534 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535 return OK;
1536}
1537
1538status_t Camera3Device::waitUntilDrained() {
1539 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001542
Zhijun He69a37482014-03-23 18:44:49 -07001543 return waitUntilDrainedLocked();
1544}
1545
1546status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 switch (mStatus) {
1548 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 ALOGV("%s: Already idle", __FUNCTION__);
1551 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 case STATUS_CONFIGURED:
1553 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 case STATUS_ERROR:
1555 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 break;
1558 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001559 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return INVALID_OPERATION;
1561 }
1562
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001563 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001565 if (res != OK) {
1566 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1567 res);
1568 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 return res;
1570}
1571
Ruben Brunk183f0562015-08-12 12:55:02 -07001572
1573void Camera3Device::internalUpdateStatusLocked(Status status) {
1574 mStatus = status;
1575 mRecentStatusUpdates.add(mStatus);
1576 mStatusChanged.broadcast();
1577}
1578
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579// Pause to reconfigure
1580status_t Camera3Device::internalPauseAndWaitLocked() {
1581 mRequestThread->setPaused(true);
1582 mPauseStateNotify = true;
1583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001584 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1586 if (res != OK) {
1587 SET_ERR_L("Can't idle device in %f seconds!",
1588 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 }
1590
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 return res;
1592}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594// Resume after internalPauseAndWaitLocked
1595status_t Camera3Device::internalResumeLocked() {
1596 status_t res;
1597
1598 mRequestThread->setPaused(false);
1599
1600 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1601 if (res != OK) {
1602 SET_ERR_L("Can't transition to active in %f seconds!",
1603 kActiveTimeout/1e9);
1604 }
1605 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607}
1608
Ruben Brunk183f0562015-08-12 12:55:02 -07001609status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001610 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001611
1612 size_t startIndex = 0;
1613 if (mStatusWaiters == 0) {
1614 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1615 // this status list
1616 mRecentStatusUpdates.clear();
1617 } else {
1618 // If other threads are waiting on updates to this status list, set the position of the
1619 // first element that this list will check rather than clearing the list.
1620 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 }
1622
Ruben Brunk183f0562015-08-12 12:55:02 -07001623 mStatusWaiters++;
1624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 bool stateSeen = false;
1626 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001627 if (active == (mStatus == STATUS_ACTIVE)) {
1628 // Desired state is current
1629 break;
1630 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631
1632 res = mStatusChanged.waitRelative(mLock, timeout);
1633 if (res != OK) break;
1634
Ruben Brunk183f0562015-08-12 12:55:02 -07001635 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1636 // transitions.
1637 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1638 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1639 __FUNCTION__);
1640
1641 // Encountered desired state since we began waiting
1642 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001643 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1644 stateSeen = true;
1645 break;
1646 }
1647 }
1648 } while (!stateSeen);
1649
Ruben Brunk183f0562015-08-12 12:55:02 -07001650 mStatusWaiters--;
1651
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001652 return res;
1653}
1654
1655
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001656status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001657 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001658 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001660 if (listener != NULL && mListener != NULL) {
1661 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1662 }
1663 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001664 mRequestThread->setNotificationListener(listener);
1665 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001666
1667 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668}
1669
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001670bool Camera3Device::willNotify3A() {
1671 return false;
1672}
1673
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001675 status_t res;
1676 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 while (mResultQueue.empty()) {
1679 res = mResultSignal.waitRelative(mOutputLock, timeout);
1680 if (res == TIMED_OUT) {
1681 return res;
1682 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001683 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1684 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001685 return res;
1686 }
1687 }
1688 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689}
1690
Jianing Weicb0652e2014-03-12 18:29:36 -07001691status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001693 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001695 if (mResultQueue.empty()) {
1696 return NOT_ENOUGH_DATA;
1697 }
1698
Jianing Weicb0652e2014-03-12 18:29:36 -07001699 if (frame == NULL) {
1700 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1701 return BAD_VALUE;
1702 }
1703
1704 CaptureResult &result = *(mResultQueue.begin());
1705 frame->mResultExtras = result.mResultExtras;
1706 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001707 mResultQueue.erase(mResultQueue.begin());
1708
1709 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710}
1711
1712status_t Camera3Device::triggerAutofocus(uint32_t id) {
1713 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001714 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001715
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001716 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1717 // Mix-in this trigger into the next request and only the next request.
1718 RequestTrigger trigger[] = {
1719 {
1720 ANDROID_CONTROL_AF_TRIGGER,
1721 ANDROID_CONTROL_AF_TRIGGER_START
1722 },
1723 {
1724 ANDROID_CONTROL_AF_TRIGGER_ID,
1725 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001726 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001727 };
1728
1729 return mRequestThread->queueTrigger(trigger,
1730 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731}
1732
1733status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1734 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001736
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001737 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1738 // Mix-in this trigger into the next request and only the next request.
1739 RequestTrigger trigger[] = {
1740 {
1741 ANDROID_CONTROL_AF_TRIGGER,
1742 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1743 },
1744 {
1745 ANDROID_CONTROL_AF_TRIGGER_ID,
1746 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001747 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001748 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001750 return mRequestThread->queueTrigger(trigger,
1751 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752}
1753
1754status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1755 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001758 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1759 // Mix-in this trigger into the next request and only the next request.
1760 RequestTrigger trigger[] = {
1761 {
1762 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1763 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1764 },
1765 {
1766 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1767 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001768 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001769 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001771 return mRequestThread->queueTrigger(trigger,
1772 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001773}
1774
Jianing Weicb0652e2014-03-12 18:29:36 -07001775status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001776 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001777 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001778 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001779
Zhijun He7ef20392014-04-21 16:04:17 -07001780 {
1781 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001782 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001783 }
1784
Emilian Peev08dd2452017-04-06 16:55:14 +01001785 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001786}
1787
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001788status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001789 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1790}
1791
1792status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001793 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001794 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001795 Mutex::Autolock il(mInterfaceLock);
1796 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001797
1798 sp<Camera3StreamInterface> stream;
1799 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1800 if (outputStreamIdx == NAME_NOT_FOUND) {
1801 CLOGE("Stream %d does not exist", streamId);
1802 return BAD_VALUE;
1803 }
1804
1805 stream = mOutputStreams.editValueAt(outputStreamIdx);
1806
1807 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001808 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001809 return BAD_VALUE;
1810 }
1811
1812 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001813 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001814 return BAD_VALUE;
1815 }
1816
Ruben Brunkc78ac262015-08-13 17:58:46 -07001817 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001818}
1819
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001820status_t Camera3Device::tearDown(int streamId) {
1821 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001822 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001823 Mutex::Autolock il(mInterfaceLock);
1824 Mutex::Autolock l(mLock);
1825
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001826 sp<Camera3StreamInterface> stream;
1827 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1828 if (outputStreamIdx == NAME_NOT_FOUND) {
1829 CLOGE("Stream %d does not exist", streamId);
1830 return BAD_VALUE;
1831 }
1832
1833 stream = mOutputStreams.editValueAt(outputStreamIdx);
1834
1835 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1836 CLOGE("Stream %d is a target of a in-progress request", streamId);
1837 return BAD_VALUE;
1838 }
1839
1840 return stream->tearDown();
1841}
1842
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001843status_t Camera3Device::addBufferListenerForStream(int streamId,
1844 wp<Camera3StreamBufferListener> listener) {
1845 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001846 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001847 Mutex::Autolock il(mInterfaceLock);
1848 Mutex::Autolock l(mLock);
1849
1850 sp<Camera3StreamInterface> stream;
1851 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1852 if (outputStreamIdx == NAME_NOT_FOUND) {
1853 CLOGE("Stream %d does not exist", streamId);
1854 return BAD_VALUE;
1855 }
1856
1857 stream = mOutputStreams.editValueAt(outputStreamIdx);
1858 stream->addBufferListener(listener);
1859
1860 return OK;
1861}
1862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001863/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 * Methods called by subclasses
1865 */
1866
1867void Camera3Device::notifyStatus(bool idle) {
1868 {
1869 // Need mLock to safely update state and synchronize to current
1870 // state of methods in flight.
1871 Mutex::Autolock l(mLock);
1872 // We can get various system-idle notices from the status tracker
1873 // while starting up. Only care about them if we've actually sent
1874 // in some requests recently.
1875 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1876 return;
1877 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001878 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001879 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001880 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881
1882 // Skip notifying listener if we're doing some user-transparent
1883 // state changes
1884 if (mPauseStateNotify) return;
1885 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001886
1887 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888 {
1889 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001890 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 }
1892 if (idle && listener != NULL) {
1893 listener->notifyIdle();
1894 }
1895}
1896
Shuzhen Wang758c2152017-01-10 18:26:18 -08001897status_t Camera3Device::setConsumerSurfaces(int streamId,
1898 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001899 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001900 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1901 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001902 Mutex::Autolock il(mInterfaceLock);
1903 Mutex::Autolock l(mLock);
1904
Shuzhen Wang758c2152017-01-10 18:26:18 -08001905 if (consumers.size() == 0) {
1906 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001907 return BAD_VALUE;
1908 }
1909
1910 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1911 if (idx == NAME_NOT_FOUND) {
1912 CLOGE("Stream %d is unknown", streamId);
1913 return idx;
1914 }
1915 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001916 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001917 if (res != OK) {
1918 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1919 return res;
1920 }
1921
Shuzhen Wang0129d522016-10-30 22:43:41 -07001922 if (stream->isConsumerConfigurationDeferred()) {
1923 if (!stream->isConfiguring()) {
1924 CLOGE("Stream %d was already fully configured.", streamId);
1925 return INVALID_OPERATION;
1926 }
Zhijun He5d677d12016-05-29 16:52:39 -07001927
Shuzhen Wang0129d522016-10-30 22:43:41 -07001928 res = stream->finishConfiguration();
1929 if (res != OK) {
1930 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1931 stream->getId(), strerror(-res), res);
1932 return res;
1933 }
Zhijun He5d677d12016-05-29 16:52:39 -07001934 }
1935
1936 return OK;
1937}
1938
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001939/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001940 * Camera3Device private methods
1941 */
1942
1943sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001944 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001945 ATRACE_CALL();
1946 status_t res;
1947
1948 sp<CaptureRequest> newRequest = new CaptureRequest;
1949 newRequest->mSettings = request;
1950
1951 camera_metadata_entry_t inputStreams =
1952 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1953 if (inputStreams.count > 0) {
1954 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001955 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001956 CLOGE("Request references unknown input stream %d",
1957 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001958 return NULL;
1959 }
1960 // Lazy completion of stream configuration (allocation/registration)
1961 // on first use
1962 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001963 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001964 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001965 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001966 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001967 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001968 return NULL;
1969 }
1970 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001971 // Check if stream is being prepared
1972 if (mInputStream->isPreparing()) {
1973 CLOGE("Request references an input stream that's being prepared!");
1974 return NULL;
1975 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976
1977 newRequest->mInputStream = mInputStream;
1978 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1979 }
1980
1981 camera_metadata_entry_t streams =
1982 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1983 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001984 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001985 return NULL;
1986 }
1987
1988 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001989 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001990 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001991 CLOGE("Request references unknown stream %d",
1992 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 return NULL;
1994 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001995 sp<Camera3OutputStreamInterface> stream =
1996 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001997
Zhijun He5d677d12016-05-29 16:52:39 -07001998 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07001999 auto iter = surfaceMap.find(streams.data.i32[i]);
2000 if (iter != surfaceMap.end()) {
2001 const std::vector<size_t>& surfaces = iter->second;
2002 for (const auto& surface : surfaces) {
2003 if (stream->isConsumerConfigurationDeferred(surface)) {
2004 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2005 "due to deferred consumer", stream->getId(), surface);
2006 return NULL;
2007 }
2008 }
2009 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002010 }
2011
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002012 // Lazy completion of stream configuration (allocation/registration)
2013 // on first use
2014 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002015 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002017 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2018 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019 return NULL;
2020 }
2021 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002022 // Check if stream is being prepared
2023 if (stream->isPreparing()) {
2024 CLOGE("Request references an output stream that's being prepared!");
2025 return NULL;
2026 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027
2028 newRequest->mOutputStreams.push(stream);
2029 }
2030 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002031 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002032
2033 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002034}
2035
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002036bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2037 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2038 Size size = mSupportedOpaqueInputSizes[i];
2039 if (size.width == width && size.height == height) {
2040 return true;
2041 }
2042 }
2043
2044 return false;
2045}
2046
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002047void Camera3Device::cancelStreamsConfigurationLocked() {
2048 int res = OK;
2049 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2050 res = mInputStream->cancelConfiguration();
2051 if (res != OK) {
2052 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2053 mInputStream->getId(), strerror(-res), res);
2054 }
2055 }
2056
2057 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2058 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2059 if (outputStream->isConfiguring()) {
2060 res = outputStream->cancelConfiguration();
2061 if (res != OK) {
2062 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2063 outputStream->getId(), strerror(-res), res);
2064 }
2065 }
2066 }
2067
2068 // Return state to that at start of call, so that future configures
2069 // properly clean things up
2070 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2071 mNeedConfig = true;
2072}
2073
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002074status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 ATRACE_CALL();
2076 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002077
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002078 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002079 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 return INVALID_OPERATION;
2081 }
2082
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002083 if (operatingMode < 0) {
2084 CLOGE("Invalid operating mode: %d", operatingMode);
2085 return BAD_VALUE;
2086 }
2087
2088 bool isConstrainedHighSpeed =
2089 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2090 operatingMode;
2091
2092 if (mOperatingMode != operatingMode) {
2093 mNeedConfig = true;
2094 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2095 mOperatingMode = operatingMode;
2096 }
2097
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002098 if (!mNeedConfig) {
2099 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2100 return OK;
2101 }
2102
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002103 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2104 // adding a dummy stream instead.
2105 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2106 if (mOutputStreams.size() == 0) {
2107 addDummyStreamLocked();
2108 } else {
2109 tryRemoveDummyStreamLocked();
2110 }
2111
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002113 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114
2115 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002116 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2118
2119 Vector<camera3_stream_t*> streams;
2120 streams.setCapacity(config.num_streams);
2121
2122 if (mInputStream != NULL) {
2123 camera3_stream_t *inputStream;
2124 inputStream = mInputStream->startConfiguration();
2125 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002126 CLOGE("Can't start input stream configuration");
2127 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128 return INVALID_OPERATION;
2129 }
2130 streams.add(inputStream);
2131 }
2132
2133 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002134
2135 // Don't configure bidi streams twice, nor add them twice to the list
2136 if (mOutputStreams[i].get() ==
2137 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2138
2139 config.num_streams--;
2140 continue;
2141 }
2142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143 camera3_stream_t *outputStream;
2144 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2145 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002146 CLOGE("Can't start output stream configuration");
2147 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148 return INVALID_OPERATION;
2149 }
2150 streams.add(outputStream);
2151 }
2152
2153 config.streams = streams.editArray();
2154
2155 // Do the HAL configuration; will potentially touch stream
2156 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002157
2158 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002159
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002160 if (res == BAD_VALUE) {
2161 // HAL rejected this set of streams as unsupported, clean up config
2162 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002163 CLOGE("Set of requested inputs/outputs not supported by HAL");
2164 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002165 return BAD_VALUE;
2166 } else if (res != OK) {
2167 // Some other kind of error from configure_streams - this is not
2168 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002169 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2170 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002171 return res;
2172 }
2173
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002174 // Finish all stream configuration immediately.
2175 // TODO: Try to relax this later back to lazy completion, which should be
2176 // faster
2177
Igor Murashkin073f8572013-05-02 14:59:28 -07002178 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002179 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002180 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002181 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002182 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002183 cancelStreamsConfigurationLocked();
2184 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002185 }
2186 }
2187
2188 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002189 sp<Camera3OutputStreamInterface> outputStream =
2190 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002191 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002192 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002193 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002194 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002195 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002196 cancelStreamsConfigurationLocked();
2197 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002198 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002199 }
2200 }
2201
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002202 // Request thread needs to know to avoid using repeat-last-settings protocol
2203 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002204 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205
Zhijun He90f7c372016-08-16 16:19:43 -07002206 char value[PROPERTY_VALUE_MAX];
2207 property_get("camera.fifo.disable", value, "0");
2208 int32_t disableFifo = atoi(value);
2209 if (disableFifo != 1) {
2210 // Boost priority of request thread to SCHED_FIFO.
2211 pid_t requestThreadTid = mRequestThread->getTid();
2212 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002213 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002214 if (res != OK) {
2215 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2216 strerror(-res), res);
2217 } else {
2218 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2219 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002220 }
2221
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002222 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002224 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225
Ruben Brunk183f0562015-08-12 12:55:02 -07002226 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2227 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002228
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002229 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230
Zhijun He0a210512014-07-24 13:45:15 -07002231 // tear down the deleted streams after configure streams.
2232 mDeletedStreams.clear();
2233
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002235}
2236
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002237status_t Camera3Device::addDummyStreamLocked() {
2238 ATRACE_CALL();
2239 status_t res;
2240
2241 if (mDummyStreamId != NO_STREAM) {
2242 // Should never be adding a second dummy stream when one is already
2243 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002244 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2245 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002246 return INVALID_OPERATION;
2247 }
2248
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002249 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002250
2251 sp<Camera3OutputStreamInterface> dummyStream =
2252 new Camera3DummyStream(mNextStreamId);
2253
2254 res = mOutputStreams.add(mNextStreamId, dummyStream);
2255 if (res < 0) {
2256 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2257 return res;
2258 }
2259
2260 mDummyStreamId = mNextStreamId;
2261 mNextStreamId++;
2262
2263 return OK;
2264}
2265
2266status_t Camera3Device::tryRemoveDummyStreamLocked() {
2267 ATRACE_CALL();
2268 status_t res;
2269
2270 if (mDummyStreamId == NO_STREAM) return OK;
2271 if (mOutputStreams.size() == 1) return OK;
2272
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002273 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002274
2275 // Ok, have a dummy stream and there's at least one other output stream,
2276 // so remove the dummy
2277
2278 sp<Camera3StreamInterface> deletedStream;
2279 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2280 if (outputStreamIdx == NAME_NOT_FOUND) {
2281 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2282 return INVALID_OPERATION;
2283 }
2284
2285 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2286 mOutputStreams.removeItemsAt(outputStreamIdx);
2287
2288 // Free up the stream endpoint so that it can be used by some other stream
2289 res = deletedStream->disconnect();
2290 if (res != OK) {
2291 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2292 // fall through since we want to still list the stream as deleted.
2293 }
2294 mDeletedStreams.add(deletedStream);
2295 mDummyStreamId = NO_STREAM;
2296
2297 return res;
2298}
2299
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002300void Camera3Device::setErrorState(const char *fmt, ...) {
2301 Mutex::Autolock l(mLock);
2302 va_list args;
2303 va_start(args, fmt);
2304
2305 setErrorStateLockedV(fmt, args);
2306
2307 va_end(args);
2308}
2309
2310void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2311 Mutex::Autolock l(mLock);
2312 setErrorStateLockedV(fmt, args);
2313}
2314
2315void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2316 va_list args;
2317 va_start(args, fmt);
2318
2319 setErrorStateLockedV(fmt, args);
2320
2321 va_end(args);
2322}
2323
2324void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002325 // Print out all error messages to log
2326 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002327 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002328
2329 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002330 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002331
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002332 mErrorCause = errorCause;
2333
2334 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002335 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002336
2337 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002338 sp<NotificationListener> listener = mListener.promote();
2339 if (listener != NULL) {
2340 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002341 CaptureResultExtras());
2342 }
2343
2344 // Save stack trace. View by dumping it later.
2345 CameraTraces::saveTrace();
2346 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002347}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002348
2349/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002350 * In-flight request management
2351 */
2352
Jianing Weicb0652e2014-03-12 18:29:36 -07002353status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002354 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002355 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002356 ATRACE_CALL();
2357 Mutex::Autolock l(mInFlightLock);
2358
2359 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002360 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002361 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002362 if (res < 0) return res;
2363
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002364 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002365 // hold mLock to prevent race with disconnect
2366 Mutex::Autolock l(mLock);
2367 if (mStatusTracker != nullptr) {
2368 mStatusTracker->markComponentActive(mInFlightStatusId);
2369 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002370 }
2371
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002372 return OK;
2373}
2374
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002375void Camera3Device::returnOutputBuffers(
2376 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2377 nsecs_t timestamp) {
2378 for (size_t i = 0; i < numBuffers; i++)
2379 {
2380 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2381 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2382 // Note: stream may be deallocated at this point, if this buffer was
2383 // the last reference to it.
2384 if (res != OK) {
2385 ALOGE("Can't return buffer to its stream: %s (%d)",
2386 strerror(-res), res);
2387 }
2388 }
2389}
2390
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002391void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2392 mInFlightMap.removeItemsAt(idx, 1);
2393
2394 // Indicate idle inFlightMap to the status tracker
2395 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002396 // hold mLock to prevent race with disconnect
2397 Mutex::Autolock l(mLock);
2398 if (mStatusTracker != nullptr) {
2399 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2400 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002401 }
2402}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002403
2404void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2405
2406 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2407 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2408
2409 nsecs_t sensorTimestamp = request.sensorTimestamp;
2410 nsecs_t shutterTimestamp = request.shutterTimestamp;
2411
Emilian Peevc6747862017-06-12 15:57:26 +01002412 bool skipResultMetadata = false;
2413 if (request.requestStatus != OK) {
2414 switch (request.requestStatus) {
2415 case CAMERA3_MSG_ERROR_DEVICE:
2416 case CAMERA3_MSG_ERROR_REQUEST:
2417 case CAMERA3_MSG_ERROR_RESULT:
2418 skipResultMetadata = true;
2419 break;
2420 case CAMERA3_MSG_ERROR_BUFFER:
2421 //Result metadata should return in this case.
2422 skipResultMetadata = false;
2423 break;
2424 default:
2425 SET_ERR("Unknown error message: %d", request.requestStatus);
2426 skipResultMetadata = false;
2427 break;
2428 }
2429 }
2430
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002431 // Check if it's okay to remove the request from InFlightMap:
2432 // In the case of a successful request:
2433 // all input and output buffers, all result metadata, shutter callback
2434 // arrived.
2435 // In the case of a unsuccessful request:
2436 // all input and output buffers arrived.
2437 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002438 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002439 (request.haveResultMetadata && shutterTimestamp != 0))) {
2440 ATRACE_ASYNC_END("frame capture", frameNumber);
2441
Shuzhen Wang403044a2017-02-26 23:29:04 -08002442 // Sanity check - if sensor timestamp matches shutter timestamp in the
2443 // case of request having callback.
2444 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002445 sensorTimestamp != shutterTimestamp) {
2446 SET_ERR("sensor timestamp (%" PRId64
2447 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2448 sensorTimestamp, frameNumber, shutterTimestamp);
2449 }
2450
2451 // for an unsuccessful request, it may have pending output buffers to
2452 // return.
2453 assert(request.requestStatus != OK ||
2454 request.pendingOutputBuffers.size() == 0);
2455 returnOutputBuffers(request.pendingOutputBuffers.array(),
2456 request.pendingOutputBuffers.size(), 0);
2457
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002458 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002459 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2460 }
2461
2462 // Sanity check - if we have too many in-flight frames, something has
2463 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002464 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002465 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002466 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2467 kInFlightWarnLimitHighSpeed) {
2468 CLOGE("In-flight list too large for high speed configuration: %zu",
2469 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002470 }
2471}
2472
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002473void Camera3Device::flushInflightRequests() {
2474 { // First return buffers cached in mInFlightMap
2475 Mutex::Autolock l(mInFlightLock);
2476 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2477 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2478 returnOutputBuffers(request.pendingOutputBuffers.array(),
2479 request.pendingOutputBuffers.size(), 0);
2480 }
2481 mInFlightMap.clear();
2482 }
2483
2484 // Then return all inflight buffers not returned by HAL
2485 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2486 mInterface->getInflightBufferKeys(&inflightKeys);
2487
2488 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2489 for (auto& pair : inflightKeys) {
2490 int32_t frameNumber = pair.first;
2491 int32_t streamId = pair.second;
2492 buffer_handle_t* buffer;
2493 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2494 if (res != OK) {
2495 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2496 __FUNCTION__, frameNumber, streamId);
2497 continue;
2498 }
2499
2500 camera3_stream_buffer_t streamBuffer;
2501 streamBuffer.buffer = buffer;
2502 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2503 streamBuffer.acquire_fence = -1;
2504 streamBuffer.release_fence = -1;
2505 if (streamId == inputStreamId) {
2506 streamBuffer.stream = mInputStream->asHalStream();
2507 res = mInputStream->returnInputBuffer(streamBuffer);
2508 if (res != OK) {
2509 ALOGE("%s: Can't return input buffer for frame %d to"
2510 " its stream:%s (%d)", __FUNCTION__,
2511 frameNumber, strerror(-res), res);
2512 }
2513 } else {
2514 streamBuffer.stream = mOutputStreams.valueFor(streamId)->asHalStream();
2515 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2516 }
2517 }
2518}
2519
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002520void Camera3Device::insertResultLocked(CaptureResult *result,
2521 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002522 if (result == nullptr) return;
2523
Emilian Peev71c73a22017-03-21 16:35:51 +00002524 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2525 result->mMetadata.getAndLock());
2526 set_camera_metadata_vendor_id(meta, mVendorTagId);
2527 result->mMetadata.unlock(meta);
2528
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002529 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2530 (int32_t*)&frameNumber, 1) != OK) {
2531 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2532 return;
2533 }
2534
2535 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2536 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2537 return;
2538 }
2539
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002540 // Valid result, insert into queue
2541 List<CaptureResult>::iterator queuedResult =
2542 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2543 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2544 ", burstId = %" PRId32, __FUNCTION__,
2545 queuedResult->mResultExtras.requestId,
2546 queuedResult->mResultExtras.frameNumber,
2547 queuedResult->mResultExtras.burstId);
2548
2549 mResultSignal.signal();
2550}
2551
2552
2553void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002554 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002555 Mutex::Autolock l(mOutputLock);
2556
2557 CaptureResult captureResult;
2558 captureResult.mResultExtras = resultExtras;
2559 captureResult.mMetadata = partialResult;
2560
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002561 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002562}
2563
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002564
2565void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2566 CaptureResultExtras &resultExtras,
2567 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002568 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002569 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002570 if (pendingMetadata.isEmpty())
2571 return;
2572
2573 Mutex::Autolock l(mOutputLock);
2574
2575 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002576 if (reprocess) {
2577 if (frameNumber < mNextReprocessResultFrameNumber) {
2578 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002579 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002580 frameNumber, mNextReprocessResultFrameNumber);
2581 return;
2582 }
2583 mNextReprocessResultFrameNumber = frameNumber + 1;
2584 } else {
2585 if (frameNumber < mNextResultFrameNumber) {
2586 SET_ERR("Out-of-order capture result metadata submitted! "
2587 "(got frame number %d, expecting %d)",
2588 frameNumber, mNextResultFrameNumber);
2589 return;
2590 }
2591 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002592 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002593
2594 CaptureResult captureResult;
2595 captureResult.mResultExtras = resultExtras;
2596 captureResult.mMetadata = pendingMetadata;
2597
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002598 // Append any previous partials to form a complete result
2599 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2600 captureResult.mMetadata.append(collectedPartialResult);
2601 }
2602
2603 captureResult.mMetadata.sort();
2604
2605 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002606 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2607 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002608 SET_ERR("No timestamp provided by HAL for frame %d!",
2609 frameNumber);
2610 return;
2611 }
2612
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002613 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2614 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2615
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002616 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002617}
2618
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002619/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620 * Camera HAL device callback methods
2621 */
2622
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002623void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002624 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002625
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002626 status_t res;
2627
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002628 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002629 if (result->result == NULL && result->num_output_buffers == 0 &&
2630 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002631 SET_ERR("No result data provided by HAL for frame %d",
2632 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002633 return;
2634 }
Zhijun He204e3292014-07-14 17:09:23 -07002635
Zhijun He204e3292014-07-14 17:09:23 -07002636 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002637 result->result != NULL &&
2638 result->partial_result != 1) {
2639 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2640 " if partial result is not supported",
2641 frameNumber, result->partial_result);
2642 return;
2643 }
2644
2645 bool isPartialResult = false;
2646 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002647 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002648 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002649
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002650 // Get shutter timestamp and resultExtras from list of in-flight requests,
2651 // where it was added by the shutter notification for this frame. If the
2652 // shutter timestamp isn't received yet, append the output buffers to the
2653 // in-flight request and they will be returned when the shutter timestamp
2654 // arrives. Update the in-flight status and remove the in-flight entry if
2655 // all result data and shutter timestamp have been received.
2656 nsecs_t shutterTimestamp = 0;
2657
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002658 {
2659 Mutex::Autolock l(mInFlightLock);
2660 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2661 if (idx == NAME_NOT_FOUND) {
2662 SET_ERR("Unknown frame number for capture result: %d",
2663 frameNumber);
2664 return;
2665 }
2666 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002667 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2668 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002669 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002670 __FUNCTION__, request.resultExtras.requestId,
2671 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002672 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002673 // Always update the partial count to the latest one if it's not 0
2674 // (buffers only). When framework aggregates adjacent partial results
2675 // into one, the latest partial count will be used.
2676 if (result->partial_result != 0)
2677 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002678
2679 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002680 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002681 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2682 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2683 " the range of [1, %d] when metadata is included in the result",
2684 frameNumber, result->partial_result, mNumPartialResults);
2685 return;
2686 }
2687 isPartialResult = (result->partial_result < mNumPartialResults);
2688 if (isPartialResult) {
2689 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002690 }
2691
Shuzhen Wang4a472662017-02-26 23:29:04 -08002692 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002693 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002694 sendPartialCaptureResult(result->result, request.resultExtras,
2695 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002696 }
2697 }
2698
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002699 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002700 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002701
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002702 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002703 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002704 if (request.haveResultMetadata) {
2705 SET_ERR("Called multiple times with metadata for frame %d",
2706 frameNumber);
2707 return;
2708 }
Zhijun He204e3292014-07-14 17:09:23 -07002709 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002710 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002711 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002712 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002713 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002714 request.haveResultMetadata = true;
2715 }
2716
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002717 uint32_t numBuffersReturned = result->num_output_buffers;
2718 if (result->input_buffer != NULL) {
2719 if (hasInputBufferInRequest) {
2720 numBuffersReturned += 1;
2721 } else {
2722 ALOGW("%s: Input buffer should be NULL if there is no input"
2723 " buffer sent in the request",
2724 __FUNCTION__);
2725 }
2726 }
2727 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002728 if (request.numBuffersLeft < 0) {
2729 SET_ERR("Too many buffers returned for frame %d",
2730 frameNumber);
2731 return;
2732 }
2733
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002734 camera_metadata_ro_entry_t entry;
2735 res = find_camera_metadata_ro_entry(result->result,
2736 ANDROID_SENSOR_TIMESTAMP, &entry);
2737 if (res == OK && entry.count == 1) {
2738 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002739 }
2740
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002741 // If shutter event isn't received yet, append the output buffers to
2742 // the in-flight request. Otherwise, return the output buffers to
2743 // streams.
2744 if (shutterTimestamp == 0) {
2745 request.pendingOutputBuffers.appendArray(result->output_buffers,
2746 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002747 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002748 returnOutputBuffers(result->output_buffers,
2749 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002750 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 if (result->result != NULL && !isPartialResult) {
2753 if (shutterTimestamp == 0) {
2754 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002755 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002756 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757 CameraMetadata metadata;
2758 metadata = result->result;
2759 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002760 collectedPartialResult, frameNumber,
2761 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002762 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002763 }
2764
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002765 removeInFlightRequestIfReadyLocked(idx);
2766 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002767
Zhijun Hef0d962a2014-06-30 10:24:11 -07002768 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002769 if (hasInputBufferInRequest) {
2770 Camera3Stream *stream =
2771 Camera3Stream::cast(result->input_buffer->stream);
2772 res = stream->returnInputBuffer(*(result->input_buffer));
2773 // Note: stream may be deallocated at this point, if this buffer was the
2774 // last reference to it.
2775 if (res != OK) {
2776 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2777 " its stream:%s (%d)", __FUNCTION__,
2778 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002779 }
2780 } else {
2781 ALOGW("%s: Input buffer should be NULL if there is no input"
2782 " buffer sent in the request, skipping input buffer return.",
2783 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002784 }
2785 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002786}
2787
2788void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002789 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002790 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002791 {
2792 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002793 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002794 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002795
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002796 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002797 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002798 return;
2799 }
2800
2801 switch (msg->type) {
2802 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002803 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002804 break;
2805 }
2806 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002807 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002808 break;
2809 }
2810 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002811 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002812 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002813 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002814}
2815
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002816void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002817 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002818
2819 // Map camera HAL error codes to ICameraDeviceCallback error codes
2820 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002821 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002822 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002823 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002824 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002825 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002826 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002827 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002828 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002829 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002830 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002831 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002832 };
2833
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002834 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 ((msg.error_code >= 0) &&
2836 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2837 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002838 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002839
2840 int streamId = 0;
2841 if (msg.error_stream != NULL) {
2842 Camera3Stream *stream =
2843 Camera3Stream::cast(msg.error_stream);
2844 streamId = stream->getId();
2845 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002846 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2847 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848 streamId, msg.error_code);
2849
2850 CaptureResultExtras resultExtras;
2851 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002852 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002853 // SET_ERR calls notifyError
2854 SET_ERR("Camera HAL reported serious device error");
2855 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002856 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2857 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2858 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859 {
2860 Mutex::Autolock l(mInFlightLock);
2861 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2862 if (idx >= 0) {
2863 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2864 r.requestStatus = msg.error_code;
2865 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002866 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2867 errorCode) {
2868 // In case of missing result check whether the buffers
2869 // returned. If they returned, then remove inflight
2870 // request.
2871 removeInFlightRequestIfReadyLocked(idx);
2872 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002873 } else {
2874 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002875 ALOGE("Camera %s: %s: cannot find in-flight request on "
2876 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002877 resultExtras.frameNumber);
2878 }
2879 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002880 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002881 if (listener != NULL) {
2882 listener->notifyError(errorCode, resultExtras);
2883 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002884 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 }
2886 break;
2887 default:
2888 // SET_ERR calls notifyError
2889 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2890 break;
2891 }
2892}
2893
2894void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002895 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002896 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002897
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002898 // Set timestamp for the request in the in-flight tracking
2899 // and get the request ID to send upstream
2900 {
2901 Mutex::Autolock l(mInFlightLock);
2902 idx = mInFlightMap.indexOfKey(msg.frame_number);
2903 if (idx >= 0) {
2904 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002905
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002906 // Verify ordering of shutter notifications
2907 {
2908 Mutex::Autolock l(mOutputLock);
2909 // TODO: need to track errors for tighter bounds on expected frame number.
2910 if (r.hasInputBuffer) {
2911 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2912 SET_ERR("Shutter notification out-of-order. Expected "
2913 "notification for frame %d, got frame %d",
2914 mNextReprocessShutterFrameNumber, msg.frame_number);
2915 return;
2916 }
2917 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2918 } else {
2919 if (msg.frame_number < mNextShutterFrameNumber) {
2920 SET_ERR("Shutter notification out-of-order. Expected "
2921 "notification for frame %d, got frame %d",
2922 mNextShutterFrameNumber, msg.frame_number);
2923 return;
2924 }
2925 mNextShutterFrameNumber = msg.frame_number + 1;
2926 }
2927 }
2928
Shuzhen Wang4a472662017-02-26 23:29:04 -08002929 r.shutterTimestamp = msg.timestamp;
2930 if (r.hasCallback) {
2931 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002932 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002933 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002934 // Call listener, if any
2935 if (listener != NULL) {
2936 listener->notifyShutter(r.resultExtras, msg.timestamp);
2937 }
2938 // send pending result and buffers
2939 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2940 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002941 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002942 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002943 returnOutputBuffers(r.pendingOutputBuffers.array(),
2944 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2945 r.pendingOutputBuffers.clear();
2946
2947 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002948 }
2949 }
2950 if (idx < 0) {
2951 SET_ERR("Shutter notification for non-existent frame number %d",
2952 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002953 }
2954}
2955
2956
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002957CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002958 ALOGV("%s", __FUNCTION__);
2959
Igor Murashkin1e479c02013-09-06 16:55:14 -07002960 CameraMetadata retVal;
2961
2962 if (mRequestThread != NULL) {
2963 retVal = mRequestThread->getLatestRequest();
2964 }
2965
Igor Murashkin1e479c02013-09-06 16:55:14 -07002966 return retVal;
2967}
2968
Jianing Weicb0652e2014-03-12 18:29:36 -07002969
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002970void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2971 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2972 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2973}
2974
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002975/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002976 * HalInterface inner class methods
2977 */
2978
Yifan Hongf79b5542017-04-11 14:44:25 -07002979Camera3Device::HalInterface::HalInterface(
2980 sp<ICameraDeviceSession> &session,
2981 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002982 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002983 mHidlSession(session),
2984 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002985
2986Camera3Device::HalInterface::HalInterface() :
2987 mHal3Device(nullptr) {}
2988
2989Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002990 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002991 mHidlSession(other.mHidlSession),
2992 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002993
2994bool Camera3Device::HalInterface::valid() {
2995 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2996}
2997
2998void Camera3Device::HalInterface::clear() {
2999 mHal3Device = nullptr;
3000 mHidlSession.clear();
3001}
3002
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003003bool Camera3Device::HalInterface::supportBatchRequest() {
3004 return mHidlSession != nullptr;
3005}
3006
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003007status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3008 camera3_request_template_t templateId,
3009 /*out*/ camera_metadata_t **requestTemplate) {
3010 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3011 if (!valid()) return INVALID_OPERATION;
3012 status_t res = OK;
3013
3014 if (mHal3Device != nullptr) {
3015 const camera_metadata *r;
3016 r = mHal3Device->ops->construct_default_request_settings(
3017 mHal3Device, templateId);
3018 if (r == nullptr) return BAD_VALUE;
3019 *requestTemplate = clone_camera_metadata(r);
3020 if (requestTemplate == nullptr) {
3021 ALOGE("%s: Unable to clone camera metadata received from HAL",
3022 __FUNCTION__);
3023 return INVALID_OPERATION;
3024 }
3025 } else {
3026 common::V1_0::Status status;
3027 RequestTemplate id;
3028 switch (templateId) {
3029 case CAMERA3_TEMPLATE_PREVIEW:
3030 id = RequestTemplate::PREVIEW;
3031 break;
3032 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3033 id = RequestTemplate::STILL_CAPTURE;
3034 break;
3035 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3036 id = RequestTemplate::VIDEO_RECORD;
3037 break;
3038 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3039 id = RequestTemplate::VIDEO_SNAPSHOT;
3040 break;
3041 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3042 id = RequestTemplate::ZERO_SHUTTER_LAG;
3043 break;
3044 case CAMERA3_TEMPLATE_MANUAL:
3045 id = RequestTemplate::MANUAL;
3046 break;
3047 default:
3048 // Unknown template ID
3049 return BAD_VALUE;
3050 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003051 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003052 [&status, &requestTemplate]
3053 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3054 status = s;
3055 if (status == common::V1_0::Status::OK) {
3056 const camera_metadata *r =
3057 reinterpret_cast<const camera_metadata_t*>(request.data());
3058 size_t expectedSize = request.size();
3059 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003060 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003061 *requestTemplate = clone_camera_metadata(r);
3062 if (*requestTemplate == nullptr) {
3063 ALOGE("%s: Unable to clone camera metadata received from HAL",
3064 __FUNCTION__);
3065 status = common::V1_0::Status::INTERNAL_ERROR;
3066 }
3067 } else {
3068 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3069 status = common::V1_0::Status::INTERNAL_ERROR;
3070 }
3071 }
3072 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003073 if (!err.isOk()) {
3074 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3075 res = DEAD_OBJECT;
3076 } else {
3077 res = CameraProviderManager::mapToStatusT(status);
3078 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003079 }
3080 return res;
3081}
3082
3083status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3084 ATRACE_NAME("CameraHal::configureStreams");
3085 if (!valid()) return INVALID_OPERATION;
3086 status_t res = OK;
3087
3088 if (mHal3Device != nullptr) {
3089 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3090 } else {
3091 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003092 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003093 StreamConfiguration requestedConfiguration;
3094 requestedConfiguration.streams.resize(config->num_streams);
3095 for (size_t i = 0; i < config->num_streams; i++) {
3096 Stream &dst = requestedConfiguration.streams[i];
3097 camera3_stream_t *src = config->streams[i];
3098
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003099 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3100 cam3stream->setBufferFreedListener(this);
3101 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003102 StreamType streamType;
3103 switch (src->stream_type) {
3104 case CAMERA3_STREAM_OUTPUT:
3105 streamType = StreamType::OUTPUT;
3106 break;
3107 case CAMERA3_STREAM_INPUT:
3108 streamType = StreamType::INPUT;
3109 break;
3110 default:
3111 ALOGE("%s: Stream %d: Unsupported stream type %d",
3112 __FUNCTION__, streamId, config->streams[i]->stream_type);
3113 return BAD_VALUE;
3114 }
3115 dst.id = streamId;
3116 dst.streamType = streamType;
3117 dst.width = src->width;
3118 dst.height = src->height;
3119 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003120 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003121 dst.dataSpace = mapToHidlDataspace(src->data_space);
3122 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003123
3124 activeStreams.insert(streamId);
3125 // Create Buffer ID map if necessary
3126 if (mBufferIdMaps.count(streamId) == 0) {
3127 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3128 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003129 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003130 // remove BufferIdMap for deleted streams
3131 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3132 int streamId = it->first;
3133 bool active = activeStreams.count(streamId) > 0;
3134 if (!active) {
3135 it = mBufferIdMaps.erase(it);
3136 } else {
3137 ++it;
3138 }
3139 }
3140
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003141 res = mapToStreamConfigurationMode(
3142 (camera3_stream_configuration_mode_t) config->operation_mode,
3143 /*out*/ &requestedConfiguration.operationMode);
3144 if (res != OK) {
3145 return res;
3146 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003147
3148 // Invoke configureStreams
3149
3150 HalStreamConfiguration finalConfiguration;
3151 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003152 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003153 [&status, &finalConfiguration]
3154 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3155 finalConfiguration = halConfiguration;
3156 status = s;
3157 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003158 if (!err.isOk()) {
3159 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3160 return DEAD_OBJECT;
3161 }
3162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003163 if (status != common::V1_0::Status::OK ) {
3164 return CameraProviderManager::mapToStatusT(status);
3165 }
3166
3167 // And convert output stream configuration from HIDL
3168
3169 for (size_t i = 0; i < config->num_streams; i++) {
3170 camera3_stream_t *dst = config->streams[i];
3171 int streamId = Camera3Stream::cast(dst)->getId();
3172
3173 // Start scan at i, with the assumption that the stream order matches
3174 size_t realIdx = i;
3175 bool found = false;
3176 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3177 if (finalConfiguration.streams[realIdx].id == streamId) {
3178 found = true;
3179 break;
3180 }
3181 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3182 }
3183 if (!found) {
3184 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3185 __FUNCTION__, streamId);
3186 return INVALID_OPERATION;
3187 }
3188 HalStream &src = finalConfiguration.streams[realIdx];
3189
3190 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3191 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3192 if (dst->format != overrideFormat) {
3193 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3194 streamId, dst->format);
3195 }
3196 } else {
3197 // Override allowed with IMPLEMENTATION_DEFINED
3198 dst->format = overrideFormat;
3199 }
3200
3201 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3202 if (src.producerUsage != 0) {
3203 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3204 __FUNCTION__, streamId);
3205 return INVALID_OPERATION;
3206 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003207 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003208 } else {
3209 // OUTPUT
3210 if (src.consumerUsage != 0) {
3211 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3212 __FUNCTION__, streamId);
3213 return INVALID_OPERATION;
3214 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003215 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003216 }
3217 dst->max_buffers = src.maxBuffers;
3218 }
3219 }
3220 return res;
3221}
3222
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003223void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3224 /*out*/device::V3_2::CaptureRequest* captureRequest,
3225 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3226
3227 if (captureRequest == nullptr || handlesCreated == nullptr) {
3228 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3229 __FUNCTION__, captureRequest, handlesCreated);
3230 return;
3231 }
3232
3233 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003234
3235 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003236
3237 {
3238 std::lock_guard<std::mutex> lock(mInflightLock);
3239 if (request->input_buffer != nullptr) {
3240 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3241 buffer_handle_t buf = *(request->input_buffer->buffer);
3242 auto pair = getBufferId(buf, streamId);
3243 bool isNewBuffer = pair.first;
3244 uint64_t bufferId = pair.second;
3245 captureRequest->inputBuffer.streamId = streamId;
3246 captureRequest->inputBuffer.bufferId = bufferId;
3247 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3248 captureRequest->inputBuffer.status = BufferStatus::OK;
3249 native_handle_t *acquireFence = nullptr;
3250 if (request->input_buffer->acquire_fence != -1) {
3251 acquireFence = native_handle_create(1,0);
3252 acquireFence->data[0] = request->input_buffer->acquire_fence;
3253 handlesCreated->push_back(acquireFence);
3254 }
3255 captureRequest->inputBuffer.acquireFence = acquireFence;
3256 captureRequest->inputBuffer.releaseFence = nullptr;
3257
3258 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3259 request->input_buffer->buffer,
3260 request->input_buffer->acquire_fence);
3261 } else {
3262 captureRequest->inputBuffer.streamId = -1;
3263 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3264 }
3265
3266 captureRequest->outputBuffers.resize(request->num_output_buffers);
3267 for (size_t i = 0; i < request->num_output_buffers; i++) {
3268 const camera3_stream_buffer_t *src = request->output_buffers + i;
3269 StreamBuffer &dst = captureRequest->outputBuffers[i];
3270 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3271 buffer_handle_t buf = *(src->buffer);
3272 auto pair = getBufferId(buf, streamId);
3273 bool isNewBuffer = pair.first;
3274 dst.streamId = streamId;
3275 dst.bufferId = pair.second;
3276 dst.buffer = isNewBuffer ? buf : nullptr;
3277 dst.status = BufferStatus::OK;
3278 native_handle_t *acquireFence = nullptr;
3279 if (src->acquire_fence != -1) {
3280 acquireFence = native_handle_create(1,0);
3281 acquireFence->data[0] = src->acquire_fence;
3282 handlesCreated->push_back(acquireFence);
3283 }
3284 dst.acquireFence = acquireFence;
3285 dst.releaseFence = nullptr;
3286
3287 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3288 src->buffer, src->acquire_fence);
3289 }
3290 }
3291}
3292
3293status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3294 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3295 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3296 if (!valid()) return INVALID_OPERATION;
3297
3298 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3299 size_t batchSize = requests.size();
3300 captureRequests.resize(batchSize);
3301 std::vector<native_handle_t*> handlesCreated;
3302
3303 for (size_t i = 0; i < batchSize; i++) {
3304 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3305 }
3306
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003307 std::vector<device::V3_2::BufferCache> cachesToRemove;
3308 {
3309 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3310 for (auto& pair : mFreedBuffers) {
3311 // The stream might have been removed since onBufferFreed
3312 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3313 cachesToRemove.push_back({pair.first, pair.second});
3314 }
3315 }
3316 mFreedBuffers.clear();
3317 }
3318
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003319 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3320 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003321
3322 // Write metadata to FMQ.
3323 for (size_t i = 0; i < batchSize; i++) {
3324 camera3_capture_request_t* request = requests[i];
3325 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3326
3327 if (request->settings != nullptr) {
3328 size_t settingsSize = get_camera_metadata_size(request->settings);
3329 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3330 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3331 captureRequest->settings.resize(0);
3332 captureRequest->fmqSettingsSize = settingsSize;
3333 } else {
3334 if (mRequestMetadataQueue != nullptr) {
3335 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3336 }
3337 captureRequest->settings.setToExternal(
3338 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3339 get_camera_metadata_size(request->settings));
3340 captureRequest->fmqSettingsSize = 0u;
3341 }
3342 } else {
3343 // A null request settings maps to a size-0 CameraMetadata
3344 captureRequest->settings.resize(0);
3345 captureRequest->fmqSettingsSize = 0u;
3346 }
3347 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003348 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003349 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3350 status = s;
3351 *numRequestProcessed = n;
3352 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003353 if (!err.isOk()) {
3354 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3355 return DEAD_OBJECT;
3356 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003357 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3358 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3359 __FUNCTION__, *numRequestProcessed, batchSize);
3360 status = common::V1_0::Status::INTERNAL_ERROR;
3361 }
3362
3363 for (auto& handle : handlesCreated) {
3364 native_handle_delete(handle);
3365 }
3366 return CameraProviderManager::mapToStatusT(status);
3367}
3368
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003369status_t Camera3Device::HalInterface::processCaptureRequest(
3370 camera3_capture_request_t *request) {
3371 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003372 if (!valid()) return INVALID_OPERATION;
3373 status_t res = OK;
3374
3375 if (mHal3Device != nullptr) {
3376 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3377 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003378 uint32_t numRequestProcessed = 0;
3379 std::vector<camera3_capture_request_t*> requests(1);
3380 requests[0] = request;
3381 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003382 }
3383 return res;
3384}
3385
3386status_t Camera3Device::HalInterface::flush() {
3387 ATRACE_NAME("CameraHal::flush");
3388 if (!valid()) return INVALID_OPERATION;
3389 status_t res = OK;
3390
3391 if (mHal3Device != nullptr) {
3392 res = mHal3Device->ops->flush(mHal3Device);
3393 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003394 auto err = mHidlSession->flush();
3395 if (!err.isOk()) {
3396 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3397 res = DEAD_OBJECT;
3398 } else {
3399 res = CameraProviderManager::mapToStatusT(err);
3400 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003401 }
3402 return res;
3403}
3404
3405status_t Camera3Device::HalInterface::dump(int fd) {
3406 ATRACE_NAME("CameraHal::dump");
3407 if (!valid()) return INVALID_OPERATION;
3408 status_t res = OK;
3409
3410 if (mHal3Device != nullptr) {
3411 mHal3Device->ops->dump(mHal3Device, fd);
3412 } else {
3413 // Handled by CameraProviderManager::dump
3414 }
3415 return res;
3416}
3417
3418status_t Camera3Device::HalInterface::close() {
3419 ATRACE_NAME("CameraHal::close()");
3420 if (!valid()) return INVALID_OPERATION;
3421 status_t res = OK;
3422
3423 if (mHal3Device != nullptr) {
3424 mHal3Device->common.close(&mHal3Device->common);
3425 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003426 auto err = mHidlSession->close();
3427 // Interface will be dead shortly anyway, so don't log errors
3428 if (!err.isOk()) {
3429 res = DEAD_OBJECT;
3430 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003431 }
3432 return res;
3433}
3434
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003435void Camera3Device::HalInterface::getInflightBufferKeys(
3436 std::vector<std::pair<int32_t, int32_t>>* out) {
3437 std::lock_guard<std::mutex> lock(mInflightLock);
3438 out->clear();
3439 out->reserve(mInflightBufferMap.size());
3440 for (auto& pair : mInflightBufferMap) {
3441 uint64_t key = pair.first;
3442 int32_t streamId = key & 0xFFFFFFFF;
3443 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3444 out->push_back(std::make_pair(frameNumber, streamId));
3445 }
3446 return;
3447}
3448
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003449status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003450 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003451 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003452 auto pair = std::make_pair(buffer, acquireFence);
3453 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003454 return OK;
3455}
3456
3457status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003458 int32_t frameNumber, int32_t streamId,
3459 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003460 std::lock_guard<std::mutex> lock(mInflightLock);
3461
3462 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3463 auto it = mInflightBufferMap.find(key);
3464 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003465 auto pair = it->second;
3466 *buffer = pair.first;
3467 int acquireFence = pair.second;
3468 if (acquireFence > 0) {
3469 ::close(acquireFence);
3470 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003471 mInflightBufferMap.erase(it);
3472 return OK;
3473}
3474
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003475std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3476 const buffer_handle_t& buf, int streamId) {
3477 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3478
3479 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3480 auto it = bIdMap.find(buf);
3481 if (it == bIdMap.end()) {
3482 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003483 ALOGV("stream %d now have %zu buffer caches, buf %p",
3484 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003485 return std::make_pair(true, mNextBufferId - 1);
3486 } else {
3487 return std::make_pair(false, it->second);
3488 }
3489}
3490
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003491void Camera3Device::HalInterface::onBufferFreed(
3492 int streamId, const native_handle_t* handle) {
3493 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3494 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3495 auto mapIt = mBufferIdMaps.find(streamId);
3496 if (mapIt == mBufferIdMaps.end()) {
3497 // streamId might be from a deleted stream here
3498 ALOGI("%s: stream %d has been removed",
3499 __FUNCTION__, streamId);
3500 return;
3501 }
3502 BufferIdMap& bIdMap = mapIt->second;
3503 auto it = bIdMap.find(handle);
3504 if (it == bIdMap.end()) {
3505 ALOGW("%s: cannot find buffer %p in stream %d",
3506 __FUNCTION__, handle, streamId);
3507 return;
3508 } else {
3509 bufferId = it->second;
3510 bIdMap.erase(it);
3511 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3512 __FUNCTION__, streamId, bIdMap.size(), handle);
3513 }
3514 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3515}
3516
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003517/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003518 * RequestThread inner class methods
3519 */
3520
3521Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003522 sp<StatusTracker> statusTracker,
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07003523 sp<HalInterface> interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003524 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003525 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003526 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003527 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003528 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003529 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003530 mReconfigured(false),
3531 mDoPause(false),
3532 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003533 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003534 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003535 mCurrentAfTriggerId(0),
3536 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003537 mRepeatingLastFrameNumber(
3538 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003539 mPrepareVideoStream(false),
3540 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003541 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003542}
3543
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003544Camera3Device::RequestThread::~RequestThread() {}
3545
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003546void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003547 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003548 Mutex::Autolock l(mRequestLock);
3549 mListener = listener;
3550}
3551
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003552void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003553 Mutex::Autolock l(mRequestLock);
3554 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003555 // Prepare video stream for high speed recording.
3556 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003557}
3558
Jianing Wei90e59c92014-03-12 18:29:36 -07003559status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003560 List<sp<CaptureRequest> > &requests,
3561 /*out*/
3562 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003563 Mutex::Autolock l(mRequestLock);
3564 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3565 ++it) {
3566 mRequestQueue.push_back(*it);
3567 }
3568
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003569 if (lastFrameNumber != NULL) {
3570 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3571 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3572 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3573 *lastFrameNumber);
3574 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003575
Jianing Wei90e59c92014-03-12 18:29:36 -07003576 unpauseForNewRequests();
3577
3578 return OK;
3579}
3580
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003581
3582status_t Camera3Device::RequestThread::queueTrigger(
3583 RequestTrigger trigger[],
3584 size_t count) {
3585
3586 Mutex::Autolock l(mTriggerMutex);
3587 status_t ret;
3588
3589 for (size_t i = 0; i < count; ++i) {
3590 ret = queueTriggerLocked(trigger[i]);
3591
3592 if (ret != OK) {
3593 return ret;
3594 }
3595 }
3596
3597 return OK;
3598}
3599
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003600const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3601 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003602 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003603 if (d != nullptr) return d->mId;
3604 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003605}
3606
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003607status_t Camera3Device::RequestThread::queueTriggerLocked(
3608 RequestTrigger trigger) {
3609
3610 uint32_t tag = trigger.metadataTag;
3611 ssize_t index = mTriggerMap.indexOfKey(tag);
3612
3613 switch (trigger.getTagType()) {
3614 case TYPE_BYTE:
3615 // fall-through
3616 case TYPE_INT32:
3617 break;
3618 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003619 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3620 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003621 return INVALID_OPERATION;
3622 }
3623
3624 /**
3625 * Collect only the latest trigger, since we only have 1 field
3626 * in the request settings per trigger tag, and can't send more than 1
3627 * trigger per request.
3628 */
3629 if (index != NAME_NOT_FOUND) {
3630 mTriggerMap.editValueAt(index) = trigger;
3631 } else {
3632 mTriggerMap.add(tag, trigger);
3633 }
3634
3635 return OK;
3636}
3637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003638status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003639 const RequestList &requests,
3640 /*out*/
3641 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003642 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003643 if (lastFrameNumber != NULL) {
3644 *lastFrameNumber = mRepeatingLastFrameNumber;
3645 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003646 mRepeatingRequests.clear();
3647 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3648 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003649
3650 unpauseForNewRequests();
3651
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003652 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003653 return OK;
3654}
3655
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003656bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003657 if (mRepeatingRequests.empty()) {
3658 return false;
3659 }
3660 int32_t requestId = requestIn->mResultExtras.requestId;
3661 const RequestList &repeatRequests = mRepeatingRequests;
3662 // All repeating requests are guaranteed to have same id so only check first quest
3663 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3664 return (firstRequest->mResultExtras.requestId == requestId);
3665}
3666
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003667status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003668 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003669 return clearRepeatingRequestsLocked(lastFrameNumber);
3670
3671}
3672
3673status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003674 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003675 if (lastFrameNumber != NULL) {
3676 *lastFrameNumber = mRepeatingLastFrameNumber;
3677 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003678 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003679 return OK;
3680}
3681
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003682status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003683 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003684 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003685 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003686
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003687 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003688
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003689 // Send errors for all requests pending in the request queue, including
3690 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003691 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003692 if (listener != NULL) {
3693 for (RequestList::iterator it = mRequestQueue.begin();
3694 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003695 // Abort the input buffers for reprocess requests.
3696 if ((*it)->mInputStream != NULL) {
3697 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003698 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3699 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003700 if (res != OK) {
3701 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3702 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3703 } else {
3704 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3705 if (res != OK) {
3706 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3707 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3708 }
3709 }
3710 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003711 // Set the frame number this request would have had, if it
3712 // had been submitted; this frame number will not be reused.
3713 // The requestId and burstId fields were set when the request was
3714 // submitted originally (in convertMetadataListToRequestListLocked)
3715 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003716 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003717 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003718 }
3719 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003720 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003721
3722 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003723 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003724 if (lastFrameNumber != NULL) {
3725 *lastFrameNumber = mRepeatingLastFrameNumber;
3726 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003727 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003728 return OK;
3729}
3730
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003731status_t Camera3Device::RequestThread::flush() {
3732 ATRACE_CALL();
3733 Mutex::Autolock l(mFlushLock);
3734
Emilian Peev08dd2452017-04-06 16:55:14 +01003735 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003736}
3737
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003738void Camera3Device::RequestThread::setPaused(bool paused) {
3739 Mutex::Autolock l(mPauseLock);
3740 mDoPause = paused;
3741 mDoPauseSignal.signal();
3742}
3743
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003744status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3745 int32_t requestId, nsecs_t timeout) {
3746 Mutex::Autolock l(mLatestRequestMutex);
3747 status_t res;
3748 while (mLatestRequestId != requestId) {
3749 nsecs_t startTime = systemTime();
3750
3751 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3752 if (res != OK) return res;
3753
3754 timeout -= (systemTime() - startTime);
3755 }
3756
3757 return OK;
3758}
3759
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003760void Camera3Device::RequestThread::requestExit() {
3761 // Call parent to set up shutdown
3762 Thread::requestExit();
3763 // The exit from any possible waits
3764 mDoPauseSignal.signal();
3765 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003766
3767 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3768 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003769}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003770
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003771void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003772 bool surfaceAbandoned = false;
3773 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003774 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003775 {
3776 Mutex::Autolock l(mRequestLock);
3777 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3778 // repeating requests.
3779 for (const auto& request : mRepeatingRequests) {
3780 for (const auto& s : request->mOutputStreams) {
3781 if (s->isAbandoned()) {
3782 surfaceAbandoned = true;
3783 clearRepeatingRequestsLocked(&lastFrameNumber);
3784 break;
3785 }
3786 }
3787 if (surfaceAbandoned) {
3788 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003789 }
3790 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003791 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003792 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003793
3794 if (listener != NULL && surfaceAbandoned) {
3795 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003796 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003797}
3798
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003799bool Camera3Device::RequestThread::sendRequestsBatch() {
3800 status_t res;
3801 size_t batchSize = mNextRequests.size();
3802 std::vector<camera3_capture_request_t*> requests(batchSize);
3803 uint32_t numRequestProcessed = 0;
3804 for (size_t i = 0; i < batchSize; i++) {
3805 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3806 }
3807
3808 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3809 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3810
3811 bool triggerRemoveFailed = false;
3812 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3813 for (size_t i = 0; i < numRequestProcessed; i++) {
3814 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3815 nextRequest.submitted = true;
3816
3817
3818 // Update the latest request sent to HAL
3819 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3820 Mutex::Autolock al(mLatestRequestMutex);
3821
3822 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3823 mLatestRequest.acquire(cloned);
3824
3825 sp<Camera3Device> parent = mParent.promote();
3826 if (parent != NULL) {
3827 parent->monitorMetadata(TagMonitor::REQUEST,
3828 nextRequest.halRequest.frame_number,
3829 0, mLatestRequest);
3830 }
3831 }
3832
3833 if (nextRequest.halRequest.settings != NULL) {
3834 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3835 }
3836
3837 if (!triggerRemoveFailed) {
3838 // Remove any previously queued triggers (after unlock)
3839 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3840 if (removeTriggerRes != OK) {
3841 triggerRemoveFailed = true;
3842 triggerFailedRequest = nextRequest;
3843 }
3844 }
3845 }
3846
3847 if (triggerRemoveFailed) {
3848 SET_ERR("RequestThread: Unable to remove triggers "
3849 "(capture request %d, HAL device: %s (%d)",
3850 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3851 cleanUpFailedRequests(/*sendRequestError*/ false);
3852 return false;
3853 }
3854
3855 if (res != OK) {
3856 // Should only get a failure here for malformed requests or device-level
3857 // errors, so consider all errors fatal. Bad metadata failures should
3858 // come through notify.
3859 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3860 mNextRequests[numRequestProcessed].halRequest.frame_number,
3861 strerror(-res), res);
3862 cleanUpFailedRequests(/*sendRequestError*/ false);
3863 return false;
3864 }
3865 return true;
3866}
3867
3868bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3869 status_t res;
3870
3871 for (auto& nextRequest : mNextRequests) {
3872 // Submit request and block until ready for next one
3873 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3874 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3875
3876 if (res != OK) {
3877 // Should only get a failure here for malformed requests or device-level
3878 // errors, so consider all errors fatal. Bad metadata failures should
3879 // come through notify.
3880 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3881 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3882 res);
3883 cleanUpFailedRequests(/*sendRequestError*/ false);
3884 return false;
3885 }
3886
3887 // Mark that the request has be submitted successfully.
3888 nextRequest.submitted = true;
3889
3890 // Update the latest request sent to HAL
3891 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3892 Mutex::Autolock al(mLatestRequestMutex);
3893
3894 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3895 mLatestRequest.acquire(cloned);
3896
3897 sp<Camera3Device> parent = mParent.promote();
3898 if (parent != NULL) {
3899 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3900 0, mLatestRequest);
3901 }
3902 }
3903
3904 if (nextRequest.halRequest.settings != NULL) {
3905 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3906 }
3907
3908 // Remove any previously queued triggers (after unlock)
3909 res = removeTriggers(mPrevRequest);
3910 if (res != OK) {
3911 SET_ERR("RequestThread: Unable to remove triggers "
3912 "(capture request %d, HAL device: %s (%d)",
3913 nextRequest.halRequest.frame_number, strerror(-res), res);
3914 cleanUpFailedRequests(/*sendRequestError*/ false);
3915 return false;
3916 }
3917 }
3918 return true;
3919}
3920
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003921bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003922 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003923 status_t res;
3924
3925 // Handle paused state.
3926 if (waitIfPaused()) {
3927 return true;
3928 }
3929
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003930 // Wait for the next batch of requests.
3931 waitForNextRequestBatch();
3932 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003933 return true;
3934 }
3935
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003936 // Get the latest request ID, if any
3937 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003938 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003939 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003940 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003941 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003942 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003943 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3944 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003945 }
3946
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003947 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003948 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003949 if (res == TIMED_OUT) {
3950 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003951 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003952 // Check if any stream is abandoned.
3953 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003954 return true;
3955 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003956 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003957 return false;
3958 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003959
Zhijun Hecc27e112013-10-03 16:12:43 -07003960 // Inform waitUntilRequestProcessed thread of a new request ID
3961 {
3962 Mutex::Autolock al(mLatestRequestMutex);
3963
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003964 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003965 mLatestRequestSignal.signal();
3966 }
3967
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003968 // Submit a batch of requests to HAL.
3969 // Use flush lock only when submitting multilple requests in a batch.
3970 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3971 // which may take a long time to finish so synchronizing flush() and
3972 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3973 // For now, only synchronize for high speed recording and we should figure something out for
3974 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003975 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003976
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003977 if (useFlushLock) {
3978 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003979 }
3980
Zhijun Hef0645c12016-08-02 00:58:11 -07003981 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003982 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003983
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003984 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003985 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003986 if (mInterface->supportBatchRequest()) {
3987 submitRequestSuccess = sendRequestsBatch();
3988 } else {
3989 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003990 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07003991 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3992 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003993
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003994 if (useFlushLock) {
3995 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003996 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003997
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003998 // Unset as current request
3999 {
4000 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004001 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004002 }
4003
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004004 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004005}
4006
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004007status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004008 ATRACE_CALL();
4009
Shuzhen Wang4a472662017-02-26 23:29:04 -08004010 for (size_t i = 0; i < mNextRequests.size(); i++) {
4011 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004012 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4013 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4014 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4015
4016 // Prepare a request to HAL
4017 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4018
4019 // Insert any queued triggers (before metadata is locked)
4020 status_t res = insertTriggers(captureRequest);
4021
4022 if (res < 0) {
4023 SET_ERR("RequestThread: Unable to insert triggers "
4024 "(capture request %d, HAL device: %s (%d)",
4025 halRequest->frame_number, strerror(-res), res);
4026 return INVALID_OPERATION;
4027 }
4028 int triggerCount = res;
4029 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4030 mPrevTriggers = triggerCount;
4031
4032 // If the request is the same as last, or we had triggers last time
4033 if (mPrevRequest != captureRequest || triggersMixedIn) {
4034 /**
4035 * HAL workaround:
4036 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4037 */
4038 res = addDummyTriggerIds(captureRequest);
4039 if (res != OK) {
4040 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4041 "(capture request %d, HAL device: %s (%d)",
4042 halRequest->frame_number, strerror(-res), res);
4043 return INVALID_OPERATION;
4044 }
4045
4046 /**
4047 * The request should be presorted so accesses in HAL
4048 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4049 */
4050 captureRequest->mSettings.sort();
4051 halRequest->settings = captureRequest->mSettings.getAndLock();
4052 mPrevRequest = captureRequest;
4053 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4054
4055 IF_ALOGV() {
4056 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4057 find_camera_metadata_ro_entry(
4058 halRequest->settings,
4059 ANDROID_CONTROL_AF_TRIGGER,
4060 &e
4061 );
4062 if (e.count > 0) {
4063 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4064 __FUNCTION__,
4065 halRequest->frame_number,
4066 e.data.u8[0]);
4067 }
4068 }
4069 } else {
4070 // leave request.settings NULL to indicate 'reuse latest given'
4071 ALOGVV("%s: Request settings are REUSED",
4072 __FUNCTION__);
4073 }
4074
4075 uint32_t totalNumBuffers = 0;
4076
4077 // Fill in buffers
4078 if (captureRequest->mInputStream != NULL) {
4079 halRequest->input_buffer = &captureRequest->mInputBuffer;
4080 totalNumBuffers += 1;
4081 } else {
4082 halRequest->input_buffer = NULL;
4083 }
4084
4085 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4086 captureRequest->mOutputStreams.size());
4087 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004088 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4089 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004090
4091 // Prepare video buffers for high speed recording on the first video request.
4092 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4093 // Only try to prepare video stream on the first video request.
4094 mPrepareVideoStream = false;
4095
4096 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4097 while (res == NOT_ENOUGH_DATA) {
4098 res = outputStream->prepareNextBuffer();
4099 }
4100 if (res != OK) {
4101 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4102 __FUNCTION__, strerror(-res), res);
4103 outputStream->cancelPrepare();
4104 }
4105 }
4106
Shuzhen Wang4a472662017-02-26 23:29:04 -08004107 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4108 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004109 if (res != OK) {
4110 // Can't get output buffer from gralloc queue - this could be due to
4111 // abandoned queue or other consumer misbehavior, so not a fatal
4112 // error
4113 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4114 " %s (%d)", strerror(-res), res);
4115
4116 return TIMED_OUT;
4117 }
4118 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004119
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004120 }
4121 totalNumBuffers += halRequest->num_output_buffers;
4122
4123 // Log request in the in-flight queue
4124 sp<Camera3Device> parent = mParent.promote();
4125 if (parent == NULL) {
4126 // Should not happen, and nowhere to send errors to, so just log it
4127 CLOGE("RequestThread: Parent is gone");
4128 return INVALID_OPERATION;
4129 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004130
4131 // If this request list is for constrained high speed recording (not
4132 // preview), and the current request is not the last one in the batch,
4133 // do not send callback to the app.
4134 bool hasCallback = true;
4135 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4136 hasCallback = false;
4137 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004138 res = parent->registerInFlight(halRequest->frame_number,
4139 totalNumBuffers, captureRequest->mResultExtras,
4140 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004141 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004142 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4143 ", burstId = %" PRId32 ".",
4144 __FUNCTION__,
4145 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4146 captureRequest->mResultExtras.burstId);
4147 if (res != OK) {
4148 SET_ERR("RequestThread: Unable to register new in-flight request:"
4149 " %s (%d)", strerror(-res), res);
4150 return INVALID_OPERATION;
4151 }
4152 }
4153
4154 return OK;
4155}
4156
Igor Murashkin1e479c02013-09-06 16:55:14 -07004157CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4158 Mutex::Autolock al(mLatestRequestMutex);
4159
4160 ALOGV("RequestThread::%s", __FUNCTION__);
4161
4162 return mLatestRequest;
4163}
4164
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004165bool Camera3Device::RequestThread::isStreamPending(
4166 sp<Camera3StreamInterface>& stream) {
4167 Mutex::Autolock l(mRequestLock);
4168
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004169 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004170 if (!nextRequest.submitted) {
4171 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4172 if (stream == s) return true;
4173 }
4174 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004175 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004176 }
4177
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004178 for (const auto& request : mRequestQueue) {
4179 for (const auto& s : request->mOutputStreams) {
4180 if (stream == s) return true;
4181 }
4182 if (stream == request->mInputStream) return true;
4183 }
4184
4185 for (const auto& request : mRepeatingRequests) {
4186 for (const auto& s : request->mOutputStreams) {
4187 if (stream == s) return true;
4188 }
4189 if (stream == request->mInputStream) return true;
4190 }
4191
4192 return false;
4193}
Jianing Weicb0652e2014-03-12 18:29:36 -07004194
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004195void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4196 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004197 return;
4198 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004200 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004201 // Skip the ones that have been submitted successfully.
4202 if (nextRequest.submitted) {
4203 continue;
4204 }
4205
4206 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4207 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4208 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4209
4210 if (halRequest->settings != NULL) {
4211 captureRequest->mSettings.unlock(halRequest->settings);
4212 }
4213
4214 if (captureRequest->mInputStream != NULL) {
4215 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4216 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4217 }
4218
4219 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004220 //Buffers that failed processing could still have
4221 //valid acquire fence.
4222 int acquireFence = (*outputBuffers)[i].acquire_fence;
4223 if (0 <= acquireFence) {
4224 close(acquireFence);
4225 outputBuffers->editItemAt(i).acquire_fence = -1;
4226 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004227 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4228 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4229 }
4230
4231 if (sendRequestError) {
4232 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004233 sp<NotificationListener> listener = mListener.promote();
4234 if (listener != NULL) {
4235 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004236 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004237 captureRequest->mResultExtras);
4238 }
4239 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004240
4241 // Remove yet-to-be submitted inflight request from inflightMap
4242 {
4243 sp<Camera3Device> parent = mParent.promote();
4244 if (parent != NULL) {
4245 Mutex::Autolock l(parent->mInFlightLock);
4246 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4247 if (idx >= 0) {
4248 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4249 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4250 parent->removeInFlightMapEntryLocked(idx);
4251 }
4252 }
4253 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004254 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004255
4256 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004257 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258}
4259
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004260void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004261 // Optimized a bit for the simple steady-state case (single repeating
4262 // request), to avoid putting that request in the queue temporarily.
4263 Mutex::Autolock l(mRequestLock);
4264
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004265 assert(mNextRequests.empty());
4266
4267 NextRequest nextRequest;
4268 nextRequest.captureRequest = waitForNextRequestLocked();
4269 if (nextRequest.captureRequest == nullptr) {
4270 return;
4271 }
4272
4273 nextRequest.halRequest = camera3_capture_request_t();
4274 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004275 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004276
4277 // Wait for additional requests
4278 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4279
4280 for (size_t i = 1; i < batchSize; i++) {
4281 NextRequest additionalRequest;
4282 additionalRequest.captureRequest = waitForNextRequestLocked();
4283 if (additionalRequest.captureRequest == nullptr) {
4284 break;
4285 }
4286
4287 additionalRequest.halRequest = camera3_capture_request_t();
4288 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004289 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004290 }
4291
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004292 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004293 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004294 mNextRequests.size(), batchSize);
4295 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004296 }
4297
4298 return;
4299}
4300
4301sp<Camera3Device::CaptureRequest>
4302 Camera3Device::RequestThread::waitForNextRequestLocked() {
4303 status_t res;
4304 sp<CaptureRequest> nextRequest;
4305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306 while (mRequestQueue.empty()) {
4307 if (!mRepeatingRequests.empty()) {
4308 // Always atomically enqueue all requests in a repeating request
4309 // list. Guarantees a complete in-sequence set of captures to
4310 // application.
4311 const RequestList &requests = mRepeatingRequests;
4312 RequestList::const_iterator firstRequest =
4313 requests.begin();
4314 nextRequest = *firstRequest;
4315 mRequestQueue.insert(mRequestQueue.end(),
4316 ++firstRequest,
4317 requests.end());
4318 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004319
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004320 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004321
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 break;
4323 }
4324
4325 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4326
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004327 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4328 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329 Mutex::Autolock pl(mPauseLock);
4330 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004331 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004332 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004333 // Let the tracker know
4334 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4335 if (statusTracker != 0) {
4336 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4337 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 }
4339 // Stop waiting for now and let thread management happen
4340 return NULL;
4341 }
4342 }
4343
4344 if (nextRequest == NULL) {
4345 // Don't have a repeating request already in hand, so queue
4346 // must have an entry now.
4347 RequestList::iterator firstRequest =
4348 mRequestQueue.begin();
4349 nextRequest = *firstRequest;
4350 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004351 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4352 sp<NotificationListener> listener = mListener.promote();
4353 if (listener != NULL) {
4354 listener->notifyRequestQueueEmpty();
4355 }
4356 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 }
4358
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004359 // In case we've been unpaused by setPaused clearing mDoPause, need to
4360 // update internal pause state (capture/setRepeatingRequest unpause
4361 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004362 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004363 if (mPaused) {
4364 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4365 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4366 if (statusTracker != 0) {
4367 statusTracker->markComponentActive(mStatusId);
4368 }
4369 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004370 mPaused = false;
4371
4372 // Check if we've reconfigured since last time, and reset the preview
4373 // request if so. Can't use 'NULL request == repeat' across configure calls.
4374 if (mReconfigured) {
4375 mPrevRequest.clear();
4376 mReconfigured = false;
4377 }
4378
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004379 if (nextRequest != NULL) {
4380 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004381 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4382 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004383
4384 // Since RequestThread::clear() removes buffers from the input stream,
4385 // get the right buffer here before unlocking mRequestLock
4386 if (nextRequest->mInputStream != NULL) {
4387 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4388 if (res != OK) {
4389 // Can't get input buffer from gralloc queue - this could be due to
4390 // disconnected queue or other producer misbehavior, so not a fatal
4391 // error
4392 ALOGE("%s: Can't get input buffer, skipping request:"
4393 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004394
4395 sp<NotificationListener> listener = mListener.promote();
4396 if (listener != NULL) {
4397 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004398 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004399 nextRequest->mResultExtras);
4400 }
4401 return NULL;
4402 }
4403 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004404 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004405
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004406 return nextRequest;
4407}
4408
4409bool Camera3Device::RequestThread::waitIfPaused() {
4410 status_t res;
4411 Mutex::Autolock l(mPauseLock);
4412 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 if (mPaused == false) {
4414 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004415 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4416 // Let the tracker know
4417 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4418 if (statusTracker != 0) {
4419 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4420 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004421 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004422
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004423 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004424 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004425 return true;
4426 }
4427 }
4428 // We don't set mPaused to false here, because waitForNextRequest needs
4429 // to further manage the paused state in case of starvation.
4430 return false;
4431}
4432
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004433void Camera3Device::RequestThread::unpauseForNewRequests() {
4434 // With work to do, mark thread as unpaused.
4435 // If paused by request (setPaused), don't resume, to avoid
4436 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004437 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004438 Mutex::Autolock p(mPauseLock);
4439 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004440 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4441 if (mPaused) {
4442 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4443 if (statusTracker != 0) {
4444 statusTracker->markComponentActive(mStatusId);
4445 }
4446 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004447 mPaused = false;
4448 }
4449}
4450
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004451void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4452 sp<Camera3Device> parent = mParent.promote();
4453 if (parent != NULL) {
4454 va_list args;
4455 va_start(args, fmt);
4456
4457 parent->setErrorStateV(fmt, args);
4458
4459 va_end(args);
4460 }
4461}
4462
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004463status_t Camera3Device::RequestThread::insertTriggers(
4464 const sp<CaptureRequest> &request) {
4465
4466 Mutex::Autolock al(mTriggerMutex);
4467
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004468 sp<Camera3Device> parent = mParent.promote();
4469 if (parent == NULL) {
4470 CLOGE("RequestThread: Parent is gone");
4471 return DEAD_OBJECT;
4472 }
4473
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004474 CameraMetadata &metadata = request->mSettings;
4475 size_t count = mTriggerMap.size();
4476
4477 for (size_t i = 0; i < count; ++i) {
4478 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004479 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004480
4481 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4482 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4483 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004484 if (isAeTrigger) {
4485 request->mResultExtras.precaptureTriggerId = triggerId;
4486 mCurrentPreCaptureTriggerId = triggerId;
4487 } else {
4488 request->mResultExtras.afTriggerId = triggerId;
4489 mCurrentAfTriggerId = triggerId;
4490 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004491 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004492 }
4493
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004494 camera_metadata_entry entry = metadata.find(tag);
4495
4496 if (entry.count > 0) {
4497 /**
4498 * Already has an entry for this trigger in the request.
4499 * Rewrite it with our requested trigger value.
4500 */
4501 RequestTrigger oldTrigger = trigger;
4502
4503 oldTrigger.entryValue = entry.data.u8[0];
4504
4505 mTriggerReplacedMap.add(tag, oldTrigger);
4506 } else {
4507 /**
4508 * More typical, no trigger entry, so we just add it
4509 */
4510 mTriggerRemovedMap.add(tag, trigger);
4511 }
4512
4513 status_t res;
4514
4515 switch (trigger.getTagType()) {
4516 case TYPE_BYTE: {
4517 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4518 res = metadata.update(tag,
4519 &entryValue,
4520 /*count*/1);
4521 break;
4522 }
4523 case TYPE_INT32:
4524 res = metadata.update(tag,
4525 &trigger.entryValue,
4526 /*count*/1);
4527 break;
4528 default:
4529 ALOGE("%s: Type not supported: 0x%x",
4530 __FUNCTION__,
4531 trigger.getTagType());
4532 return INVALID_OPERATION;
4533 }
4534
4535 if (res != OK) {
4536 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4537 ", value %d", __FUNCTION__, trigger.getTagName(),
4538 trigger.entryValue);
4539 return res;
4540 }
4541
4542 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4543 trigger.getTagName(),
4544 trigger.entryValue);
4545 }
4546
4547 mTriggerMap.clear();
4548
4549 return count;
4550}
4551
4552status_t Camera3Device::RequestThread::removeTriggers(
4553 const sp<CaptureRequest> &request) {
4554 Mutex::Autolock al(mTriggerMutex);
4555
4556 CameraMetadata &metadata = request->mSettings;
4557
4558 /**
4559 * Replace all old entries with their old values.
4560 */
4561 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4562 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4563
4564 status_t res;
4565
4566 uint32_t tag = trigger.metadataTag;
4567 switch (trigger.getTagType()) {
4568 case TYPE_BYTE: {
4569 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4570 res = metadata.update(tag,
4571 &entryValue,
4572 /*count*/1);
4573 break;
4574 }
4575 case TYPE_INT32:
4576 res = metadata.update(tag,
4577 &trigger.entryValue,
4578 /*count*/1);
4579 break;
4580 default:
4581 ALOGE("%s: Type not supported: 0x%x",
4582 __FUNCTION__,
4583 trigger.getTagType());
4584 return INVALID_OPERATION;
4585 }
4586
4587 if (res != OK) {
4588 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4589 ", trigger value %d", __FUNCTION__,
4590 trigger.getTagName(), trigger.entryValue);
4591 return res;
4592 }
4593 }
4594 mTriggerReplacedMap.clear();
4595
4596 /**
4597 * Remove all new entries.
4598 */
4599 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4600 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4601 status_t res = metadata.erase(trigger.metadataTag);
4602
4603 if (res != OK) {
4604 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4605 ", trigger value %d", __FUNCTION__,
4606 trigger.getTagName(), trigger.entryValue);
4607 return res;
4608 }
4609 }
4610 mTriggerRemovedMap.clear();
4611
4612 return OK;
4613}
4614
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004615status_t Camera3Device::RequestThread::addDummyTriggerIds(
4616 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004617 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004618 static const int32_t dummyTriggerId = 1;
4619 status_t res;
4620
4621 CameraMetadata &metadata = request->mSettings;
4622
4623 // If AF trigger is active, insert a dummy AF trigger ID if none already
4624 // exists
4625 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4626 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4627 if (afTrigger.count > 0 &&
4628 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4629 afId.count == 0) {
4630 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4631 if (res != OK) return res;
4632 }
4633
4634 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4635 // if none already exists
4636 camera_metadata_entry pcTrigger =
4637 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4638 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4639 if (pcTrigger.count > 0 &&
4640 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4641 pcId.count == 0) {
4642 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4643 &dummyTriggerId, 1);
4644 if (res != OK) return res;
4645 }
4646
4647 return OK;
4648}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004649
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004650/**
4651 * PreparerThread inner class methods
4652 */
4653
4654Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004655 Thread(/*canCallJava*/false), mListener(nullptr),
4656 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004657}
4658
4659Camera3Device::PreparerThread::~PreparerThread() {
4660 Thread::requestExitAndWait();
4661 if (mCurrentStream != nullptr) {
4662 mCurrentStream->cancelPrepare();
4663 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4664 mCurrentStream.clear();
4665 }
4666 clear();
4667}
4668
Ruben Brunkc78ac262015-08-13 17:58:46 -07004669status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004670 status_t res;
4671
4672 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004673 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004674
Ruben Brunkc78ac262015-08-13 17:58:46 -07004675 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004676 if (res == OK) {
4677 // No preparation needed, fire listener right off
4678 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004679 if (listener != NULL) {
4680 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004681 }
4682 return OK;
4683 } else if (res != NOT_ENOUGH_DATA) {
4684 return res;
4685 }
4686
4687 // Need to prepare, start up thread if necessary
4688 if (!mActive) {
4689 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4690 // isn't running
4691 Thread::requestExitAndWait();
4692 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4693 if (res != OK) {
4694 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004695 if (listener != NULL) {
4696 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004697 }
4698 return res;
4699 }
4700 mCancelNow = false;
4701 mActive = true;
4702 ALOGV("%s: Preparer stream started", __FUNCTION__);
4703 }
4704
4705 // queue up the work
4706 mPendingStreams.push_back(stream);
4707 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4708
4709 return OK;
4710}
4711
4712status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004713 Mutex::Autolock l(mLock);
4714
4715 for (const auto& stream : mPendingStreams) {
4716 stream->cancelPrepare();
4717 }
4718 mPendingStreams.clear();
4719 mCancelNow = true;
4720
4721 return OK;
4722}
4723
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004724void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004725 Mutex::Autolock l(mLock);
4726 mListener = listener;
4727}
4728
4729bool Camera3Device::PreparerThread::threadLoop() {
4730 status_t res;
4731 {
4732 Mutex::Autolock l(mLock);
4733 if (mCurrentStream == nullptr) {
4734 // End thread if done with work
4735 if (mPendingStreams.empty()) {
4736 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4737 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4738 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4739 mActive = false;
4740 return false;
4741 }
4742
4743 // Get next stream to prepare
4744 auto it = mPendingStreams.begin();
4745 mCurrentStream = *it;
4746 mPendingStreams.erase(it);
4747 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4748 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4749 } else if (mCancelNow) {
4750 mCurrentStream->cancelPrepare();
4751 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4752 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4753 mCurrentStream.clear();
4754 mCancelNow = false;
4755 return true;
4756 }
4757 }
4758
4759 res = mCurrentStream->prepareNextBuffer();
4760 if (res == NOT_ENOUGH_DATA) return true;
4761 if (res != OK) {
4762 // Something bad happened; try to recover by cancelling prepare and
4763 // signalling listener anyway
4764 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4765 mCurrentStream->getId(), res, strerror(-res));
4766 mCurrentStream->cancelPrepare();
4767 }
4768
4769 // This stream has finished, notify listener
4770 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004771 sp<NotificationListener> listener = mListener.promote();
4772 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004773 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4774 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004775 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776 }
4777
4778 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4779 mCurrentStream.clear();
4780
4781 return true;
4782}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004783
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004784/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004785 * Static callback forwarding methods from HAL to instance
4786 */
4787
4788void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4789 const camera3_capture_result *result) {
4790 Camera3Device *d =
4791 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004792
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004793 d->processCaptureResult(result);
4794}
4795
4796void Camera3Device::sNotify(const camera3_callback_ops *cb,
4797 const camera3_notify_msg *msg) {
4798 Camera3Device *d =
4799 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4800 d->notify(msg);
4801}
4802
4803}; // namespace android