blob: e022057cd751a08a6e0d39196b40a3525589a333 [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 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700141 auto resultQueueRet = session->getCaptureResultMetadataQueue(
142 [&queue = mResultMetadataQueue](const auto& descriptor) {
143 queue = std::make_unique<ResultMetadataQueue>(descriptor);
144 if (!queue->isValid() || queue->availableToWrite() <= 0) {
145 ALOGE("HAL returns empty result metadata fmq, not use it");
146 queue = nullptr;
147 // Don't use the queue onwards.
148 }
149 });
150 if (!resultQueueRet.isOk()) {
151 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
152 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700153 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700154 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700155
Yifan Hongf79b5542017-04-11 14:44:25 -0700156 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000157 std::string providerType;
158 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800159
160 return initializeCommonLocked();
161}
162
163status_t Camera3Device::initializeCommonLocked() {
164
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700165 /** Start up status tracker thread */
166 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800167 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700168 if (res != OK) {
169 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
170 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800171 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700172 mStatusTracker.clear();
173 return res;
174 }
175
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700176 /** Register in-flight map to the status tracker */
177 mInFlightStatusId = mStatusTracker->addComponent();
178
Zhijun He125684a2015-12-26 15:07:30 -0800179 /** Create buffer manager */
180 mBufferManager = new Camera3BufferManager();
181
Emilian Peev71c73a22017-03-21 16:35:51 +0000182 mTagMonitor.initialize(mVendorTagId);
183
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700184 /** Start up request queue thread */
Emilian Peev7e25e5e2017-04-07 15:48:49 +0100185 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800186 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800187 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700188 SET_ERR_L("Unable to start request queue thread: %s (%d)",
189 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800190 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800191 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800192 return res;
193 }
194
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700195 mPreparerThread = new PreparerThread();
196
Ruben Brunk183f0562015-08-12 12:55:02 -0700197 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800198 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700199 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700200 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700201 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800202
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800203 // Measure the clock domain offset between camera and video/hw_composer
204 camera_metadata_entry timestampSource =
205 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
206 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
207 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
208 mTimestampOffset = getMonoToBoottimeOffset();
209 }
210
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700211 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100212 camera_metadata_entry partialResultsCount =
213 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
214 if (partialResultsCount.count > 0) {
215 mNumPartialResults = partialResultsCount.data.i32[0];
216 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700217 }
218
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700219 camera_metadata_entry configs =
220 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
221 for (uint32_t i = 0; i < configs.count; i += 4) {
222 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
223 configs.data.i32[i + 3] ==
224 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
225 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
226 configs.data.i32[i + 2]));
227 }
228 }
229
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800230 return OK;
231}
232
233status_t Camera3Device::disconnect() {
234 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700235 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800236
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700237 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800238
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700239 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800240
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700241 {
242 Mutex::Autolock l(mLock);
243 if (mStatus == STATUS_UNINITIALIZED) return res;
244
245 if (mStatus == STATUS_ACTIVE ||
246 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
247 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700248 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700249 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 } else {
252 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
253 if (res != OK) {
254 SET_ERR_L("Timeout waiting for HAL to drain");
255 // Continue to close device even in case of error
256 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700257 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800258 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800259
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 if (mStatus == STATUS_ERROR) {
261 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700262 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263
264 if (mStatusTracker != NULL) {
265 mStatusTracker->requestExit();
266 }
267
268 if (mRequestThread != NULL) {
269 mRequestThread->requestExit();
270 }
271
272 mOutputStreams.clear();
273 mInputStream.clear();
274 }
275
276 // Joining done without holding mLock, otherwise deadlocks may ensue
277 // as the threads try to access parent state
278 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
279 // HAL may be in a bad state, so waiting for request thread
280 // (which may be stuck in the HAL processCaptureRequest call)
281 // could be dangerous.
282 mRequestThread->join();
283 }
284
285 if (mStatusTracker != NULL) {
286 mStatusTracker->join();
287 }
288
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800289 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 {
291 Mutex::Autolock l(mLock);
292
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800293 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800295 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800296
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800297 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700298 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800299
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700300 // Call close without internal mutex held, as the HAL close may need to
301 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800302 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700303
304 {
305 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800306 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700307 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800309
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700310 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700311 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800312}
313
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314// For dumping/debugging only -
315// try to acquire a lock a few times, eventually give up to proceed with
316// debug/dump operations
317bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
318 bool gotLock = false;
319 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
320 if (lock.tryLock() == NO_ERROR) {
321 gotLock = true;
322 break;
323 } else {
324 usleep(kDumpSleepDuration);
325 }
326 }
327 return gotLock;
328}
329
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700330Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
331 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100332 const int STREAM_CONFIGURATION_SIZE = 4;
333 const int STREAM_FORMAT_OFFSET = 0;
334 const int STREAM_WIDTH_OFFSET = 1;
335 const int STREAM_HEIGHT_OFFSET = 2;
336 const int STREAM_IS_INPUT_OFFSET = 3;
337 camera_metadata_ro_entry_t availableStreamConfigs =
338 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
339 if (availableStreamConfigs.count == 0 ||
340 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
341 return Size(0, 0);
342 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700343
Emilian Peev08dd2452017-04-06 16:55:14 +0100344 // Get max jpeg size (area-wise).
345 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
346 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
347 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
348 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
349 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
350 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
351 && format == HAL_PIXEL_FORMAT_BLOB &&
352 (width * height > maxJpegWidth * maxJpegHeight)) {
353 maxJpegWidth = width;
354 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700355 }
356 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100357
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700358 return Size(maxJpegWidth, maxJpegHeight);
359}
360
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800361nsecs_t Camera3Device::getMonoToBoottimeOffset() {
362 // try three times to get the clock offset, choose the one
363 // with the minimum gap in measurements.
364 const int tries = 3;
365 nsecs_t bestGap, measured;
366 for (int i = 0; i < tries; ++i) {
367 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
369 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t gap = tmono2 - tmono;
371 if (i == 0 || gap < bestGap) {
372 bestGap = gap;
373 measured = tbase - ((tmono + tmono2) >> 1);
374 }
375 }
376 return measured;
377}
378
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800379hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
380 int frameworkFormat) {
381 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
382}
383
384DataspaceFlags Camera3Device::mapToHidlDataspace(
385 android_dataspace dataSpace) {
386 return dataSpace;
387}
388
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700389BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700390 uint32_t usage) {
391 return usage;
392}
393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800394StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
395 switch (rotation) {
396 case CAMERA3_STREAM_ROTATION_0:
397 return StreamRotation::ROTATION_0;
398 case CAMERA3_STREAM_ROTATION_90:
399 return StreamRotation::ROTATION_90;
400 case CAMERA3_STREAM_ROTATION_180:
401 return StreamRotation::ROTATION_180;
402 case CAMERA3_STREAM_ROTATION_270:
403 return StreamRotation::ROTATION_270;
404 }
405 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
406 return StreamRotation::ROTATION_0;
407}
408
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800409status_t Camera3Device::mapToStreamConfigurationMode(
410 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
411 if (mode == nullptr) return BAD_VALUE;
412 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
413 switch(operationMode) {
414 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
415 *mode = StreamConfigurationMode::NORMAL_MODE;
416 break;
417 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
418 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
419 break;
420 default:
421 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
422 return BAD_VALUE;
423 }
424 } else {
425 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800426 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800427 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800428}
429
430camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
431 switch (status) {
432 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
433 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
434 }
435 return CAMERA3_BUFFER_STATUS_ERROR;
436}
437
438int Camera3Device::mapToFrameworkFormat(
439 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
440 return static_cast<uint32_t>(pixelFormat);
441}
442
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700443uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700444 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700445 return usage;
446}
447
448uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700449 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700450 return usage;
451}
452
Zhijun Hef7da0962014-04-24 13:27:56 -0700453ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700454 // Get max jpeg size (area-wise).
455 Size maxJpegResolution = getMaxJpegResolution();
456 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800457 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
458 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700459 return BAD_VALUE;
460 }
461
Zhijun Hef7da0962014-04-24 13:27:56 -0700462 // Get max jpeg buffer size
463 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700464 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
465 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800466 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
467 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700468 return BAD_VALUE;
469 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700470 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800471 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700472
473 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700474 float scaleFactor = ((float) (width * height)) /
475 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800476 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
477 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700478 if (jpegBufferSize > maxJpegBufferSize) {
479 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700480 }
481
482 return jpegBufferSize;
483}
484
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700485ssize_t Camera3Device::getPointCloudBufferSize() const {
486 const int FLOATS_PER_POINT=4;
487 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
488 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800489 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
490 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700491 return BAD_VALUE;
492 }
493 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
494 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
495 return maxBytesForPointCloud;
496}
497
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800498ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800499 const int PER_CONFIGURATION_SIZE = 3;
500 const int WIDTH_OFFSET = 0;
501 const int HEIGHT_OFFSET = 1;
502 const int SIZE_OFFSET = 2;
503 camera_metadata_ro_entry rawOpaqueSizes =
504 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800505 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800506 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800507 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
508 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800509 return BAD_VALUE;
510 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700511
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800512 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
513 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
514 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
515 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
516 }
517 }
518
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800519 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
520 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800521 return BAD_VALUE;
522}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700523
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800524status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
525 ATRACE_CALL();
526 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700527
528 // Try to lock, but continue in case of failure (to avoid blocking in
529 // deadlocks)
530 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
531 bool gotLock = tryLockSpinRightRound(mLock);
532
533 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
535 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700536 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800537 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
538 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700539
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800540 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700541
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800542 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700543 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800544 int n = args.size();
545 for (int i = 0; i < n; i++) {
546 if (args[i] == templatesOption) {
547 dumpTemplates = true;
548 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700549 if (args[i] == monitorOption) {
550 if (i + 1 < n) {
551 String8 monitorTags = String8(args[i + 1]);
552 if (monitorTags == "off") {
553 mTagMonitor.disableMonitoring();
554 } else {
555 mTagMonitor.parseTagsToMonitor(monitorTags);
556 }
557 } else {
558 mTagMonitor.disableMonitoring();
559 }
560 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800561 }
562
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800563 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800564
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800565 const char *status =
566 mStatus == STATUS_ERROR ? "ERROR" :
567 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700568 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
569 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800570 mStatus == STATUS_ACTIVE ? "ACTIVE" :
571 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700572
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800573 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700574 if (mStatus == STATUS_ERROR) {
575 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
576 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800577 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800578 const char *mode =
579 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
580 mOperatingMode == static_cast<int>(
581 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
582 "CUSTOM";
583 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800584
585 if (mInputStream != NULL) {
586 write(fd, lines.string(), lines.size());
587 mInputStream->dump(fd, args);
588 } else {
589 lines.appendFormat(" No input stream.\n");
590 write(fd, lines.string(), lines.size());
591 }
592 for (size_t i = 0; i < mOutputStreams.size(); i++) {
593 mOutputStreams[i]->dump(fd,args);
594 }
595
Zhijun He431503c2016-03-07 17:30:16 -0800596 if (mBufferManager != NULL) {
597 lines = String8(" Camera3 Buffer Manager:\n");
598 write(fd, lines.string(), lines.size());
599 mBufferManager->dump(fd, args);
600 }
Zhijun He125684a2015-12-26 15:07:30 -0800601
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700602 lines = String8(" In-flight requests:\n");
603 if (mInFlightMap.size() == 0) {
604 lines.append(" None\n");
605 } else {
606 for (size_t i = 0; i < mInFlightMap.size(); i++) {
607 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700608 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700609 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800610 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700611 r.numBuffersLeft);
612 }
613 }
614 write(fd, lines.string(), lines.size());
615
Shuzhen Wang686f6442017-06-20 16:16:04 -0700616 if (mRequestThread != NULL) {
617 mRequestThread->dumpCaptureRequestLatency(fd,
618 " ProcessCaptureRequest latency histogram:");
619 }
620
Igor Murashkin1e479c02013-09-06 16:55:14 -0700621 {
622 lines = String8(" Last request sent:\n");
623 write(fd, lines.string(), lines.size());
624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700625 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700626 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
627 }
628
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800629 if (dumpTemplates) {
630 const char *templateNames[] = {
631 "TEMPLATE_PREVIEW",
632 "TEMPLATE_STILL_CAPTURE",
633 "TEMPLATE_VIDEO_RECORD",
634 "TEMPLATE_VIDEO_SNAPSHOT",
635 "TEMPLATE_ZERO_SHUTTER_LAG",
636 "TEMPLATE_MANUAL"
637 };
638
639 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 camera_metadata_t *templateRequest = nullptr;
641 mInterface->constructDefaultRequestSettings(
642 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800643 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800644 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800645 lines.append(" Not supported\n");
646 write(fd, lines.string(), lines.size());
647 } else {
648 write(fd, lines.string(), lines.size());
649 dump_indented_camera_metadata(templateRequest,
650 fd, /*verbosity*/2, /*indentation*/8);
651 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800652 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800653 }
654 }
655
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700656 mTagMonitor.dumpMonitoredMetadata(fd);
657
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800659 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800660 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800661 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800662 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800663
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700664 if (gotLock) mLock.unlock();
665 if (gotInterfaceLock) mInterfaceLock.unlock();
666
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667 return OK;
668}
669
670const CameraMetadata& Camera3Device::info() const {
671 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
673 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700674 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 mStatus == STATUS_ERROR ?
676 "when in error state" : "before init");
677 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800678 return mDeviceInfo;
679}
680
Jianing Wei90e59c92014-03-12 18:29:36 -0700681status_t Camera3Device::checkStatusOkToCaptureLocked() {
682 switch (mStatus) {
683 case STATUS_ERROR:
684 CLOGE("Device has encountered a serious error");
685 return INVALID_OPERATION;
686 case STATUS_UNINITIALIZED:
687 CLOGE("Device not initialized");
688 return INVALID_OPERATION;
689 case STATUS_UNCONFIGURED:
690 case STATUS_CONFIGURED:
691 case STATUS_ACTIVE:
692 // OK
693 break;
694 default:
695 SET_ERR_L("Unexpected status: %d", mStatus);
696 return INVALID_OPERATION;
697 }
698 return OK;
699}
700
701status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700702 const List<const CameraMetadata> &metadataList,
703 const std::list<const SurfaceMap> &surfaceMaps,
704 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700705 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700706 if (requestList == NULL) {
707 CLOGE("requestList cannot be NULL.");
708 return BAD_VALUE;
709 }
710
Jianing Weicb0652e2014-03-12 18:29:36 -0700711 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700712 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
713 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
714 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
715 ++metadataIt, ++surfaceMapIt) {
716 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700717 if (newRequest == 0) {
718 CLOGE("Can't create capture request");
719 return BAD_VALUE;
720 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700721
Shuzhen Wang9d066012016-09-30 11:30:20 -0700722 newRequest->mRepeating = repeating;
723
Jianing Weicb0652e2014-03-12 18:29:36 -0700724 // Setup burst Id and request Id
725 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700726 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
727 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700728 CLOGE("RequestID entry exists; but must not be empty in metadata");
729 return BAD_VALUE;
730 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700731 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700732 } else {
733 CLOGE("RequestID does not exist in metadata");
734 return BAD_VALUE;
735 }
736
Jianing Wei90e59c92014-03-12 18:29:36 -0700737 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700738
739 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700740 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700741 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
742 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
743 return BAD_VALUE;
744 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700745
746 // Setup batch size if this is a high speed video recording request.
747 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
748 auto firstRequest = requestList->begin();
749 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
750 if (outputStream->isVideoStream()) {
751 (*firstRequest)->mBatchSize = requestList->size();
752 break;
753 }
754 }
755 }
756
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 return OK;
758}
759
Jianing Weicb0652e2014-03-12 18:29:36 -0700760status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800762
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700763 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700764 std::list<const SurfaceMap> surfaceMaps;
765 convertToRequestList(requests, surfaceMaps, request);
766
767 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
768}
769
770void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
771 std::list<const SurfaceMap>& surfaceMaps,
772 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700773 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774
775 SurfaceMap surfaceMap;
776 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
777 // With no surface list passed in, stream and surface will have 1-to-1
778 // mapping. So the surface index is 0 for each stream in the surfaceMap.
779 for (size_t i = 0; i < streams.count; i++) {
780 surfaceMap[streams.data.i32[i]].push_back(0);
781 }
782 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783}
784
Jianing Wei90e59c92014-03-12 18:29:36 -0700785status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700786 const List<const CameraMetadata> &requests,
787 const std::list<const SurfaceMap> &surfaceMaps,
788 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700789 /*out*/
790 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700791 ATRACE_CALL();
792 Mutex::Autolock il(mInterfaceLock);
793 Mutex::Autolock l(mLock);
794
795 status_t res = checkStatusOkToCaptureLocked();
796 if (res != OK) {
797 // error logged by previous call
798 return res;
799 }
800
801 RequestList requestList;
802
Shuzhen Wang0129d522016-10-30 22:43:41 -0700803 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
804 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700805 if (res != OK) {
806 // error logged by previous call
807 return res;
808 }
809
810 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700811 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700812 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700813 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700814 }
815
816 if (res == OK) {
817 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
818 if (res != OK) {
819 SET_ERR_L("Can't transition to active in %f seconds!",
820 kActiveTimeout/1e9);
821 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700823 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 } else {
825 CLOGE("Cannot queue request. Impossible.");
826 return BAD_VALUE;
827 }
828
829 return res;
830}
831
Yifan Honga640c5a2017-04-12 16:30:31 -0700832// Only one processCaptureResult should be called at a time, so
833// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800834hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800835 const hardware::hidl_vec<
836 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700837
838 if (mProcessCaptureResultLock.tryLock() != OK) {
839 // This should never happen; it indicates a wrong client implementation
840 // that doesn't follow the contract. But, we can be tolerant here.
841 ALOGE("%s: callback overlapped! waiting 1s...",
842 __FUNCTION__);
843 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
844 ALOGE("%s: cannot acquire lock in 1s, dropping results",
845 __FUNCTION__);
846 // really don't know what to do, so bail out.
847 return hardware::Void();
848 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800849 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700850 for (const auto& result : results) {
851 processOneCaptureResultLocked(result);
852 }
853 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800854 return hardware::Void();
855}
856
Yifan Honga640c5a2017-04-12 16:30:31 -0700857void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800858 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800859 camera3_capture_result r;
860 status_t res;
861 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700862
863 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
864 if (result.fmqResultSize > 0) {
865 resultMetadata.resize(result.fmqResultSize);
866 if (mResultMetadataQueue == nullptr) {
867 return; // logged in initialize()
868 }
869 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
870 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
871 __FUNCTION__, result.frameNumber, result.fmqResultSize);
872 return;
873 }
874 } else {
875 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
876 result.result.size());
877 }
878
879 if (resultMetadata.size() != 0) {
880 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
881 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800882 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
883 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
884 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800885 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800886 }
887 } else {
888 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800889 }
890
891 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
892 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
893 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
894 auto& bDst = outputBuffers[i];
895 const StreamBuffer &bSrc = result.outputBuffers[i];
896
897 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100898 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800899 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
900 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800901 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800902 }
903 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
904
905 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800906 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800907 if (res != OK) {
908 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
909 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800910 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800911 }
912 bDst.buffer = buffer;
913 bDst.status = mapHidlBufferStatus(bSrc.status);
914 bDst.acquire_fence = -1;
915 if (bSrc.releaseFence == nullptr) {
916 bDst.release_fence = -1;
917 } else if (bSrc.releaseFence->numFds == 1) {
918 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
919 } else {
920 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
921 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800922 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800923 }
924 }
925 r.num_output_buffers = outputBuffers.size();
926 r.output_buffers = outputBuffers.data();
927
928 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800929 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800930 r.input_buffer = nullptr;
931 } else {
932 if (mInputStream->getId() != result.inputBuffer.streamId) {
933 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
934 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800935 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 }
937 inputBuffer.stream = mInputStream->asHalStream();
938 buffer_handle_t *buffer;
939 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
940 &buffer);
941 if (res != OK) {
942 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
943 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800944 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800945 }
946 inputBuffer.buffer = buffer;
947 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
948 inputBuffer.acquire_fence = -1;
949 if (result.inputBuffer.releaseFence == nullptr) {
950 inputBuffer.release_fence = -1;
951 } else if (result.inputBuffer.releaseFence->numFds == 1) {
952 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
953 } else {
954 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
955 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800956 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800957 }
958 r.input_buffer = &inputBuffer;
959 }
960
961 r.partial_result = result.partialResult;
962
963 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800964}
965
966hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800967 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
968 for (const auto& msg : msgs) {
969 notify(msg);
970 }
971 return hardware::Void();
972}
973
974void Camera3Device::notify(
975 const hardware::camera::device::V3_2::NotifyMsg& msg) {
976
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800977 camera3_notify_msg m;
978 switch (msg.type) {
979 case MsgType::ERROR:
980 m.type = CAMERA3_MSG_ERROR;
981 m.message.error.frame_number = msg.msg.error.frameNumber;
982 if (msg.msg.error.errorStreamId >= 0) {
983 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100984 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800985 ALOGE("%s: Frame %d: Invalid error stream id %d",
986 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800987 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800988 }
989 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
990 } else {
991 m.message.error.error_stream = nullptr;
992 }
993 switch (msg.msg.error.errorCode) {
994 case ErrorCode::ERROR_DEVICE:
995 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
996 break;
997 case ErrorCode::ERROR_REQUEST:
998 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
999 break;
1000 case ErrorCode::ERROR_RESULT:
1001 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1002 break;
1003 case ErrorCode::ERROR_BUFFER:
1004 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1005 break;
1006 }
1007 break;
1008 case MsgType::SHUTTER:
1009 m.type = CAMERA3_MSG_SHUTTER;
1010 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1011 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1012 break;
1013 }
1014 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001015}
1016
Jianing Weicb0652e2014-03-12 18:29:36 -07001017status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001018 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001019 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001020 ATRACE_CALL();
1021
Shuzhen Wang0129d522016-10-30 22:43:41 -07001022 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001023}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001024
Jianing Weicb0652e2014-03-12 18:29:36 -07001025status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1026 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001027 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001028
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001029 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001030 std::list<const SurfaceMap> surfaceMaps;
1031 convertToRequestList(requests, surfaceMaps, request);
1032
1033 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1034 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001035}
1036
Jianing Weicb0652e2014-03-12 18:29:36 -07001037status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001038 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001039 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001040 ATRACE_CALL();
1041
Shuzhen Wang0129d522016-10-30 22:43:41 -07001042 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001043}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001044
1045sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001046 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 status_t res;
1048
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001049 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001050 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1051 // so unilaterally select normal operating mode.
1052 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001053 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001054 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001055 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001056 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001057 } else if (mStatus == STATUS_UNCONFIGURED) {
1058 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 CLOGE("No streams configured");
1060 return NULL;
1061 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 }
1063
Shuzhen Wang0129d522016-10-30 22:43:41 -07001064 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001065 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001066}
1067
Jianing Weicb0652e2014-03-12 18:29:36 -07001068status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001069 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001070 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001072
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073 switch (mStatus) {
1074 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001075 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001076 return INVALID_OPERATION;
1077 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001078 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001080 case STATUS_UNCONFIGURED:
1081 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001082 case STATUS_ACTIVE:
1083 // OK
1084 break;
1085 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001086 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001087 return INVALID_OPERATION;
1088 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001089 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001090
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001091 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001092}
1093
1094status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1095 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001096 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001097
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001098 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001099}
1100
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001101status_t Camera3Device::createInputStream(
1102 uint32_t width, uint32_t height, int format, int *id) {
1103 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001104 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001105 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001106 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1107 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001108
1109 status_t res;
1110 bool wasActive = false;
1111
1112 switch (mStatus) {
1113 case STATUS_ERROR:
1114 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1115 return INVALID_OPERATION;
1116 case STATUS_UNINITIALIZED:
1117 ALOGE("%s: Device not initialized", __FUNCTION__);
1118 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001119 case STATUS_UNCONFIGURED:
1120 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001121 // OK
1122 break;
1123 case STATUS_ACTIVE:
1124 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001125 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001126 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001127 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001128 return res;
1129 }
1130 wasActive = true;
1131 break;
1132 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001133 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001134 return INVALID_OPERATION;
1135 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001136 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001137
1138 if (mInputStream != 0) {
1139 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1140 return INVALID_OPERATION;
1141 }
1142
1143 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1144 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001145 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001146
1147 mInputStream = newStream;
1148
1149 *id = mNextStreamId++;
1150
1151 // Continue captures if active at start
1152 if (wasActive) {
1153 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001154 // Reuse current operating mode for new stream config
1155 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001156 if (res != OK) {
1157 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1158 __FUNCTION__, mNextStreamId, strerror(-res), res);
1159 return res;
1160 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001161 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162 }
1163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001164 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001165 return OK;
1166}
1167
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001168status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001169 uint32_t width, uint32_t height, int format,
1170 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001171 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172 ATRACE_CALL();
1173
1174 if (consumer == nullptr) {
1175 ALOGE("%s: consumer must not be null", __FUNCTION__);
1176 return BAD_VALUE;
1177 }
1178
1179 std::vector<sp<Surface>> consumers;
1180 consumers.push_back(consumer);
1181
1182 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001183 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001184}
1185
1186status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1187 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1188 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001189 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001190 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001193 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001194 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1195 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001196
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 status_t res;
1198 bool wasActive = false;
1199
1200 switch (mStatus) {
1201 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001202 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return INVALID_OPERATION;
1204 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001205 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001207 case STATUS_UNCONFIGURED:
1208 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 // OK
1210 break;
1211 case STATUS_ACTIVE:
1212 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return res;
1217 }
1218 wasActive = true;
1219 break;
1220 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001221 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return INVALID_OPERATION;
1223 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225
1226 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001227
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 if (consumers.size() == 0 && !hasDeferredConsumer) {
1229 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1230 return BAD_VALUE;
1231 }
Zhijun He5d677d12016-05-29 16:52:39 -07001232
Shuzhen Wang0129d522016-10-30 22:43:41 -07001233 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001234 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1235 return BAD_VALUE;
1236 }
1237
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001239 ssize_t blobBufferSize;
1240 if (dataSpace != HAL_DATASPACE_DEPTH) {
1241 blobBufferSize = getJpegBufferSize(width, height);
1242 if (blobBufferSize <= 0) {
1243 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1244 return BAD_VALUE;
1245 }
1246 } else {
1247 blobBufferSize = getPointCloudBufferSize();
1248 if (blobBufferSize <= 0) {
1249 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1250 return BAD_VALUE;
1251 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001252 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001253 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001254 width, height, blobBufferSize, format, dataSpace, rotation,
1255 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001256 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1257 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1258 if (rawOpaqueBufferSize <= 0) {
1259 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1260 return BAD_VALUE;
1261 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001262 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001263 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1264 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001265 } else if (isShared) {
1266 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1267 width, height, format, consumerUsage, dataSpace, rotation,
1268 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001269 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001270 newStream = new Camera3OutputStream(mNextStreamId,
1271 width, height, format, consumerUsage, dataSpace, rotation,
1272 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001274 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001275 width, height, format, dataSpace, rotation,
1276 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279
Emilian Peev08dd2452017-04-06 16:55:14 +01001280 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001281
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 res = mOutputStreams.add(mNextStreamId, newStream);
1283 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001284 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 return res;
1286 }
1287
1288 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001289 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290
1291 // Continue captures if active at start
1292 if (wasActive) {
1293 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001294 // Reuse current operating mode for new stream config
1295 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1298 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 return res;
1300 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001303 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001305}
1306
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001307status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001308 uint32_t *width, uint32_t *height,
1309 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001310 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001311 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001313
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001314 switch (mStatus) {
1315 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001316 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 return INVALID_OPERATION;
1318 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001319 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001320 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001321 case STATUS_UNCONFIGURED:
1322 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001323 case STATUS_ACTIVE:
1324 // OK
1325 break;
1326 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001327 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001328 return INVALID_OPERATION;
1329 }
1330
1331 ssize_t idx = mOutputStreams.indexOfKey(id);
1332 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001333 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001334 return idx;
1335 }
1336
1337 if (width) *width = mOutputStreams[idx]->getWidth();
1338 if (height) *height = mOutputStreams[idx]->getHeight();
1339 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001340 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001342}
1343
1344status_t Camera3Device::setStreamTransform(int id,
1345 int transform) {
1346 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 does not exist",
1370 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371 return BAD_VALUE;
1372 }
1373
1374 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001375}
1376
1377status_t Camera3Device::deleteStream(int id) {
1378 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001379 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 Mutex::Autolock l(mLock);
1381 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001382
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001383 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001384
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 // CameraDevice semantics require device to already be idle before
1386 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001387 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001389 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 }
1391
Igor Murashkin2fba5842013-04-22 14:03:54 -07001392 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001393 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 if (mInputStream != NULL && id == mInputStream->getId()) {
1395 deletedStream = mInputStream;
1396 mInputStream.clear();
1397 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001398 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return BAD_VALUE;
1401 }
Zhijun He5f446352014-01-22 09:49:33 -08001402 }
1403
1404 // Delete output stream or the output part of a bi-directional stream.
1405 if (outputStreamIdx != NAME_NOT_FOUND) {
1406 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407 mOutputStreams.removeItem(id);
1408 }
1409
1410 // Free up the stream endpoint so that it can be used by some other stream
1411 res = deletedStream->disconnect();
1412 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001413 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 // fall through since we want to still list the stream as deleted.
1415 }
1416 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001417 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001418
1419 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001420}
1421
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001422status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001423 ATRACE_CALL();
1424 ALOGV("%s: E", __FUNCTION__);
1425
1426 Mutex::Autolock il(mInterfaceLock);
1427 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001428
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001429 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001430}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001431
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001432status_t Camera3Device::getInputBufferProducer(
1433 sp<IGraphicBufferProducer> *producer) {
1434 Mutex::Autolock il(mInterfaceLock);
1435 Mutex::Autolock l(mLock);
1436
1437 if (producer == NULL) {
1438 return BAD_VALUE;
1439 } else if (mInputStream == NULL) {
1440 return INVALID_OPERATION;
1441 }
1442
1443 return mInputStream->getInputBufferProducer(producer);
1444}
1445
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001446status_t Camera3Device::createDefaultRequest(int templateId,
1447 CameraMetadata *request) {
1448 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001449 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001450
1451 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1452 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1453 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1454 return BAD_VALUE;
1455 }
1456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 Mutex::Autolock l(mLock);
1459
1460 switch (mStatus) {
1461 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001462 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 return INVALID_OPERATION;
1464 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001465 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001467 case STATUS_UNCONFIGURED:
1468 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 case STATUS_ACTIVE:
1470 // OK
1471 break;
1472 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001473 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return INVALID_OPERATION;
1475 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001476
Zhijun Hea1530f12014-09-14 12:44:20 -07001477 if (!mRequestTemplateCache[templateId].isEmpty()) {
1478 *request = mRequestTemplateCache[templateId];
1479 return OK;
1480 }
1481
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001482 camera_metadata_t *rawRequest;
1483 status_t res = mInterface->constructDefaultRequestSettings(
1484 (camera3_request_template_t) templateId, &rawRequest);
1485 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001486 ALOGI("%s: template %d is not supported on this camera device",
1487 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001488 return res;
1489 } else if (res != OK) {
1490 CLOGE("Unable to construct request template %d: %s (%d)",
1491 templateId, strerror(-res), res);
1492 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001493 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001494
Emilian Peev71c73a22017-03-21 16:35:51 +00001495 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001496 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001497
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001498 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499 return OK;
1500}
1501
1502status_t Camera3Device::waitUntilDrained() {
1503 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001506
Zhijun He69a37482014-03-23 18:44:49 -07001507 return waitUntilDrainedLocked();
1508}
1509
1510status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 switch (mStatus) {
1512 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 ALOGV("%s: Already idle", __FUNCTION__);
1515 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 case STATUS_CONFIGURED:
1517 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 case STATUS_ERROR:
1519 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001520 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 break;
1522 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return INVALID_OPERATION;
1525 }
1526
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001527 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001529 if (res != OK) {
1530 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1531 res);
1532 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 return res;
1534}
1535
Ruben Brunk183f0562015-08-12 12:55:02 -07001536
1537void Camera3Device::internalUpdateStatusLocked(Status status) {
1538 mStatus = status;
1539 mRecentStatusUpdates.add(mStatus);
1540 mStatusChanged.broadcast();
1541}
1542
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543// Pause to reconfigure
1544status_t Camera3Device::internalPauseAndWaitLocked() {
1545 mRequestThread->setPaused(true);
1546 mPauseStateNotify = true;
1547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001548 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1550 if (res != OK) {
1551 SET_ERR_L("Can't idle device in %f seconds!",
1552 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 }
1554
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 return res;
1556}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558// Resume after internalPauseAndWaitLocked
1559status_t Camera3Device::internalResumeLocked() {
1560 status_t res;
1561
1562 mRequestThread->setPaused(false);
1563
1564 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1565 if (res != OK) {
1566 SET_ERR_L("Can't transition to active in %f seconds!",
1567 kActiveTimeout/1e9);
1568 }
1569 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571}
1572
Ruben Brunk183f0562015-08-12 12:55:02 -07001573status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001575
1576 size_t startIndex = 0;
1577 if (mStatusWaiters == 0) {
1578 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1579 // this status list
1580 mRecentStatusUpdates.clear();
1581 } else {
1582 // If other threads are waiting on updates to this status list, set the position of the
1583 // first element that this list will check rather than clearing the list.
1584 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 }
1586
Ruben Brunk183f0562015-08-12 12:55:02 -07001587 mStatusWaiters++;
1588
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 bool stateSeen = false;
1590 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001591 if (active == (mStatus == STATUS_ACTIVE)) {
1592 // Desired state is current
1593 break;
1594 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001595
1596 res = mStatusChanged.waitRelative(mLock, timeout);
1597 if (res != OK) break;
1598
Ruben Brunk183f0562015-08-12 12:55:02 -07001599 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1600 // transitions.
1601 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1602 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1603 __FUNCTION__);
1604
1605 // Encountered desired state since we began waiting
1606 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001607 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1608 stateSeen = true;
1609 break;
1610 }
1611 }
1612 } while (!stateSeen);
1613
Ruben Brunk183f0562015-08-12 12:55:02 -07001614 mStatusWaiters--;
1615
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 return res;
1617}
1618
1619
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001620status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001621 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001622 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001623
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001624 if (listener != NULL && mListener != NULL) {
1625 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1626 }
1627 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001628 mRequestThread->setNotificationListener(listener);
1629 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001630
1631 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632}
1633
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001634bool Camera3Device::willNotify3A() {
1635 return false;
1636}
1637
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001638status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001639 status_t res;
1640 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001642 while (mResultQueue.empty()) {
1643 res = mResultSignal.waitRelative(mOutputLock, timeout);
1644 if (res == TIMED_OUT) {
1645 return res;
1646 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001647 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1648 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001649 return res;
1650 }
1651 }
1652 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653}
1654
Jianing Weicb0652e2014-03-12 18:29:36 -07001655status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001656 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001657 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001659 if (mResultQueue.empty()) {
1660 return NOT_ENOUGH_DATA;
1661 }
1662
Jianing Weicb0652e2014-03-12 18:29:36 -07001663 if (frame == NULL) {
1664 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1665 return BAD_VALUE;
1666 }
1667
1668 CaptureResult &result = *(mResultQueue.begin());
1669 frame->mResultExtras = result.mResultExtras;
1670 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001671 mResultQueue.erase(mResultQueue.begin());
1672
1673 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674}
1675
1676status_t Camera3Device::triggerAutofocus(uint32_t id) {
1677 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001678 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001679
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001680 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1681 // Mix-in this trigger into the next request and only the next request.
1682 RequestTrigger trigger[] = {
1683 {
1684 ANDROID_CONTROL_AF_TRIGGER,
1685 ANDROID_CONTROL_AF_TRIGGER_START
1686 },
1687 {
1688 ANDROID_CONTROL_AF_TRIGGER_ID,
1689 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001690 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001691 };
1692
1693 return mRequestThread->queueTrigger(trigger,
1694 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001695}
1696
1697status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1698 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001699 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001701 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1702 // Mix-in this trigger into the next request and only the next request.
1703 RequestTrigger trigger[] = {
1704 {
1705 ANDROID_CONTROL_AF_TRIGGER,
1706 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1707 },
1708 {
1709 ANDROID_CONTROL_AF_TRIGGER_ID,
1710 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001711 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001712 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001714 return mRequestThread->queueTrigger(trigger,
1715 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716}
1717
1718status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1719 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001720 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001721
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001722 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1723 // Mix-in this trigger into the next request and only the next request.
1724 RequestTrigger trigger[] = {
1725 {
1726 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1727 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1728 },
1729 {
1730 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1731 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001732 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001733 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001735 return mRequestThread->queueTrigger(trigger,
1736 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001737}
1738
Jianing Weicb0652e2014-03-12 18:29:36 -07001739status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001740 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001741 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001742 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001743
Zhijun He7ef20392014-04-21 16:04:17 -07001744 {
1745 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001746 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001747 }
1748
Emilian Peev08dd2452017-04-06 16:55:14 +01001749 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001750}
1751
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001753 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1754}
1755
1756status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001757 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001758 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001759 Mutex::Autolock il(mInterfaceLock);
1760 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001761
1762 sp<Camera3StreamInterface> stream;
1763 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1764 if (outputStreamIdx == NAME_NOT_FOUND) {
1765 CLOGE("Stream %d does not exist", streamId);
1766 return BAD_VALUE;
1767 }
1768
1769 stream = mOutputStreams.editValueAt(outputStreamIdx);
1770
1771 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001772 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001773 return BAD_VALUE;
1774 }
1775
1776 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001777 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001778 return BAD_VALUE;
1779 }
1780
Ruben Brunkc78ac262015-08-13 17:58:46 -07001781 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001782}
1783
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001784status_t Camera3Device::tearDown(int streamId) {
1785 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001786 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001787 Mutex::Autolock il(mInterfaceLock);
1788 Mutex::Autolock l(mLock);
1789
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001790 sp<Camera3StreamInterface> stream;
1791 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1792 if (outputStreamIdx == NAME_NOT_FOUND) {
1793 CLOGE("Stream %d does not exist", streamId);
1794 return BAD_VALUE;
1795 }
1796
1797 stream = mOutputStreams.editValueAt(outputStreamIdx);
1798
1799 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1800 CLOGE("Stream %d is a target of a in-progress request", streamId);
1801 return BAD_VALUE;
1802 }
1803
1804 return stream->tearDown();
1805}
1806
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001807status_t Camera3Device::addBufferListenerForStream(int streamId,
1808 wp<Camera3StreamBufferListener> listener) {
1809 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001810 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001811 Mutex::Autolock il(mInterfaceLock);
1812 Mutex::Autolock l(mLock);
1813
1814 sp<Camera3StreamInterface> stream;
1815 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1816 if (outputStreamIdx == NAME_NOT_FOUND) {
1817 CLOGE("Stream %d does not exist", streamId);
1818 return BAD_VALUE;
1819 }
1820
1821 stream = mOutputStreams.editValueAt(outputStreamIdx);
1822 stream->addBufferListener(listener);
1823
1824 return OK;
1825}
1826
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001827/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 * Methods called by subclasses
1829 */
1830
1831void Camera3Device::notifyStatus(bool idle) {
1832 {
1833 // Need mLock to safely update state and synchronize to current
1834 // state of methods in flight.
1835 Mutex::Autolock l(mLock);
1836 // We can get various system-idle notices from the status tracker
1837 // while starting up. Only care about them if we've actually sent
1838 // in some requests recently.
1839 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1840 return;
1841 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001842 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001844 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845
1846 // Skip notifying listener if we're doing some user-transparent
1847 // state changes
1848 if (mPauseStateNotify) return;
1849 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001850
1851 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852 {
1853 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001854 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 }
1856 if (idle && listener != NULL) {
1857 listener->notifyIdle();
1858 }
1859}
1860
Shuzhen Wang758c2152017-01-10 18:26:18 -08001861status_t Camera3Device::setConsumerSurfaces(int streamId,
1862 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001863 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001864 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1865 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001866 Mutex::Autolock il(mInterfaceLock);
1867 Mutex::Autolock l(mLock);
1868
Shuzhen Wang758c2152017-01-10 18:26:18 -08001869 if (consumers.size() == 0) {
1870 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001871 return BAD_VALUE;
1872 }
1873
1874 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1875 if (idx == NAME_NOT_FOUND) {
1876 CLOGE("Stream %d is unknown", streamId);
1877 return idx;
1878 }
1879 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001880 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001881 if (res != OK) {
1882 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1883 return res;
1884 }
1885
Shuzhen Wang0129d522016-10-30 22:43:41 -07001886 if (stream->isConsumerConfigurationDeferred()) {
1887 if (!stream->isConfiguring()) {
1888 CLOGE("Stream %d was already fully configured.", streamId);
1889 return INVALID_OPERATION;
1890 }
Zhijun He5d677d12016-05-29 16:52:39 -07001891
Shuzhen Wang0129d522016-10-30 22:43:41 -07001892 res = stream->finishConfiguration();
1893 if (res != OK) {
1894 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1895 stream->getId(), strerror(-res), res);
1896 return res;
1897 }
Zhijun He5d677d12016-05-29 16:52:39 -07001898 }
1899
1900 return OK;
1901}
1902
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 * Camera3Device private methods
1905 */
1906
1907sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001908 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001909 ATRACE_CALL();
1910 status_t res;
1911
1912 sp<CaptureRequest> newRequest = new CaptureRequest;
1913 newRequest->mSettings = request;
1914
1915 camera_metadata_entry_t inputStreams =
1916 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1917 if (inputStreams.count > 0) {
1918 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001919 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001920 CLOGE("Request references unknown input stream %d",
1921 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 return NULL;
1923 }
1924 // Lazy completion of stream configuration (allocation/registration)
1925 // on first use
1926 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001927 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001928 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001929 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001931 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001932 return NULL;
1933 }
1934 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001935 // Check if stream is being prepared
1936 if (mInputStream->isPreparing()) {
1937 CLOGE("Request references an input stream that's being prepared!");
1938 return NULL;
1939 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001940
1941 newRequest->mInputStream = mInputStream;
1942 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1943 }
1944
1945 camera_metadata_entry_t streams =
1946 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1947 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001948 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001949 return NULL;
1950 }
1951
1952 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001953 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001954 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001955 CLOGE("Request references unknown stream %d",
1956 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001957 return NULL;
1958 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001959 sp<Camera3OutputStreamInterface> stream =
1960 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001961
Zhijun He5d677d12016-05-29 16:52:39 -07001962 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07001963 auto iter = surfaceMap.find(streams.data.i32[i]);
1964 if (iter != surfaceMap.end()) {
1965 const std::vector<size_t>& surfaces = iter->second;
1966 for (const auto& surface : surfaces) {
1967 if (stream->isConsumerConfigurationDeferred(surface)) {
1968 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
1969 "due to deferred consumer", stream->getId(), surface);
1970 return NULL;
1971 }
1972 }
1973 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07001974 }
1975
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976 // Lazy completion of stream configuration (allocation/registration)
1977 // on first use
1978 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001979 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001981 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
1982 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001983 return NULL;
1984 }
1985 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001986 // Check if stream is being prepared
1987 if (stream->isPreparing()) {
1988 CLOGE("Request references an output stream that's being prepared!");
1989 return NULL;
1990 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001991
1992 newRequest->mOutputStreams.push(stream);
1993 }
1994 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001995 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001996
1997 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001998}
1999
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002000bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2001 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2002 Size size = mSupportedOpaqueInputSizes[i];
2003 if (size.width == width && size.height == height) {
2004 return true;
2005 }
2006 }
2007
2008 return false;
2009}
2010
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002011void Camera3Device::cancelStreamsConfigurationLocked() {
2012 int res = OK;
2013 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2014 res = mInputStream->cancelConfiguration();
2015 if (res != OK) {
2016 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2017 mInputStream->getId(), strerror(-res), res);
2018 }
2019 }
2020
2021 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2022 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2023 if (outputStream->isConfiguring()) {
2024 res = outputStream->cancelConfiguration();
2025 if (res != OK) {
2026 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2027 outputStream->getId(), strerror(-res), res);
2028 }
2029 }
2030 }
2031
2032 // Return state to that at start of call, so that future configures
2033 // properly clean things up
2034 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2035 mNeedConfig = true;
2036}
2037
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002038status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002039 ATRACE_CALL();
2040 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002041
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002042 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002043 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002044 return INVALID_OPERATION;
2045 }
2046
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002047 if (operatingMode < 0) {
2048 CLOGE("Invalid operating mode: %d", operatingMode);
2049 return BAD_VALUE;
2050 }
2051
2052 bool isConstrainedHighSpeed =
2053 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2054 operatingMode;
2055
2056 if (mOperatingMode != operatingMode) {
2057 mNeedConfig = true;
2058 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2059 mOperatingMode = operatingMode;
2060 }
2061
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002062 if (!mNeedConfig) {
2063 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2064 return OK;
2065 }
2066
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002067 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2068 // adding a dummy stream instead.
2069 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2070 if (mOutputStreams.size() == 0) {
2071 addDummyStreamLocked();
2072 } else {
2073 tryRemoveDummyStreamLocked();
2074 }
2075
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002077 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078
2079 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002080 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002081 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2082
2083 Vector<camera3_stream_t*> streams;
2084 streams.setCapacity(config.num_streams);
2085
2086 if (mInputStream != NULL) {
2087 camera3_stream_t *inputStream;
2088 inputStream = mInputStream->startConfiguration();
2089 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002090 CLOGE("Can't start input stream configuration");
2091 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092 return INVALID_OPERATION;
2093 }
2094 streams.add(inputStream);
2095 }
2096
2097 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002098
2099 // Don't configure bidi streams twice, nor add them twice to the list
2100 if (mOutputStreams[i].get() ==
2101 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2102
2103 config.num_streams--;
2104 continue;
2105 }
2106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 camera3_stream_t *outputStream;
2108 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2109 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002110 CLOGE("Can't start output stream configuration");
2111 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 return INVALID_OPERATION;
2113 }
2114 streams.add(outputStream);
2115 }
2116
2117 config.streams = streams.editArray();
2118
2119 // Do the HAL configuration; will potentially touch stream
2120 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002121
2122 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002124 if (res == BAD_VALUE) {
2125 // HAL rejected this set of streams as unsupported, clean up config
2126 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002127 CLOGE("Set of requested inputs/outputs not supported by HAL");
2128 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002129 return BAD_VALUE;
2130 } else if (res != OK) {
2131 // Some other kind of error from configure_streams - this is not
2132 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002133 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2134 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 return res;
2136 }
2137
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002138 // Finish all stream configuration immediately.
2139 // TODO: Try to relax this later back to lazy completion, which should be
2140 // faster
2141
Igor Murashkin073f8572013-05-02 14:59:28 -07002142 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002143 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002144 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002145 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002146 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002147 cancelStreamsConfigurationLocked();
2148 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002149 }
2150 }
2151
2152 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002153 sp<Camera3OutputStreamInterface> outputStream =
2154 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002155 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002156 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002157 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002158 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002159 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002160 cancelStreamsConfigurationLocked();
2161 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002162 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002163 }
2164 }
2165
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166 // Request thread needs to know to avoid using repeat-last-settings protocol
2167 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002168 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169
Zhijun He90f7c372016-08-16 16:19:43 -07002170 char value[PROPERTY_VALUE_MAX];
2171 property_get("camera.fifo.disable", value, "0");
2172 int32_t disableFifo = atoi(value);
2173 if (disableFifo != 1) {
2174 // Boost priority of request thread to SCHED_FIFO.
2175 pid_t requestThreadTid = mRequestThread->getTid();
2176 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002177 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002178 if (res != OK) {
2179 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2180 strerror(-res), res);
2181 } else {
2182 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2183 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002184 }
2185
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002186 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002187
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002188 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002189
Ruben Brunk183f0562015-08-12 12:55:02 -07002190 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2191 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002192
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002193 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002194
Zhijun He0a210512014-07-24 13:45:15 -07002195 // tear down the deleted streams after configure streams.
2196 mDeletedStreams.clear();
2197
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002199}
2200
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002201status_t Camera3Device::addDummyStreamLocked() {
2202 ATRACE_CALL();
2203 status_t res;
2204
2205 if (mDummyStreamId != NO_STREAM) {
2206 // Should never be adding a second dummy stream when one is already
2207 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002208 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2209 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002210 return INVALID_OPERATION;
2211 }
2212
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002213 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002214
2215 sp<Camera3OutputStreamInterface> dummyStream =
2216 new Camera3DummyStream(mNextStreamId);
2217
2218 res = mOutputStreams.add(mNextStreamId, dummyStream);
2219 if (res < 0) {
2220 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2221 return res;
2222 }
2223
2224 mDummyStreamId = mNextStreamId;
2225 mNextStreamId++;
2226
2227 return OK;
2228}
2229
2230status_t Camera3Device::tryRemoveDummyStreamLocked() {
2231 ATRACE_CALL();
2232 status_t res;
2233
2234 if (mDummyStreamId == NO_STREAM) return OK;
2235 if (mOutputStreams.size() == 1) return OK;
2236
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002237 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002238
2239 // Ok, have a dummy stream and there's at least one other output stream,
2240 // so remove the dummy
2241
2242 sp<Camera3StreamInterface> deletedStream;
2243 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2244 if (outputStreamIdx == NAME_NOT_FOUND) {
2245 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2246 return INVALID_OPERATION;
2247 }
2248
2249 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2250 mOutputStreams.removeItemsAt(outputStreamIdx);
2251
2252 // Free up the stream endpoint so that it can be used by some other stream
2253 res = deletedStream->disconnect();
2254 if (res != OK) {
2255 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2256 // fall through since we want to still list the stream as deleted.
2257 }
2258 mDeletedStreams.add(deletedStream);
2259 mDummyStreamId = NO_STREAM;
2260
2261 return res;
2262}
2263
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002264void Camera3Device::setErrorState(const char *fmt, ...) {
2265 Mutex::Autolock l(mLock);
2266 va_list args;
2267 va_start(args, fmt);
2268
2269 setErrorStateLockedV(fmt, args);
2270
2271 va_end(args);
2272}
2273
2274void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2275 Mutex::Autolock l(mLock);
2276 setErrorStateLockedV(fmt, args);
2277}
2278
2279void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2280 va_list args;
2281 va_start(args, fmt);
2282
2283 setErrorStateLockedV(fmt, args);
2284
2285 va_end(args);
2286}
2287
2288void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002289 // Print out all error messages to log
2290 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002291 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002292
2293 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002294 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002295
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002296 mErrorCause = errorCause;
2297
2298 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002299 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002300
2301 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002302 sp<NotificationListener> listener = mListener.promote();
2303 if (listener != NULL) {
2304 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002305 CaptureResultExtras());
2306 }
2307
2308 // Save stack trace. View by dumping it later.
2309 CameraTraces::saveTrace();
2310 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002311}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312
2313/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002314 * In-flight request management
2315 */
2316
Jianing Weicb0652e2014-03-12 18:29:36 -07002317status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002318 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002319 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002320 ATRACE_CALL();
2321 Mutex::Autolock l(mInFlightLock);
2322
2323 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002324 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002325 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002326 if (res < 0) return res;
2327
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002328 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002329 // hold mLock to prevent race with disconnect
2330 Mutex::Autolock l(mLock);
2331 if (mStatusTracker != nullptr) {
2332 mStatusTracker->markComponentActive(mInFlightStatusId);
2333 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002334 }
2335
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002336 return OK;
2337}
2338
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002339void Camera3Device::returnOutputBuffers(
2340 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2341 nsecs_t timestamp) {
2342 for (size_t i = 0; i < numBuffers; i++)
2343 {
2344 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2345 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2346 // Note: stream may be deallocated at this point, if this buffer was
2347 // the last reference to it.
2348 if (res != OK) {
2349 ALOGE("Can't return buffer to its stream: %s (%d)",
2350 strerror(-res), res);
2351 }
2352 }
2353}
2354
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002355void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2356 mInFlightMap.removeItemsAt(idx, 1);
2357
2358 // Indicate idle inFlightMap to the status tracker
2359 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002360 // hold mLock to prevent race with disconnect
2361 Mutex::Autolock l(mLock);
2362 if (mStatusTracker != nullptr) {
2363 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2364 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002365 }
2366}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002367
2368void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2369
2370 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2371 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2372
2373 nsecs_t sensorTimestamp = request.sensorTimestamp;
2374 nsecs_t shutterTimestamp = request.shutterTimestamp;
2375
Emilian Peevc6747862017-06-12 15:57:26 +01002376 bool skipResultMetadata = false;
2377 if (request.requestStatus != OK) {
2378 switch (request.requestStatus) {
2379 case CAMERA3_MSG_ERROR_DEVICE:
2380 case CAMERA3_MSG_ERROR_REQUEST:
2381 case CAMERA3_MSG_ERROR_RESULT:
2382 skipResultMetadata = true;
2383 break;
2384 case CAMERA3_MSG_ERROR_BUFFER:
2385 //Result metadata should return in this case.
2386 skipResultMetadata = false;
2387 break;
2388 default:
2389 SET_ERR("Unknown error message: %d", request.requestStatus);
2390 skipResultMetadata = false;
2391 break;
2392 }
2393 }
2394
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002395 // Check if it's okay to remove the request from InFlightMap:
2396 // In the case of a successful request:
2397 // all input and output buffers, all result metadata, shutter callback
2398 // arrived.
2399 // In the case of a unsuccessful request:
2400 // all input and output buffers arrived.
2401 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002402 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002403 (request.haveResultMetadata && shutterTimestamp != 0))) {
2404 ATRACE_ASYNC_END("frame capture", frameNumber);
2405
Shuzhen Wang403044a2017-02-26 23:29:04 -08002406 // Sanity check - if sensor timestamp matches shutter timestamp in the
2407 // case of request having callback.
2408 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002409 sensorTimestamp != shutterTimestamp) {
2410 SET_ERR("sensor timestamp (%" PRId64
2411 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2412 sensorTimestamp, frameNumber, shutterTimestamp);
2413 }
2414
2415 // for an unsuccessful request, it may have pending output buffers to
2416 // return.
2417 assert(request.requestStatus != OK ||
2418 request.pendingOutputBuffers.size() == 0);
2419 returnOutputBuffers(request.pendingOutputBuffers.array(),
2420 request.pendingOutputBuffers.size(), 0);
2421
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002422 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002423 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2424 }
2425
2426 // Sanity check - if we have too many in-flight frames, something has
2427 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002428 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002429 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002430 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2431 kInFlightWarnLimitHighSpeed) {
2432 CLOGE("In-flight list too large for high speed configuration: %zu",
2433 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002434 }
2435}
2436
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002437void Camera3Device::insertResultLocked(CaptureResult *result,
2438 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002439 if (result == nullptr) return;
2440
Emilian Peev71c73a22017-03-21 16:35:51 +00002441 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2442 result->mMetadata.getAndLock());
2443 set_camera_metadata_vendor_id(meta, mVendorTagId);
2444 result->mMetadata.unlock(meta);
2445
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002446 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2447 (int32_t*)&frameNumber, 1) != OK) {
2448 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2449 return;
2450 }
2451
2452 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2453 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2454 return;
2455 }
2456
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002457 // Valid result, insert into queue
2458 List<CaptureResult>::iterator queuedResult =
2459 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2460 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2461 ", burstId = %" PRId32, __FUNCTION__,
2462 queuedResult->mResultExtras.requestId,
2463 queuedResult->mResultExtras.frameNumber,
2464 queuedResult->mResultExtras.burstId);
2465
2466 mResultSignal.signal();
2467}
2468
2469
2470void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002471 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002472 Mutex::Autolock l(mOutputLock);
2473
2474 CaptureResult captureResult;
2475 captureResult.mResultExtras = resultExtras;
2476 captureResult.mMetadata = partialResult;
2477
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002478 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002479}
2480
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002481
2482void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2483 CaptureResultExtras &resultExtras,
2484 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002485 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002486 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002487 if (pendingMetadata.isEmpty())
2488 return;
2489
2490 Mutex::Autolock l(mOutputLock);
2491
2492 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002493 if (reprocess) {
2494 if (frameNumber < mNextReprocessResultFrameNumber) {
2495 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002496 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002497 frameNumber, mNextReprocessResultFrameNumber);
2498 return;
2499 }
2500 mNextReprocessResultFrameNumber = frameNumber + 1;
2501 } else {
2502 if (frameNumber < mNextResultFrameNumber) {
2503 SET_ERR("Out-of-order capture result metadata submitted! "
2504 "(got frame number %d, expecting %d)",
2505 frameNumber, mNextResultFrameNumber);
2506 return;
2507 }
2508 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002509 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002510
2511 CaptureResult captureResult;
2512 captureResult.mResultExtras = resultExtras;
2513 captureResult.mMetadata = pendingMetadata;
2514
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002515 // Append any previous partials to form a complete result
2516 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2517 captureResult.mMetadata.append(collectedPartialResult);
2518 }
2519
2520 captureResult.mMetadata.sort();
2521
2522 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002523 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2524 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002525 SET_ERR("No timestamp provided by HAL for frame %d!",
2526 frameNumber);
2527 return;
2528 }
2529
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002530 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2531 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2532
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002533 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002534}
2535
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002536/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002537 * Camera HAL device callback methods
2538 */
2539
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002540void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002541 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002542
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002543 status_t res;
2544
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002545 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002546 if (result->result == NULL && result->num_output_buffers == 0 &&
2547 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002548 SET_ERR("No result data provided by HAL for frame %d",
2549 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002550 return;
2551 }
Zhijun He204e3292014-07-14 17:09:23 -07002552
Zhijun He204e3292014-07-14 17:09:23 -07002553 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002554 result->result != NULL &&
2555 result->partial_result != 1) {
2556 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2557 " if partial result is not supported",
2558 frameNumber, result->partial_result);
2559 return;
2560 }
2561
2562 bool isPartialResult = false;
2563 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002564 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002565 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002566
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002567 // Get shutter timestamp and resultExtras from list of in-flight requests,
2568 // where it was added by the shutter notification for this frame. If the
2569 // shutter timestamp isn't received yet, append the output buffers to the
2570 // in-flight request and they will be returned when the shutter timestamp
2571 // arrives. Update the in-flight status and remove the in-flight entry if
2572 // all result data and shutter timestamp have been received.
2573 nsecs_t shutterTimestamp = 0;
2574
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002575 {
2576 Mutex::Autolock l(mInFlightLock);
2577 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2578 if (idx == NAME_NOT_FOUND) {
2579 SET_ERR("Unknown frame number for capture result: %d",
2580 frameNumber);
2581 return;
2582 }
2583 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002584 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2585 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002586 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002587 __FUNCTION__, request.resultExtras.requestId,
2588 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002589 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002590 // Always update the partial count to the latest one if it's not 0
2591 // (buffers only). When framework aggregates adjacent partial results
2592 // into one, the latest partial count will be used.
2593 if (result->partial_result != 0)
2594 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002595
2596 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002597 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002598 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2599 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2600 " the range of [1, %d] when metadata is included in the result",
2601 frameNumber, result->partial_result, mNumPartialResults);
2602 return;
2603 }
2604 isPartialResult = (result->partial_result < mNumPartialResults);
2605 if (isPartialResult) {
2606 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002607 }
2608
Shuzhen Wang4a472662017-02-26 23:29:04 -08002609 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002610 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002611 sendPartialCaptureResult(result->result, request.resultExtras,
2612 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002613 }
2614 }
2615
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002616 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002617 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002618
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002619 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002620 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002621 if (request.haveResultMetadata) {
2622 SET_ERR("Called multiple times with metadata for frame %d",
2623 frameNumber);
2624 return;
2625 }
Zhijun He204e3292014-07-14 17:09:23 -07002626 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002627 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002628 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002629 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002630 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002631 request.haveResultMetadata = true;
2632 }
2633
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002634 uint32_t numBuffersReturned = result->num_output_buffers;
2635 if (result->input_buffer != NULL) {
2636 if (hasInputBufferInRequest) {
2637 numBuffersReturned += 1;
2638 } else {
2639 ALOGW("%s: Input buffer should be NULL if there is no input"
2640 " buffer sent in the request",
2641 __FUNCTION__);
2642 }
2643 }
2644 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002645 if (request.numBuffersLeft < 0) {
2646 SET_ERR("Too many buffers returned for frame %d",
2647 frameNumber);
2648 return;
2649 }
2650
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002651 camera_metadata_ro_entry_t entry;
2652 res = find_camera_metadata_ro_entry(result->result,
2653 ANDROID_SENSOR_TIMESTAMP, &entry);
2654 if (res == OK && entry.count == 1) {
2655 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002656 }
2657
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002658 // If shutter event isn't received yet, append the output buffers to
2659 // the in-flight request. Otherwise, return the output buffers to
2660 // streams.
2661 if (shutterTimestamp == 0) {
2662 request.pendingOutputBuffers.appendArray(result->output_buffers,
2663 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002664 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002665 returnOutputBuffers(result->output_buffers,
2666 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002667 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002668
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002669 if (result->result != NULL && !isPartialResult) {
2670 if (shutterTimestamp == 0) {
2671 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002672 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002673 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002674 CameraMetadata metadata;
2675 metadata = result->result;
2676 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002677 collectedPartialResult, frameNumber,
2678 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002679 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002680 }
2681
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002682 removeInFlightRequestIfReadyLocked(idx);
2683 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002684
Zhijun Hef0d962a2014-06-30 10:24:11 -07002685 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002686 if (hasInputBufferInRequest) {
2687 Camera3Stream *stream =
2688 Camera3Stream::cast(result->input_buffer->stream);
2689 res = stream->returnInputBuffer(*(result->input_buffer));
2690 // Note: stream may be deallocated at this point, if this buffer was the
2691 // last reference to it.
2692 if (res != OK) {
2693 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2694 " its stream:%s (%d)", __FUNCTION__,
2695 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002696 }
2697 } else {
2698 ALOGW("%s: Input buffer should be NULL if there is no input"
2699 " buffer sent in the request, skipping input buffer return.",
2700 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002701 }
2702 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002703}
2704
2705void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002706 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002707 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002708 {
2709 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002710 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002711 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002712
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002713 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002714 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002715 return;
2716 }
2717
2718 switch (msg->type) {
2719 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002720 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002721 break;
2722 }
2723 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002724 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002725 break;
2726 }
2727 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002728 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002729 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002730 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002731}
2732
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002733void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002734 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002735
2736 // Map camera HAL error codes to ICameraDeviceCallback error codes
2737 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002738 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002739 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002740 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002741 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002742 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002743 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002744 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002745 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002746 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002747 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002748 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002749 };
2750
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002751 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002752 ((msg.error_code >= 0) &&
2753 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2754 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002755 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002756
2757 int streamId = 0;
2758 if (msg.error_stream != NULL) {
2759 Camera3Stream *stream =
2760 Camera3Stream::cast(msg.error_stream);
2761 streamId = stream->getId();
2762 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002763 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2764 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002765 streamId, msg.error_code);
2766
2767 CaptureResultExtras resultExtras;
2768 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002769 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002770 // SET_ERR calls notifyError
2771 SET_ERR("Camera HAL reported serious device error");
2772 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002773 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2774 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2775 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002776 {
2777 Mutex::Autolock l(mInFlightLock);
2778 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2779 if (idx >= 0) {
2780 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2781 r.requestStatus = msg.error_code;
2782 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002783 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2784 errorCode) {
2785 // In case of missing result check whether the buffers
2786 // returned. If they returned, then remove inflight
2787 // request.
2788 removeInFlightRequestIfReadyLocked(idx);
2789 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002790 } else {
2791 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002792 ALOGE("Camera %s: %s: cannot find in-flight request on "
2793 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002794 resultExtras.frameNumber);
2795 }
2796 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002797 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002798 if (listener != NULL) {
2799 listener->notifyError(errorCode, resultExtras);
2800 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002801 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002802 }
2803 break;
2804 default:
2805 // SET_ERR calls notifyError
2806 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2807 break;
2808 }
2809}
2810
2811void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002812 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002813 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002814
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002815 // Set timestamp for the request in the in-flight tracking
2816 // and get the request ID to send upstream
2817 {
2818 Mutex::Autolock l(mInFlightLock);
2819 idx = mInFlightMap.indexOfKey(msg.frame_number);
2820 if (idx >= 0) {
2821 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002822
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002823 // Verify ordering of shutter notifications
2824 {
2825 Mutex::Autolock l(mOutputLock);
2826 // TODO: need to track errors for tighter bounds on expected frame number.
2827 if (r.hasInputBuffer) {
2828 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2829 SET_ERR("Shutter notification out-of-order. Expected "
2830 "notification for frame %d, got frame %d",
2831 mNextReprocessShutterFrameNumber, msg.frame_number);
2832 return;
2833 }
2834 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2835 } else {
2836 if (msg.frame_number < mNextShutterFrameNumber) {
2837 SET_ERR("Shutter notification out-of-order. Expected "
2838 "notification for frame %d, got frame %d",
2839 mNextShutterFrameNumber, msg.frame_number);
2840 return;
2841 }
2842 mNextShutterFrameNumber = msg.frame_number + 1;
2843 }
2844 }
2845
Shuzhen Wang4a472662017-02-26 23:29:04 -08002846 r.shutterTimestamp = msg.timestamp;
2847 if (r.hasCallback) {
2848 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002849 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002850 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002851 // Call listener, if any
2852 if (listener != NULL) {
2853 listener->notifyShutter(r.resultExtras, msg.timestamp);
2854 }
2855 // send pending result and buffers
2856 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2857 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002858 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002859 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002860 returnOutputBuffers(r.pendingOutputBuffers.array(),
2861 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2862 r.pendingOutputBuffers.clear();
2863
2864 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002865 }
2866 }
2867 if (idx < 0) {
2868 SET_ERR("Shutter notification for non-existent frame number %d",
2869 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002870 }
2871}
2872
2873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002874CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002875 ALOGV("%s", __FUNCTION__);
2876
Igor Murashkin1e479c02013-09-06 16:55:14 -07002877 CameraMetadata retVal;
2878
2879 if (mRequestThread != NULL) {
2880 retVal = mRequestThread->getLatestRequest();
2881 }
2882
Igor Murashkin1e479c02013-09-06 16:55:14 -07002883 return retVal;
2884}
2885
Jianing Weicb0652e2014-03-12 18:29:36 -07002886
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002887void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2888 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2889 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2890}
2891
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002892/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002893 * HalInterface inner class methods
2894 */
2895
Yifan Hongf79b5542017-04-11 14:44:25 -07002896Camera3Device::HalInterface::HalInterface(
2897 sp<ICameraDeviceSession> &session,
2898 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002899 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002900 mHidlSession(session),
2901 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002902
2903Camera3Device::HalInterface::HalInterface() :
2904 mHal3Device(nullptr) {}
2905
2906Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002907 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002908 mHidlSession(other.mHidlSession),
2909 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002910
2911bool Camera3Device::HalInterface::valid() {
2912 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2913}
2914
2915void Camera3Device::HalInterface::clear() {
2916 mHal3Device = nullptr;
2917 mHidlSession.clear();
2918}
2919
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002920bool Camera3Device::HalInterface::supportBatchRequest() {
2921 return mHidlSession != nullptr;
2922}
2923
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002924status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2925 camera3_request_template_t templateId,
2926 /*out*/ camera_metadata_t **requestTemplate) {
2927 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2928 if (!valid()) return INVALID_OPERATION;
2929 status_t res = OK;
2930
2931 if (mHal3Device != nullptr) {
2932 const camera_metadata *r;
2933 r = mHal3Device->ops->construct_default_request_settings(
2934 mHal3Device, templateId);
2935 if (r == nullptr) return BAD_VALUE;
2936 *requestTemplate = clone_camera_metadata(r);
2937 if (requestTemplate == nullptr) {
2938 ALOGE("%s: Unable to clone camera metadata received from HAL",
2939 __FUNCTION__);
2940 return INVALID_OPERATION;
2941 }
2942 } else {
2943 common::V1_0::Status status;
2944 RequestTemplate id;
2945 switch (templateId) {
2946 case CAMERA3_TEMPLATE_PREVIEW:
2947 id = RequestTemplate::PREVIEW;
2948 break;
2949 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2950 id = RequestTemplate::STILL_CAPTURE;
2951 break;
2952 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2953 id = RequestTemplate::VIDEO_RECORD;
2954 break;
2955 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2956 id = RequestTemplate::VIDEO_SNAPSHOT;
2957 break;
2958 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2959 id = RequestTemplate::ZERO_SHUTTER_LAG;
2960 break;
2961 case CAMERA3_TEMPLATE_MANUAL:
2962 id = RequestTemplate::MANUAL;
2963 break;
2964 default:
2965 // Unknown template ID
2966 return BAD_VALUE;
2967 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002968 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002969 [&status, &requestTemplate]
2970 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
2971 status = s;
2972 if (status == common::V1_0::Status::OK) {
2973 const camera_metadata *r =
2974 reinterpret_cast<const camera_metadata_t*>(request.data());
2975 size_t expectedSize = request.size();
2976 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07002977 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002978 *requestTemplate = clone_camera_metadata(r);
2979 if (*requestTemplate == nullptr) {
2980 ALOGE("%s: Unable to clone camera metadata received from HAL",
2981 __FUNCTION__);
2982 status = common::V1_0::Status::INTERNAL_ERROR;
2983 }
2984 } else {
2985 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2986 status = common::V1_0::Status::INTERNAL_ERROR;
2987 }
2988 }
2989 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002990 if (!err.isOk()) {
2991 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2992 res = DEAD_OBJECT;
2993 } else {
2994 res = CameraProviderManager::mapToStatusT(status);
2995 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002996 }
2997 return res;
2998}
2999
3000status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3001 ATRACE_NAME("CameraHal::configureStreams");
3002 if (!valid()) return INVALID_OPERATION;
3003 status_t res = OK;
3004
3005 if (mHal3Device != nullptr) {
3006 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3007 } else {
3008 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003009 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003010 StreamConfiguration requestedConfiguration;
3011 requestedConfiguration.streams.resize(config->num_streams);
3012 for (size_t i = 0; i < config->num_streams; i++) {
3013 Stream &dst = requestedConfiguration.streams[i];
3014 camera3_stream_t *src = config->streams[i];
3015
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003016 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3017 cam3stream->setBufferFreedListener(this);
3018 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003019 StreamType streamType;
3020 switch (src->stream_type) {
3021 case CAMERA3_STREAM_OUTPUT:
3022 streamType = StreamType::OUTPUT;
3023 break;
3024 case CAMERA3_STREAM_INPUT:
3025 streamType = StreamType::INPUT;
3026 break;
3027 default:
3028 ALOGE("%s: Stream %d: Unsupported stream type %d",
3029 __FUNCTION__, streamId, config->streams[i]->stream_type);
3030 return BAD_VALUE;
3031 }
3032 dst.id = streamId;
3033 dst.streamType = streamType;
3034 dst.width = src->width;
3035 dst.height = src->height;
3036 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003037 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003038 dst.dataSpace = mapToHidlDataspace(src->data_space);
3039 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003040
3041 activeStreams.insert(streamId);
3042 // Create Buffer ID map if necessary
3043 if (mBufferIdMaps.count(streamId) == 0) {
3044 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3045 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003046 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003047 // remove BufferIdMap for deleted streams
3048 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3049 int streamId = it->first;
3050 bool active = activeStreams.count(streamId) > 0;
3051 if (!active) {
3052 it = mBufferIdMaps.erase(it);
3053 } else {
3054 ++it;
3055 }
3056 }
3057
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003058 res = mapToStreamConfigurationMode(
3059 (camera3_stream_configuration_mode_t) config->operation_mode,
3060 /*out*/ &requestedConfiguration.operationMode);
3061 if (res != OK) {
3062 return res;
3063 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003064
3065 // Invoke configureStreams
3066
3067 HalStreamConfiguration finalConfiguration;
3068 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003069 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003070 [&status, &finalConfiguration]
3071 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3072 finalConfiguration = halConfiguration;
3073 status = s;
3074 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003075 if (!err.isOk()) {
3076 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3077 return DEAD_OBJECT;
3078 }
3079
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003080 if (status != common::V1_0::Status::OK ) {
3081 return CameraProviderManager::mapToStatusT(status);
3082 }
3083
3084 // And convert output stream configuration from HIDL
3085
3086 for (size_t i = 0; i < config->num_streams; i++) {
3087 camera3_stream_t *dst = config->streams[i];
3088 int streamId = Camera3Stream::cast(dst)->getId();
3089
3090 // Start scan at i, with the assumption that the stream order matches
3091 size_t realIdx = i;
3092 bool found = false;
3093 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3094 if (finalConfiguration.streams[realIdx].id == streamId) {
3095 found = true;
3096 break;
3097 }
3098 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3099 }
3100 if (!found) {
3101 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3102 __FUNCTION__, streamId);
3103 return INVALID_OPERATION;
3104 }
3105 HalStream &src = finalConfiguration.streams[realIdx];
3106
3107 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3108 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3109 if (dst->format != overrideFormat) {
3110 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3111 streamId, dst->format);
3112 }
3113 } else {
3114 // Override allowed with IMPLEMENTATION_DEFINED
3115 dst->format = overrideFormat;
3116 }
3117
3118 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3119 if (src.producerUsage != 0) {
3120 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3121 __FUNCTION__, streamId);
3122 return INVALID_OPERATION;
3123 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003124 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125 } else {
3126 // OUTPUT
3127 if (src.consumerUsage != 0) {
3128 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3129 __FUNCTION__, streamId);
3130 return INVALID_OPERATION;
3131 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003132 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003133 }
3134 dst->max_buffers = src.maxBuffers;
3135 }
3136 }
3137 return res;
3138}
3139
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003140void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3141 /*out*/device::V3_2::CaptureRequest* captureRequest,
3142 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3143
3144 if (captureRequest == nullptr || handlesCreated == nullptr) {
3145 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3146 __FUNCTION__, captureRequest, handlesCreated);
3147 return;
3148 }
3149
3150 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003151
3152 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003153
3154 {
3155 std::lock_guard<std::mutex> lock(mInflightLock);
3156 if (request->input_buffer != nullptr) {
3157 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3158 buffer_handle_t buf = *(request->input_buffer->buffer);
3159 auto pair = getBufferId(buf, streamId);
3160 bool isNewBuffer = pair.first;
3161 uint64_t bufferId = pair.second;
3162 captureRequest->inputBuffer.streamId = streamId;
3163 captureRequest->inputBuffer.bufferId = bufferId;
3164 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3165 captureRequest->inputBuffer.status = BufferStatus::OK;
3166 native_handle_t *acquireFence = nullptr;
3167 if (request->input_buffer->acquire_fence != -1) {
3168 acquireFence = native_handle_create(1,0);
3169 acquireFence->data[0] = request->input_buffer->acquire_fence;
3170 handlesCreated->push_back(acquireFence);
3171 }
3172 captureRequest->inputBuffer.acquireFence = acquireFence;
3173 captureRequest->inputBuffer.releaseFence = nullptr;
3174
3175 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3176 request->input_buffer->buffer,
3177 request->input_buffer->acquire_fence);
3178 } else {
3179 captureRequest->inputBuffer.streamId = -1;
3180 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3181 }
3182
3183 captureRequest->outputBuffers.resize(request->num_output_buffers);
3184 for (size_t i = 0; i < request->num_output_buffers; i++) {
3185 const camera3_stream_buffer_t *src = request->output_buffers + i;
3186 StreamBuffer &dst = captureRequest->outputBuffers[i];
3187 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3188 buffer_handle_t buf = *(src->buffer);
3189 auto pair = getBufferId(buf, streamId);
3190 bool isNewBuffer = pair.first;
3191 dst.streamId = streamId;
3192 dst.bufferId = pair.second;
3193 dst.buffer = isNewBuffer ? buf : nullptr;
3194 dst.status = BufferStatus::OK;
3195 native_handle_t *acquireFence = nullptr;
3196 if (src->acquire_fence != -1) {
3197 acquireFence = native_handle_create(1,0);
3198 acquireFence->data[0] = src->acquire_fence;
3199 handlesCreated->push_back(acquireFence);
3200 }
3201 dst.acquireFence = acquireFence;
3202 dst.releaseFence = nullptr;
3203
3204 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3205 src->buffer, src->acquire_fence);
3206 }
3207 }
3208}
3209
3210status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3211 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3212 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3213 if (!valid()) return INVALID_OPERATION;
3214
3215 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3216 size_t batchSize = requests.size();
3217 captureRequests.resize(batchSize);
3218 std::vector<native_handle_t*> handlesCreated;
3219
3220 for (size_t i = 0; i < batchSize; i++) {
3221 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3222 }
3223
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003224 std::vector<device::V3_2::BufferCache> cachesToRemove;
3225 {
3226 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3227 for (auto& pair : mFreedBuffers) {
3228 // The stream might have been removed since onBufferFreed
3229 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3230 cachesToRemove.push_back({pair.first, pair.second});
3231 }
3232 }
3233 mFreedBuffers.clear();
3234 }
3235
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003236 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3237 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003238
3239 // Write metadata to FMQ.
3240 for (size_t i = 0; i < batchSize; i++) {
3241 camera3_capture_request_t* request = requests[i];
3242 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3243
3244 if (request->settings != nullptr) {
3245 size_t settingsSize = get_camera_metadata_size(request->settings);
3246 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3247 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3248 captureRequest->settings.resize(0);
3249 captureRequest->fmqSettingsSize = settingsSize;
3250 } else {
3251 if (mRequestMetadataQueue != nullptr) {
3252 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3253 }
3254 captureRequest->settings.setToExternal(
3255 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3256 get_camera_metadata_size(request->settings));
3257 captureRequest->fmqSettingsSize = 0u;
3258 }
3259 } else {
3260 // A null request settings maps to a size-0 CameraMetadata
3261 captureRequest->settings.resize(0);
3262 captureRequest->fmqSettingsSize = 0u;
3263 }
3264 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003265 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003266 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3267 status = s;
3268 *numRequestProcessed = n;
3269 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003270 if (!err.isOk()) {
3271 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3272 return DEAD_OBJECT;
3273 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003274 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3275 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3276 __FUNCTION__, *numRequestProcessed, batchSize);
3277 status = common::V1_0::Status::INTERNAL_ERROR;
3278 }
3279
3280 for (auto& handle : handlesCreated) {
3281 native_handle_delete(handle);
3282 }
3283 return CameraProviderManager::mapToStatusT(status);
3284}
3285
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003286status_t Camera3Device::HalInterface::processCaptureRequest(
3287 camera3_capture_request_t *request) {
3288 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003289 if (!valid()) return INVALID_OPERATION;
3290 status_t res = OK;
3291
3292 if (mHal3Device != nullptr) {
3293 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3294 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003295 uint32_t numRequestProcessed = 0;
3296 std::vector<camera3_capture_request_t*> requests(1);
3297 requests[0] = request;
3298 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003299 }
3300 return res;
3301}
3302
3303status_t Camera3Device::HalInterface::flush() {
3304 ATRACE_NAME("CameraHal::flush");
3305 if (!valid()) return INVALID_OPERATION;
3306 status_t res = OK;
3307
3308 if (mHal3Device != nullptr) {
3309 res = mHal3Device->ops->flush(mHal3Device);
3310 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003311 auto err = mHidlSession->flush();
3312 if (!err.isOk()) {
3313 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3314 res = DEAD_OBJECT;
3315 } else {
3316 res = CameraProviderManager::mapToStatusT(err);
3317 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003318 }
3319 return res;
3320}
3321
3322status_t Camera3Device::HalInterface::dump(int fd) {
3323 ATRACE_NAME("CameraHal::dump");
3324 if (!valid()) return INVALID_OPERATION;
3325 status_t res = OK;
3326
3327 if (mHal3Device != nullptr) {
3328 mHal3Device->ops->dump(mHal3Device, fd);
3329 } else {
3330 // Handled by CameraProviderManager::dump
3331 }
3332 return res;
3333}
3334
3335status_t Camera3Device::HalInterface::close() {
3336 ATRACE_NAME("CameraHal::close()");
3337 if (!valid()) return INVALID_OPERATION;
3338 status_t res = OK;
3339
3340 if (mHal3Device != nullptr) {
3341 mHal3Device->common.close(&mHal3Device->common);
3342 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003343 auto err = mHidlSession->close();
3344 // Interface will be dead shortly anyway, so don't log errors
3345 if (!err.isOk()) {
3346 res = DEAD_OBJECT;
3347 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003348 }
3349 return res;
3350}
3351
3352status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003353 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003354 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003355 auto pair = std::make_pair(buffer, acquireFence);
3356 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003357 return OK;
3358}
3359
3360status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003361 int32_t frameNumber, int32_t streamId,
3362 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003363 std::lock_guard<std::mutex> lock(mInflightLock);
3364
3365 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3366 auto it = mInflightBufferMap.find(key);
3367 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003368 auto pair = it->second;
3369 *buffer = pair.first;
3370 int acquireFence = pair.second;
3371 if (acquireFence > 0) {
3372 ::close(acquireFence);
3373 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003374 mInflightBufferMap.erase(it);
3375 return OK;
3376}
3377
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003378std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3379 const buffer_handle_t& buf, int streamId) {
3380 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3381
3382 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3383 auto it = bIdMap.find(buf);
3384 if (it == bIdMap.end()) {
3385 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003386 ALOGV("stream %d now have %zu buffer caches, buf %p",
3387 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003388 return std::make_pair(true, mNextBufferId - 1);
3389 } else {
3390 return std::make_pair(false, it->second);
3391 }
3392}
3393
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003394void Camera3Device::HalInterface::onBufferFreed(
3395 int streamId, const native_handle_t* handle) {
3396 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3397 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3398 auto mapIt = mBufferIdMaps.find(streamId);
3399 if (mapIt == mBufferIdMaps.end()) {
3400 // streamId might be from a deleted stream here
3401 ALOGI("%s: stream %d has been removed",
3402 __FUNCTION__, streamId);
3403 return;
3404 }
3405 BufferIdMap& bIdMap = mapIt->second;
3406 auto it = bIdMap.find(handle);
3407 if (it == bIdMap.end()) {
3408 ALOGW("%s: cannot find buffer %p in stream %d",
3409 __FUNCTION__, handle, streamId);
3410 return;
3411 } else {
3412 bufferId = it->second;
3413 bIdMap.erase(it);
3414 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3415 __FUNCTION__, streamId, bIdMap.size(), handle);
3416 }
3417 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3418}
3419
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003420/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003421 * RequestThread inner class methods
3422 */
3423
3424Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003425 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003426 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003427 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003428 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003429 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003431 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003432 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003433 mReconfigured(false),
3434 mDoPause(false),
3435 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003436 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003437 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003438 mCurrentAfTriggerId(0),
3439 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003440 mRepeatingLastFrameNumber(
3441 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003442 mPrepareVideoStream(false),
3443 mRequestLatency(kRequestLatencyBinSize) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003444 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003445}
3446
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003447Camera3Device::RequestThread::~RequestThread() {}
3448
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003449void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003450 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003451 Mutex::Autolock l(mRequestLock);
3452 mListener = listener;
3453}
3454
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003455void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003456 Mutex::Autolock l(mRequestLock);
3457 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003458 // Prepare video stream for high speed recording.
3459 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003460}
3461
Jianing Wei90e59c92014-03-12 18:29:36 -07003462status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003463 List<sp<CaptureRequest> > &requests,
3464 /*out*/
3465 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003466 Mutex::Autolock l(mRequestLock);
3467 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3468 ++it) {
3469 mRequestQueue.push_back(*it);
3470 }
3471
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003472 if (lastFrameNumber != NULL) {
3473 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3474 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3475 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3476 *lastFrameNumber);
3477 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003478
Jianing Wei90e59c92014-03-12 18:29:36 -07003479 unpauseForNewRequests();
3480
3481 return OK;
3482}
3483
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003484
3485status_t Camera3Device::RequestThread::queueTrigger(
3486 RequestTrigger trigger[],
3487 size_t count) {
3488
3489 Mutex::Autolock l(mTriggerMutex);
3490 status_t ret;
3491
3492 for (size_t i = 0; i < count; ++i) {
3493 ret = queueTriggerLocked(trigger[i]);
3494
3495 if (ret != OK) {
3496 return ret;
3497 }
3498 }
3499
3500 return OK;
3501}
3502
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003503const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3504 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003505 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003506 if (d != nullptr) return d->mId;
3507 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003508}
3509
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003510status_t Camera3Device::RequestThread::queueTriggerLocked(
3511 RequestTrigger trigger) {
3512
3513 uint32_t tag = trigger.metadataTag;
3514 ssize_t index = mTriggerMap.indexOfKey(tag);
3515
3516 switch (trigger.getTagType()) {
3517 case TYPE_BYTE:
3518 // fall-through
3519 case TYPE_INT32:
3520 break;
3521 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003522 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3523 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003524 return INVALID_OPERATION;
3525 }
3526
3527 /**
3528 * Collect only the latest trigger, since we only have 1 field
3529 * in the request settings per trigger tag, and can't send more than 1
3530 * trigger per request.
3531 */
3532 if (index != NAME_NOT_FOUND) {
3533 mTriggerMap.editValueAt(index) = trigger;
3534 } else {
3535 mTriggerMap.add(tag, trigger);
3536 }
3537
3538 return OK;
3539}
3540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003541status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003542 const RequestList &requests,
3543 /*out*/
3544 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003545 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003546 if (lastFrameNumber != NULL) {
3547 *lastFrameNumber = mRepeatingLastFrameNumber;
3548 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003549 mRepeatingRequests.clear();
3550 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3551 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003552
3553 unpauseForNewRequests();
3554
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003555 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003556 return OK;
3557}
3558
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003559bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003560 if (mRepeatingRequests.empty()) {
3561 return false;
3562 }
3563 int32_t requestId = requestIn->mResultExtras.requestId;
3564 const RequestList &repeatRequests = mRepeatingRequests;
3565 // All repeating requests are guaranteed to have same id so only check first quest
3566 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3567 return (firstRequest->mResultExtras.requestId == requestId);
3568}
3569
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003570status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003571 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003572 return clearRepeatingRequestsLocked(lastFrameNumber);
3573
3574}
3575
3576status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003577 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003578 if (lastFrameNumber != NULL) {
3579 *lastFrameNumber = mRepeatingLastFrameNumber;
3580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003581 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003582 return OK;
3583}
3584
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003585status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003586 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003587 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003588 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003589
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003590 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003591
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003592 // Send errors for all requests pending in the request queue, including
3593 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003594 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003595 if (listener != NULL) {
3596 for (RequestList::iterator it = mRequestQueue.begin();
3597 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003598 // Abort the input buffers for reprocess requests.
3599 if ((*it)->mInputStream != NULL) {
3600 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003601 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3602 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003603 if (res != OK) {
3604 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3605 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3606 } else {
3607 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3608 if (res != OK) {
3609 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3610 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3611 }
3612 }
3613 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003614 // Set the frame number this request would have had, if it
3615 // had been submitted; this frame number will not be reused.
3616 // The requestId and burstId fields were set when the request was
3617 // submitted originally (in convertMetadataListToRequestListLocked)
3618 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003619 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003620 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003621 }
3622 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003623 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003624
3625 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003626 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003627 if (lastFrameNumber != NULL) {
3628 *lastFrameNumber = mRepeatingLastFrameNumber;
3629 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003630 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003631 return OK;
3632}
3633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003634status_t Camera3Device::RequestThread::flush() {
3635 ATRACE_CALL();
3636 Mutex::Autolock l(mFlushLock);
3637
Emilian Peev08dd2452017-04-06 16:55:14 +01003638 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003639}
3640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003641void Camera3Device::RequestThread::setPaused(bool paused) {
3642 Mutex::Autolock l(mPauseLock);
3643 mDoPause = paused;
3644 mDoPauseSignal.signal();
3645}
3646
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003647status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3648 int32_t requestId, nsecs_t timeout) {
3649 Mutex::Autolock l(mLatestRequestMutex);
3650 status_t res;
3651 while (mLatestRequestId != requestId) {
3652 nsecs_t startTime = systemTime();
3653
3654 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3655 if (res != OK) return res;
3656
3657 timeout -= (systemTime() - startTime);
3658 }
3659
3660 return OK;
3661}
3662
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003663void Camera3Device::RequestThread::requestExit() {
3664 // Call parent to set up shutdown
3665 Thread::requestExit();
3666 // The exit from any possible waits
3667 mDoPauseSignal.signal();
3668 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003669
3670 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3671 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003672}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003673
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003674void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003675 bool surfaceAbandoned = false;
3676 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003677 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003678 {
3679 Mutex::Autolock l(mRequestLock);
3680 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3681 // repeating requests.
3682 for (const auto& request : mRepeatingRequests) {
3683 for (const auto& s : request->mOutputStreams) {
3684 if (s->isAbandoned()) {
3685 surfaceAbandoned = true;
3686 clearRepeatingRequestsLocked(&lastFrameNumber);
3687 break;
3688 }
3689 }
3690 if (surfaceAbandoned) {
3691 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003692 }
3693 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003694 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003695 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003696
3697 if (listener != NULL && surfaceAbandoned) {
3698 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003699 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003700}
3701
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003702bool Camera3Device::RequestThread::sendRequestsBatch() {
3703 status_t res;
3704 size_t batchSize = mNextRequests.size();
3705 std::vector<camera3_capture_request_t*> requests(batchSize);
3706 uint32_t numRequestProcessed = 0;
3707 for (size_t i = 0; i < batchSize; i++) {
3708 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3709 }
3710
3711 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3712 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3713
3714 bool triggerRemoveFailed = false;
3715 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3716 for (size_t i = 0; i < numRequestProcessed; i++) {
3717 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3718 nextRequest.submitted = true;
3719
3720
3721 // Update the latest request sent to HAL
3722 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3723 Mutex::Autolock al(mLatestRequestMutex);
3724
3725 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3726 mLatestRequest.acquire(cloned);
3727
3728 sp<Camera3Device> parent = mParent.promote();
3729 if (parent != NULL) {
3730 parent->monitorMetadata(TagMonitor::REQUEST,
3731 nextRequest.halRequest.frame_number,
3732 0, mLatestRequest);
3733 }
3734 }
3735
3736 if (nextRequest.halRequest.settings != NULL) {
3737 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3738 }
3739
3740 if (!triggerRemoveFailed) {
3741 // Remove any previously queued triggers (after unlock)
3742 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3743 if (removeTriggerRes != OK) {
3744 triggerRemoveFailed = true;
3745 triggerFailedRequest = nextRequest;
3746 }
3747 }
3748 }
3749
3750 if (triggerRemoveFailed) {
3751 SET_ERR("RequestThread: Unable to remove triggers "
3752 "(capture request %d, HAL device: %s (%d)",
3753 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3754 cleanUpFailedRequests(/*sendRequestError*/ false);
3755 return false;
3756 }
3757
3758 if (res != OK) {
3759 // Should only get a failure here for malformed requests or device-level
3760 // errors, so consider all errors fatal. Bad metadata failures should
3761 // come through notify.
3762 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3763 mNextRequests[numRequestProcessed].halRequest.frame_number,
3764 strerror(-res), res);
3765 cleanUpFailedRequests(/*sendRequestError*/ false);
3766 return false;
3767 }
3768 return true;
3769}
3770
3771bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3772 status_t res;
3773
3774 for (auto& nextRequest : mNextRequests) {
3775 // Submit request and block until ready for next one
3776 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3777 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3778
3779 if (res != OK) {
3780 // Should only get a failure here for malformed requests or device-level
3781 // errors, so consider all errors fatal. Bad metadata failures should
3782 // come through notify.
3783 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3784 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3785 res);
3786 cleanUpFailedRequests(/*sendRequestError*/ false);
3787 return false;
3788 }
3789
3790 // Mark that the request has be submitted successfully.
3791 nextRequest.submitted = true;
3792
3793 // Update the latest request sent to HAL
3794 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3795 Mutex::Autolock al(mLatestRequestMutex);
3796
3797 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3798 mLatestRequest.acquire(cloned);
3799
3800 sp<Camera3Device> parent = mParent.promote();
3801 if (parent != NULL) {
3802 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3803 0, mLatestRequest);
3804 }
3805 }
3806
3807 if (nextRequest.halRequest.settings != NULL) {
3808 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3809 }
3810
3811 // Remove any previously queued triggers (after unlock)
3812 res = removeTriggers(mPrevRequest);
3813 if (res != OK) {
3814 SET_ERR("RequestThread: Unable to remove triggers "
3815 "(capture request %d, HAL device: %s (%d)",
3816 nextRequest.halRequest.frame_number, strerror(-res), res);
3817 cleanUpFailedRequests(/*sendRequestError*/ false);
3818 return false;
3819 }
3820 }
3821 return true;
3822}
3823
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003824bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003825 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003826 status_t res;
3827
3828 // Handle paused state.
3829 if (waitIfPaused()) {
3830 return true;
3831 }
3832
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003833 // Wait for the next batch of requests.
3834 waitForNextRequestBatch();
3835 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003836 return true;
3837 }
3838
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003839 // Get the latest request ID, if any
3840 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003841 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003842 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003843 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003844 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003845 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003846 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3847 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003848 }
3849
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003850 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003851 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003852 if (res == TIMED_OUT) {
3853 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003854 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003855 // Check if any stream is abandoned.
3856 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003857 return true;
3858 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003859 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003860 return false;
3861 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003862
Zhijun Hecc27e112013-10-03 16:12:43 -07003863 // Inform waitUntilRequestProcessed thread of a new request ID
3864 {
3865 Mutex::Autolock al(mLatestRequestMutex);
3866
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003867 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003868 mLatestRequestSignal.signal();
3869 }
3870
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003871 // Submit a batch of requests to HAL.
3872 // Use flush lock only when submitting multilple requests in a batch.
3873 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3874 // which may take a long time to finish so synchronizing flush() and
3875 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3876 // For now, only synchronize for high speed recording and we should figure something out for
3877 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003878 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003879
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003880 if (useFlushLock) {
3881 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003882 }
3883
Zhijun Hef0645c12016-08-02 00:58:11 -07003884 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003885 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003886
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003887 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003888 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003889 if (mInterface->supportBatchRequest()) {
3890 submitRequestSuccess = sendRequestsBatch();
3891 } else {
3892 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003893 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07003894 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3895 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003896
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003897 if (useFlushLock) {
3898 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003899 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003900
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003901 // Unset as current request
3902 {
3903 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003904 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003905 }
3906
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003907 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003908}
3909
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003910status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003911 ATRACE_CALL();
3912
Shuzhen Wang4a472662017-02-26 23:29:04 -08003913 for (size_t i = 0; i < mNextRequests.size(); i++) {
3914 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003915 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3916 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3917 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3918
3919 // Prepare a request to HAL
3920 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3921
3922 // Insert any queued triggers (before metadata is locked)
3923 status_t res = insertTriggers(captureRequest);
3924
3925 if (res < 0) {
3926 SET_ERR("RequestThread: Unable to insert triggers "
3927 "(capture request %d, HAL device: %s (%d)",
3928 halRequest->frame_number, strerror(-res), res);
3929 return INVALID_OPERATION;
3930 }
3931 int triggerCount = res;
3932 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3933 mPrevTriggers = triggerCount;
3934
3935 // If the request is the same as last, or we had triggers last time
3936 if (mPrevRequest != captureRequest || triggersMixedIn) {
3937 /**
3938 * HAL workaround:
3939 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3940 */
3941 res = addDummyTriggerIds(captureRequest);
3942 if (res != OK) {
3943 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3944 "(capture request %d, HAL device: %s (%d)",
3945 halRequest->frame_number, strerror(-res), res);
3946 return INVALID_OPERATION;
3947 }
3948
3949 /**
3950 * The request should be presorted so accesses in HAL
3951 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3952 */
3953 captureRequest->mSettings.sort();
3954 halRequest->settings = captureRequest->mSettings.getAndLock();
3955 mPrevRequest = captureRequest;
3956 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3957
3958 IF_ALOGV() {
3959 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3960 find_camera_metadata_ro_entry(
3961 halRequest->settings,
3962 ANDROID_CONTROL_AF_TRIGGER,
3963 &e
3964 );
3965 if (e.count > 0) {
3966 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3967 __FUNCTION__,
3968 halRequest->frame_number,
3969 e.data.u8[0]);
3970 }
3971 }
3972 } else {
3973 // leave request.settings NULL to indicate 'reuse latest given'
3974 ALOGVV("%s: Request settings are REUSED",
3975 __FUNCTION__);
3976 }
3977
3978 uint32_t totalNumBuffers = 0;
3979
3980 // Fill in buffers
3981 if (captureRequest->mInputStream != NULL) {
3982 halRequest->input_buffer = &captureRequest->mInputBuffer;
3983 totalNumBuffers += 1;
3984 } else {
3985 halRequest->input_buffer = NULL;
3986 }
3987
3988 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3989 captureRequest->mOutputStreams.size());
3990 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08003991 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
3992 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003993
3994 // Prepare video buffers for high speed recording on the first video request.
3995 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3996 // Only try to prepare video stream on the first video request.
3997 mPrepareVideoStream = false;
3998
3999 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4000 while (res == NOT_ENOUGH_DATA) {
4001 res = outputStream->prepareNextBuffer();
4002 }
4003 if (res != OK) {
4004 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4005 __FUNCTION__, strerror(-res), res);
4006 outputStream->cancelPrepare();
4007 }
4008 }
4009
Shuzhen Wang4a472662017-02-26 23:29:04 -08004010 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4011 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004012 if (res != OK) {
4013 // Can't get output buffer from gralloc queue - this could be due to
4014 // abandoned queue or other consumer misbehavior, so not a fatal
4015 // error
4016 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4017 " %s (%d)", strerror(-res), res);
4018
4019 return TIMED_OUT;
4020 }
4021 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004022
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004023 }
4024 totalNumBuffers += halRequest->num_output_buffers;
4025
4026 // Log request in the in-flight queue
4027 sp<Camera3Device> parent = mParent.promote();
4028 if (parent == NULL) {
4029 // Should not happen, and nowhere to send errors to, so just log it
4030 CLOGE("RequestThread: Parent is gone");
4031 return INVALID_OPERATION;
4032 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004033
4034 // If this request list is for constrained high speed recording (not
4035 // preview), and the current request is not the last one in the batch,
4036 // do not send callback to the app.
4037 bool hasCallback = true;
4038 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4039 hasCallback = false;
4040 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004041 res = parent->registerInFlight(halRequest->frame_number,
4042 totalNumBuffers, captureRequest->mResultExtras,
4043 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004044 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004045 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4046 ", burstId = %" PRId32 ".",
4047 __FUNCTION__,
4048 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4049 captureRequest->mResultExtras.burstId);
4050 if (res != OK) {
4051 SET_ERR("RequestThread: Unable to register new in-flight request:"
4052 " %s (%d)", strerror(-res), res);
4053 return INVALID_OPERATION;
4054 }
4055 }
4056
4057 return OK;
4058}
4059
Igor Murashkin1e479c02013-09-06 16:55:14 -07004060CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4061 Mutex::Autolock al(mLatestRequestMutex);
4062
4063 ALOGV("RequestThread::%s", __FUNCTION__);
4064
4065 return mLatestRequest;
4066}
4067
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004068bool Camera3Device::RequestThread::isStreamPending(
4069 sp<Camera3StreamInterface>& stream) {
4070 Mutex::Autolock l(mRequestLock);
4071
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004073 if (!nextRequest.submitted) {
4074 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4075 if (stream == s) return true;
4076 }
4077 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004078 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004079 }
4080
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004081 for (const auto& request : mRequestQueue) {
4082 for (const auto& s : request->mOutputStreams) {
4083 if (stream == s) return true;
4084 }
4085 if (stream == request->mInputStream) return true;
4086 }
4087
4088 for (const auto& request : mRepeatingRequests) {
4089 for (const auto& s : request->mOutputStreams) {
4090 if (stream == s) return true;
4091 }
4092 if (stream == request->mInputStream) return true;
4093 }
4094
4095 return false;
4096}
Jianing Weicb0652e2014-03-12 18:29:36 -07004097
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004098void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4099 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 return;
4101 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004102
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004103 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004104 // Skip the ones that have been submitted successfully.
4105 if (nextRequest.submitted) {
4106 continue;
4107 }
4108
4109 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4110 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4111 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4112
4113 if (halRequest->settings != NULL) {
4114 captureRequest->mSettings.unlock(halRequest->settings);
4115 }
4116
4117 if (captureRequest->mInputStream != NULL) {
4118 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4119 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4120 }
4121
4122 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004123 //Buffers that failed processing could still have
4124 //valid acquire fence.
4125 int acquireFence = (*outputBuffers)[i].acquire_fence;
4126 if (0 <= acquireFence) {
4127 close(acquireFence);
4128 outputBuffers->editItemAt(i).acquire_fence = -1;
4129 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004130 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4131 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4132 }
4133
4134 if (sendRequestError) {
4135 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004136 sp<NotificationListener> listener = mListener.promote();
4137 if (listener != NULL) {
4138 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004139 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004140 captureRequest->mResultExtras);
4141 }
4142 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004143
4144 // Remove yet-to-be submitted inflight request from inflightMap
4145 {
4146 sp<Camera3Device> parent = mParent.promote();
4147 if (parent != NULL) {
4148 Mutex::Autolock l(parent->mInFlightLock);
4149 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4150 if (idx >= 0) {
4151 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4152 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4153 parent->removeInFlightMapEntryLocked(idx);
4154 }
4155 }
4156 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004158
4159 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004160 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004161}
4162
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004163void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 // Optimized a bit for the simple steady-state case (single repeating
4165 // request), to avoid putting that request in the queue temporarily.
4166 Mutex::Autolock l(mRequestLock);
4167
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004168 assert(mNextRequests.empty());
4169
4170 NextRequest nextRequest;
4171 nextRequest.captureRequest = waitForNextRequestLocked();
4172 if (nextRequest.captureRequest == nullptr) {
4173 return;
4174 }
4175
4176 nextRequest.halRequest = camera3_capture_request_t();
4177 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004178 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004179
4180 // Wait for additional requests
4181 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4182
4183 for (size_t i = 1; i < batchSize; i++) {
4184 NextRequest additionalRequest;
4185 additionalRequest.captureRequest = waitForNextRequestLocked();
4186 if (additionalRequest.captureRequest == nullptr) {
4187 break;
4188 }
4189
4190 additionalRequest.halRequest = camera3_capture_request_t();
4191 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004192 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004193 }
4194
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004195 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004196 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004197 mNextRequests.size(), batchSize);
4198 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004199 }
4200
4201 return;
4202}
4203
4204sp<Camera3Device::CaptureRequest>
4205 Camera3Device::RequestThread::waitForNextRequestLocked() {
4206 status_t res;
4207 sp<CaptureRequest> nextRequest;
4208
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004209 while (mRequestQueue.empty()) {
4210 if (!mRepeatingRequests.empty()) {
4211 // Always atomically enqueue all requests in a repeating request
4212 // list. Guarantees a complete in-sequence set of captures to
4213 // application.
4214 const RequestList &requests = mRepeatingRequests;
4215 RequestList::const_iterator firstRequest =
4216 requests.begin();
4217 nextRequest = *firstRequest;
4218 mRequestQueue.insert(mRequestQueue.end(),
4219 ++firstRequest,
4220 requests.end());
4221 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004222
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004223 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004224
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004225 break;
4226 }
4227
4228 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004230 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4231 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004232 Mutex::Autolock pl(mPauseLock);
4233 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004234 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004235 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004236 // Let the tracker know
4237 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4238 if (statusTracker != 0) {
4239 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4240 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004241 }
4242 // Stop waiting for now and let thread management happen
4243 return NULL;
4244 }
4245 }
4246
4247 if (nextRequest == NULL) {
4248 // Don't have a repeating request already in hand, so queue
4249 // must have an entry now.
4250 RequestList::iterator firstRequest =
4251 mRequestQueue.begin();
4252 nextRequest = *firstRequest;
4253 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004254 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4255 sp<NotificationListener> listener = mListener.promote();
4256 if (listener != NULL) {
4257 listener->notifyRequestQueueEmpty();
4258 }
4259 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 }
4261
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004262 // In case we've been unpaused by setPaused clearing mDoPause, need to
4263 // update internal pause state (capture/setRepeatingRequest unpause
4264 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004265 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004266 if (mPaused) {
4267 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4268 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4269 if (statusTracker != 0) {
4270 statusTracker->markComponentActive(mStatusId);
4271 }
4272 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004273 mPaused = false;
4274
4275 // Check if we've reconfigured since last time, and reset the preview
4276 // request if so. Can't use 'NULL request == repeat' across configure calls.
4277 if (mReconfigured) {
4278 mPrevRequest.clear();
4279 mReconfigured = false;
4280 }
4281
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004282 if (nextRequest != NULL) {
4283 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004284 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4285 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004286
4287 // Since RequestThread::clear() removes buffers from the input stream,
4288 // get the right buffer here before unlocking mRequestLock
4289 if (nextRequest->mInputStream != NULL) {
4290 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4291 if (res != OK) {
4292 // Can't get input buffer from gralloc queue - this could be due to
4293 // disconnected queue or other producer misbehavior, so not a fatal
4294 // error
4295 ALOGE("%s: Can't get input buffer, skipping request:"
4296 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004297
4298 sp<NotificationListener> listener = mListener.promote();
4299 if (listener != NULL) {
4300 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004301 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004302 nextRequest->mResultExtras);
4303 }
4304 return NULL;
4305 }
4306 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004307 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004308
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 return nextRequest;
4310}
4311
4312bool Camera3Device::RequestThread::waitIfPaused() {
4313 status_t res;
4314 Mutex::Autolock l(mPauseLock);
4315 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004316 if (mPaused == false) {
4317 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004318 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4319 // Let the tracker know
4320 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4321 if (statusTracker != 0) {
4322 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4323 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004324 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004325
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004326 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004327 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004328 return true;
4329 }
4330 }
4331 // We don't set mPaused to false here, because waitForNextRequest needs
4332 // to further manage the paused state in case of starvation.
4333 return false;
4334}
4335
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004336void Camera3Device::RequestThread::unpauseForNewRequests() {
4337 // With work to do, mark thread as unpaused.
4338 // If paused by request (setPaused), don't resume, to avoid
4339 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004340 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004341 Mutex::Autolock p(mPauseLock);
4342 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004343 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4344 if (mPaused) {
4345 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4346 if (statusTracker != 0) {
4347 statusTracker->markComponentActive(mStatusId);
4348 }
4349 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004350 mPaused = false;
4351 }
4352}
4353
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004354void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4355 sp<Camera3Device> parent = mParent.promote();
4356 if (parent != NULL) {
4357 va_list args;
4358 va_start(args, fmt);
4359
4360 parent->setErrorStateV(fmt, args);
4361
4362 va_end(args);
4363 }
4364}
4365
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004366status_t Camera3Device::RequestThread::insertTriggers(
4367 const sp<CaptureRequest> &request) {
4368
4369 Mutex::Autolock al(mTriggerMutex);
4370
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004371 sp<Camera3Device> parent = mParent.promote();
4372 if (parent == NULL) {
4373 CLOGE("RequestThread: Parent is gone");
4374 return DEAD_OBJECT;
4375 }
4376
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004377 CameraMetadata &metadata = request->mSettings;
4378 size_t count = mTriggerMap.size();
4379
4380 for (size_t i = 0; i < count; ++i) {
4381 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004382 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004383
4384 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4385 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4386 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004387 if (isAeTrigger) {
4388 request->mResultExtras.precaptureTriggerId = triggerId;
4389 mCurrentPreCaptureTriggerId = triggerId;
4390 } else {
4391 request->mResultExtras.afTriggerId = triggerId;
4392 mCurrentAfTriggerId = triggerId;
4393 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004394 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004395 }
4396
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004397 camera_metadata_entry entry = metadata.find(tag);
4398
4399 if (entry.count > 0) {
4400 /**
4401 * Already has an entry for this trigger in the request.
4402 * Rewrite it with our requested trigger value.
4403 */
4404 RequestTrigger oldTrigger = trigger;
4405
4406 oldTrigger.entryValue = entry.data.u8[0];
4407
4408 mTriggerReplacedMap.add(tag, oldTrigger);
4409 } else {
4410 /**
4411 * More typical, no trigger entry, so we just add it
4412 */
4413 mTriggerRemovedMap.add(tag, trigger);
4414 }
4415
4416 status_t res;
4417
4418 switch (trigger.getTagType()) {
4419 case TYPE_BYTE: {
4420 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4421 res = metadata.update(tag,
4422 &entryValue,
4423 /*count*/1);
4424 break;
4425 }
4426 case TYPE_INT32:
4427 res = metadata.update(tag,
4428 &trigger.entryValue,
4429 /*count*/1);
4430 break;
4431 default:
4432 ALOGE("%s: Type not supported: 0x%x",
4433 __FUNCTION__,
4434 trigger.getTagType());
4435 return INVALID_OPERATION;
4436 }
4437
4438 if (res != OK) {
4439 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4440 ", value %d", __FUNCTION__, trigger.getTagName(),
4441 trigger.entryValue);
4442 return res;
4443 }
4444
4445 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4446 trigger.getTagName(),
4447 trigger.entryValue);
4448 }
4449
4450 mTriggerMap.clear();
4451
4452 return count;
4453}
4454
4455status_t Camera3Device::RequestThread::removeTriggers(
4456 const sp<CaptureRequest> &request) {
4457 Mutex::Autolock al(mTriggerMutex);
4458
4459 CameraMetadata &metadata = request->mSettings;
4460
4461 /**
4462 * Replace all old entries with their old values.
4463 */
4464 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4465 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4466
4467 status_t res;
4468
4469 uint32_t tag = trigger.metadataTag;
4470 switch (trigger.getTagType()) {
4471 case TYPE_BYTE: {
4472 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4473 res = metadata.update(tag,
4474 &entryValue,
4475 /*count*/1);
4476 break;
4477 }
4478 case TYPE_INT32:
4479 res = metadata.update(tag,
4480 &trigger.entryValue,
4481 /*count*/1);
4482 break;
4483 default:
4484 ALOGE("%s: Type not supported: 0x%x",
4485 __FUNCTION__,
4486 trigger.getTagType());
4487 return INVALID_OPERATION;
4488 }
4489
4490 if (res != OK) {
4491 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4492 ", trigger value %d", __FUNCTION__,
4493 trigger.getTagName(), trigger.entryValue);
4494 return res;
4495 }
4496 }
4497 mTriggerReplacedMap.clear();
4498
4499 /**
4500 * Remove all new entries.
4501 */
4502 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4503 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4504 status_t res = metadata.erase(trigger.metadataTag);
4505
4506 if (res != OK) {
4507 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4508 ", trigger value %d", __FUNCTION__,
4509 trigger.getTagName(), trigger.entryValue);
4510 return res;
4511 }
4512 }
4513 mTriggerRemovedMap.clear();
4514
4515 return OK;
4516}
4517
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004518status_t Camera3Device::RequestThread::addDummyTriggerIds(
4519 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004520 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004521 static const int32_t dummyTriggerId = 1;
4522 status_t res;
4523
4524 CameraMetadata &metadata = request->mSettings;
4525
4526 // If AF trigger is active, insert a dummy AF trigger ID if none already
4527 // exists
4528 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4529 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4530 if (afTrigger.count > 0 &&
4531 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4532 afId.count == 0) {
4533 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4534 if (res != OK) return res;
4535 }
4536
4537 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4538 // if none already exists
4539 camera_metadata_entry pcTrigger =
4540 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4541 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4542 if (pcTrigger.count > 0 &&
4543 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4544 pcId.count == 0) {
4545 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4546 &dummyTriggerId, 1);
4547 if (res != OK) return res;
4548 }
4549
4550 return OK;
4551}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004552
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004553/**
4554 * PreparerThread inner class methods
4555 */
4556
4557Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004558 Thread(/*canCallJava*/false), mListener(nullptr),
4559 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004560}
4561
4562Camera3Device::PreparerThread::~PreparerThread() {
4563 Thread::requestExitAndWait();
4564 if (mCurrentStream != nullptr) {
4565 mCurrentStream->cancelPrepare();
4566 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4567 mCurrentStream.clear();
4568 }
4569 clear();
4570}
4571
Ruben Brunkc78ac262015-08-13 17:58:46 -07004572status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004573 status_t res;
4574
4575 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004576 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004577
Ruben Brunkc78ac262015-08-13 17:58:46 -07004578 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004579 if (res == OK) {
4580 // No preparation needed, fire listener right off
4581 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004582 if (listener != NULL) {
4583 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004584 }
4585 return OK;
4586 } else if (res != NOT_ENOUGH_DATA) {
4587 return res;
4588 }
4589
4590 // Need to prepare, start up thread if necessary
4591 if (!mActive) {
4592 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4593 // isn't running
4594 Thread::requestExitAndWait();
4595 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4596 if (res != OK) {
4597 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004598 if (listener != NULL) {
4599 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004600 }
4601 return res;
4602 }
4603 mCancelNow = false;
4604 mActive = true;
4605 ALOGV("%s: Preparer stream started", __FUNCTION__);
4606 }
4607
4608 // queue up the work
4609 mPendingStreams.push_back(stream);
4610 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4611
4612 return OK;
4613}
4614
4615status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004616 Mutex::Autolock l(mLock);
4617
4618 for (const auto& stream : mPendingStreams) {
4619 stream->cancelPrepare();
4620 }
4621 mPendingStreams.clear();
4622 mCancelNow = true;
4623
4624 return OK;
4625}
4626
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004627void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004628 Mutex::Autolock l(mLock);
4629 mListener = listener;
4630}
4631
4632bool Camera3Device::PreparerThread::threadLoop() {
4633 status_t res;
4634 {
4635 Mutex::Autolock l(mLock);
4636 if (mCurrentStream == nullptr) {
4637 // End thread if done with work
4638 if (mPendingStreams.empty()) {
4639 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4640 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4641 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4642 mActive = false;
4643 return false;
4644 }
4645
4646 // Get next stream to prepare
4647 auto it = mPendingStreams.begin();
4648 mCurrentStream = *it;
4649 mPendingStreams.erase(it);
4650 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4651 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4652 } else if (mCancelNow) {
4653 mCurrentStream->cancelPrepare();
4654 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4655 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4656 mCurrentStream.clear();
4657 mCancelNow = false;
4658 return true;
4659 }
4660 }
4661
4662 res = mCurrentStream->prepareNextBuffer();
4663 if (res == NOT_ENOUGH_DATA) return true;
4664 if (res != OK) {
4665 // Something bad happened; try to recover by cancelling prepare and
4666 // signalling listener anyway
4667 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4668 mCurrentStream->getId(), res, strerror(-res));
4669 mCurrentStream->cancelPrepare();
4670 }
4671
4672 // This stream has finished, notify listener
4673 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004674 sp<NotificationListener> listener = mListener.promote();
4675 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004676 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4677 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004678 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004679 }
4680
4681 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4682 mCurrentStream.clear();
4683
4684 return true;
4685}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004686
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004687/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004688 * Static callback forwarding methods from HAL to instance
4689 */
4690
4691void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4692 const camera3_capture_result *result) {
4693 Camera3Device *d =
4694 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004695
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004696 d->processCaptureResult(result);
4697}
4698
4699void Camera3Device::sNotify(const camera3_callback_ops *cb,
4700 const camera3_notify_msg *msg) {
4701 Camera3Device *d =
4702 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4703 d->notify(msg);
4704}
4705
4706}; // namespace android