blob: d6ed3ffa8b05922ce535d998b8738cabf18f9cf2 [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
Igor Murashkin1e479c02013-09-06 16:55:14 -0700616 {
617 lines = String8(" Last request sent:\n");
618 write(fd, lines.string(), lines.size());
619
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700620 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700621 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
622 }
623
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 if (dumpTemplates) {
625 const char *templateNames[] = {
626 "TEMPLATE_PREVIEW",
627 "TEMPLATE_STILL_CAPTURE",
628 "TEMPLATE_VIDEO_RECORD",
629 "TEMPLATE_VIDEO_SNAPSHOT",
630 "TEMPLATE_ZERO_SHUTTER_LAG",
631 "TEMPLATE_MANUAL"
632 };
633
634 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 camera_metadata_t *templateRequest = nullptr;
636 mInterface->constructDefaultRequestSettings(
637 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800640 lines.append(" Not supported\n");
641 write(fd, lines.string(), lines.size());
642 } else {
643 write(fd, lines.string(), lines.size());
644 dump_indented_camera_metadata(templateRequest,
645 fd, /*verbosity*/2, /*indentation*/8);
646 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800648 }
649 }
650
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700651 mTagMonitor.dumpMonitoredMetadata(fd);
652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800653 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800654 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800656 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800658
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700659 if (gotLock) mLock.unlock();
660 if (gotInterfaceLock) mInterfaceLock.unlock();
661
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800662 return OK;
663}
664
665const CameraMetadata& Camera3Device::info() const {
666 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800667 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
668 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700669 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800670 mStatus == STATUS_ERROR ?
671 "when in error state" : "before init");
672 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800673 return mDeviceInfo;
674}
675
Jianing Wei90e59c92014-03-12 18:29:36 -0700676status_t Camera3Device::checkStatusOkToCaptureLocked() {
677 switch (mStatus) {
678 case STATUS_ERROR:
679 CLOGE("Device has encountered a serious error");
680 return INVALID_OPERATION;
681 case STATUS_UNINITIALIZED:
682 CLOGE("Device not initialized");
683 return INVALID_OPERATION;
684 case STATUS_UNCONFIGURED:
685 case STATUS_CONFIGURED:
686 case STATUS_ACTIVE:
687 // OK
688 break;
689 default:
690 SET_ERR_L("Unexpected status: %d", mStatus);
691 return INVALID_OPERATION;
692 }
693 return OK;
694}
695
696status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700697 const List<const CameraMetadata> &metadataList,
698 const std::list<const SurfaceMap> &surfaceMaps,
699 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700700 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700701 if (requestList == NULL) {
702 CLOGE("requestList cannot be NULL.");
703 return BAD_VALUE;
704 }
705
Jianing Weicb0652e2014-03-12 18:29:36 -0700706 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700707 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
708 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
709 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
710 ++metadataIt, ++surfaceMapIt) {
711 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700712 if (newRequest == 0) {
713 CLOGE("Can't create capture request");
714 return BAD_VALUE;
715 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700716
Shuzhen Wang9d066012016-09-30 11:30:20 -0700717 newRequest->mRepeating = repeating;
718
Jianing Weicb0652e2014-03-12 18:29:36 -0700719 // Setup burst Id and request Id
720 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700721 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
722 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700723 CLOGE("RequestID entry exists; but must not be empty in metadata");
724 return BAD_VALUE;
725 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700726 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700727 } else {
728 CLOGE("RequestID does not exist in metadata");
729 return BAD_VALUE;
730 }
731
Jianing Wei90e59c92014-03-12 18:29:36 -0700732 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700733
734 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700735 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700736 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
737 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
738 return BAD_VALUE;
739 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700740
741 // Setup batch size if this is a high speed video recording request.
742 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
743 auto firstRequest = requestList->begin();
744 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
745 if (outputStream->isVideoStream()) {
746 (*firstRequest)->mBatchSize = requestList->size();
747 break;
748 }
749 }
750 }
751
Jianing Wei90e59c92014-03-12 18:29:36 -0700752 return OK;
753}
754
Jianing Weicb0652e2014-03-12 18:29:36 -0700755status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800756 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700758 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700759 std::list<const SurfaceMap> surfaceMaps;
760 convertToRequestList(requests, surfaceMaps, request);
761
762 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
763}
764
765void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
766 std::list<const SurfaceMap>& surfaceMaps,
767 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700768 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700769
770 SurfaceMap surfaceMap;
771 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
772 // With no surface list passed in, stream and surface will have 1-to-1
773 // mapping. So the surface index is 0 for each stream in the surfaceMap.
774 for (size_t i = 0; i < streams.count; i++) {
775 surfaceMap[streams.data.i32[i]].push_back(0);
776 }
777 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800778}
779
Jianing Wei90e59c92014-03-12 18:29:36 -0700780status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700781 const List<const CameraMetadata> &requests,
782 const std::list<const SurfaceMap> &surfaceMaps,
783 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700784 /*out*/
785 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700786 ATRACE_CALL();
787 Mutex::Autolock il(mInterfaceLock);
788 Mutex::Autolock l(mLock);
789
790 status_t res = checkStatusOkToCaptureLocked();
791 if (res != OK) {
792 // error logged by previous call
793 return res;
794 }
795
796 RequestList requestList;
797
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
799 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700800 if (res != OK) {
801 // error logged by previous call
802 return res;
803 }
804
805 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700806 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700807 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700808 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700809 }
810
811 if (res == OK) {
812 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
813 if (res != OK) {
814 SET_ERR_L("Can't transition to active in %f seconds!",
815 kActiveTimeout/1e9);
816 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800817 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700818 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700819 } else {
820 CLOGE("Cannot queue request. Impossible.");
821 return BAD_VALUE;
822 }
823
824 return res;
825}
826
Yifan Honga640c5a2017-04-12 16:30:31 -0700827// Only one processCaptureResult should be called at a time, so
828// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800829hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800830 const hardware::hidl_vec<
831 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700832
833 if (mProcessCaptureResultLock.tryLock() != OK) {
834 // This should never happen; it indicates a wrong client implementation
835 // that doesn't follow the contract. But, we can be tolerant here.
836 ALOGE("%s: callback overlapped! waiting 1s...",
837 __FUNCTION__);
838 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
839 ALOGE("%s: cannot acquire lock in 1s, dropping results",
840 __FUNCTION__);
841 // really don't know what to do, so bail out.
842 return hardware::Void();
843 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800844 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700845 for (const auto& result : results) {
846 processOneCaptureResultLocked(result);
847 }
848 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800849 return hardware::Void();
850}
851
Yifan Honga640c5a2017-04-12 16:30:31 -0700852void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800853 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800854 camera3_capture_result r;
855 status_t res;
856 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700857
858 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
859 if (result.fmqResultSize > 0) {
860 resultMetadata.resize(result.fmqResultSize);
861 if (mResultMetadataQueue == nullptr) {
862 return; // logged in initialize()
863 }
864 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
865 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
866 __FUNCTION__, result.frameNumber, result.fmqResultSize);
867 return;
868 }
869 } else {
870 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
871 result.result.size());
872 }
873
874 if (resultMetadata.size() != 0) {
875 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
876 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800877 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
878 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
879 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800880 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800881 }
882 } else {
883 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800884 }
885
886 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
887 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
888 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
889 auto& bDst = outputBuffers[i];
890 const StreamBuffer &bSrc = result.outputBuffers[i];
891
892 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100893 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
895 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800896 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800897 }
898 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
899
900 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800901 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800902 if (res != OK) {
903 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
904 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800905 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800906 }
907 bDst.buffer = buffer;
908 bDst.status = mapHidlBufferStatus(bSrc.status);
909 bDst.acquire_fence = -1;
910 if (bSrc.releaseFence == nullptr) {
911 bDst.release_fence = -1;
912 } else if (bSrc.releaseFence->numFds == 1) {
913 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
914 } else {
915 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
916 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800917 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 }
919 }
920 r.num_output_buffers = outputBuffers.size();
921 r.output_buffers = outputBuffers.data();
922
923 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800924 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800925 r.input_buffer = nullptr;
926 } else {
927 if (mInputStream->getId() != result.inputBuffer.streamId) {
928 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
929 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800930 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 }
932 inputBuffer.stream = mInputStream->asHalStream();
933 buffer_handle_t *buffer;
934 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
935 &buffer);
936 if (res != OK) {
937 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
938 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800939 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 }
941 inputBuffer.buffer = buffer;
942 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
943 inputBuffer.acquire_fence = -1;
944 if (result.inputBuffer.releaseFence == nullptr) {
945 inputBuffer.release_fence = -1;
946 } else if (result.inputBuffer.releaseFence->numFds == 1) {
947 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
948 } else {
949 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
950 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800951 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 }
953 r.input_buffer = &inputBuffer;
954 }
955
956 r.partial_result = result.partialResult;
957
958 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800959}
960
961hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800962 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
963 for (const auto& msg : msgs) {
964 notify(msg);
965 }
966 return hardware::Void();
967}
968
969void Camera3Device::notify(
970 const hardware::camera::device::V3_2::NotifyMsg& msg) {
971
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800972 camera3_notify_msg m;
973 switch (msg.type) {
974 case MsgType::ERROR:
975 m.type = CAMERA3_MSG_ERROR;
976 m.message.error.frame_number = msg.msg.error.frameNumber;
977 if (msg.msg.error.errorStreamId >= 0) {
978 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100979 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800980 ALOGE("%s: Frame %d: Invalid error stream id %d",
981 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800982 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800983 }
984 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
985 } else {
986 m.message.error.error_stream = nullptr;
987 }
988 switch (msg.msg.error.errorCode) {
989 case ErrorCode::ERROR_DEVICE:
990 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
991 break;
992 case ErrorCode::ERROR_REQUEST:
993 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
994 break;
995 case ErrorCode::ERROR_RESULT:
996 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
997 break;
998 case ErrorCode::ERROR_BUFFER:
999 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1000 break;
1001 }
1002 break;
1003 case MsgType::SHUTTER:
1004 m.type = CAMERA3_MSG_SHUTTER;
1005 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1006 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1007 break;
1008 }
1009 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001010}
1011
Jianing Weicb0652e2014-03-12 18:29:36 -07001012status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001013 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001014 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001015 ATRACE_CALL();
1016
Shuzhen Wang0129d522016-10-30 22:43:41 -07001017 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001018}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001019
Jianing Weicb0652e2014-03-12 18:29:36 -07001020status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1021 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001022 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001023
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001024 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001025 std::list<const SurfaceMap> surfaceMaps;
1026 convertToRequestList(requests, surfaceMaps, request);
1027
1028 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1029 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001030}
1031
Jianing Weicb0652e2014-03-12 18:29:36 -07001032status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001033 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001034 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001035 ATRACE_CALL();
1036
Shuzhen Wang0129d522016-10-30 22:43:41 -07001037 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001038}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001039
1040sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001041 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001042 status_t res;
1043
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001044 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001045 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1046 // so unilaterally select normal operating mode.
1047 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001048 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001049 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001050 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001052 } else if (mStatus == STATUS_UNCONFIGURED) {
1053 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001054 CLOGE("No streams configured");
1055 return NULL;
1056 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001057 }
1058
Shuzhen Wang0129d522016-10-30 22:43:41 -07001059 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001061}
1062
Jianing Weicb0652e2014-03-12 18:29:36 -07001063status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001064 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001065 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001067
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001068 switch (mStatus) {
1069 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001070 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 return INVALID_OPERATION;
1072 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001073 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001075 case STATUS_UNCONFIGURED:
1076 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 case STATUS_ACTIVE:
1078 // OK
1079 break;
1080 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001081 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001082 return INVALID_OPERATION;
1083 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001084 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001086 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001087}
1088
1089status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1090 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001091 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001092
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001093 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001094}
1095
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001096status_t Camera3Device::createInputStream(
1097 uint32_t width, uint32_t height, int format, int *id) {
1098 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001099 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001100 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001101 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1102 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001103
1104 status_t res;
1105 bool wasActive = false;
1106
1107 switch (mStatus) {
1108 case STATUS_ERROR:
1109 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1110 return INVALID_OPERATION;
1111 case STATUS_UNINITIALIZED:
1112 ALOGE("%s: Device not initialized", __FUNCTION__);
1113 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001114 case STATUS_UNCONFIGURED:
1115 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001116 // OK
1117 break;
1118 case STATUS_ACTIVE:
1119 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001120 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001121 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001122 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001123 return res;
1124 }
1125 wasActive = true;
1126 break;
1127 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001128 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001129 return INVALID_OPERATION;
1130 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001131 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001132
1133 if (mInputStream != 0) {
1134 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1135 return INVALID_OPERATION;
1136 }
1137
1138 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1139 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001140 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001141
1142 mInputStream = newStream;
1143
1144 *id = mNextStreamId++;
1145
1146 // Continue captures if active at start
1147 if (wasActive) {
1148 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001149 // Reuse current operating mode for new stream config
1150 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001151 if (res != OK) {
1152 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1153 __FUNCTION__, mNextStreamId, strerror(-res), res);
1154 return res;
1155 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001156 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001157 }
1158
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001159 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001160 return OK;
1161}
1162
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001163status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001164 uint32_t width, uint32_t height, int format,
1165 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001166 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001167 ATRACE_CALL();
1168
1169 if (consumer == nullptr) {
1170 ALOGE("%s: consumer must not be null", __FUNCTION__);
1171 return BAD_VALUE;
1172 }
1173
1174 std::vector<sp<Surface>> consumers;
1175 consumers.push_back(consumer);
1176
1177 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001178 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001179}
1180
1181status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1182 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1183 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001184 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001185 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001186 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001188 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001189 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1190 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001191
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 status_t res;
1193 bool wasActive = false;
1194
1195 switch (mStatus) {
1196 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001197 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 return INVALID_OPERATION;
1199 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 case STATUS_UNCONFIGURED:
1203 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 // OK
1205 break;
1206 case STATUS_ACTIVE:
1207 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001208 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 return res;
1212 }
1213 wasActive = true;
1214 break;
1215 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001219 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220
1221 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001222
Shuzhen Wang0129d522016-10-30 22:43:41 -07001223 if (consumers.size() == 0 && !hasDeferredConsumer) {
1224 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1225 return BAD_VALUE;
1226 }
Zhijun He5d677d12016-05-29 16:52:39 -07001227
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001229 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1230 return BAD_VALUE;
1231 }
1232
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001234 ssize_t blobBufferSize;
1235 if (dataSpace != HAL_DATASPACE_DEPTH) {
1236 blobBufferSize = getJpegBufferSize(width, height);
1237 if (blobBufferSize <= 0) {
1238 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1239 return BAD_VALUE;
1240 }
1241 } else {
1242 blobBufferSize = getPointCloudBufferSize();
1243 if (blobBufferSize <= 0) {
1244 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1245 return BAD_VALUE;
1246 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001247 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001248 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001249 width, height, blobBufferSize, format, dataSpace, rotation,
1250 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001251 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1252 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1253 if (rawOpaqueBufferSize <= 0) {
1254 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1255 return BAD_VALUE;
1256 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001257 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001258 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1259 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001260 } else if (isShared) {
1261 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1262 width, height, format, consumerUsage, dataSpace, rotation,
1263 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001264 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001265 newStream = new Camera3OutputStream(mNextStreamId,
1266 width, height, format, consumerUsage, dataSpace, rotation,
1267 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001269 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001270 width, height, format, dataSpace, rotation,
1271 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001273 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274
Emilian Peev08dd2452017-04-06 16:55:14 +01001275 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001276
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 res = mOutputStreams.add(mNextStreamId, newStream);
1278 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001279 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 return res;
1281 }
1282
1283 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001284 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285
1286 // Continue captures if active at start
1287 if (wasActive) {
1288 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001289 // Reuse current operating mode for new stream config
1290 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001292 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1293 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 return res;
1295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001296 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001298 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001300}
1301
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001302status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001303 uint32_t *width, uint32_t *height,
1304 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001305 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001307 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001308
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 switch (mStatus) {
1310 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001311 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312 return INVALID_OPERATION;
1313 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001314 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001315 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 case STATUS_UNCONFIGURED:
1317 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 case STATUS_ACTIVE:
1319 // OK
1320 break;
1321 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001322 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001323 return INVALID_OPERATION;
1324 }
1325
1326 ssize_t idx = mOutputStreams.indexOfKey(id);
1327 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001328 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329 return idx;
1330 }
1331
1332 if (width) *width = mOutputStreams[idx]->getWidth();
1333 if (height) *height = mOutputStreams[idx]->getHeight();
1334 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001335 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001336 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001337}
1338
1339status_t Camera3Device::setStreamTransform(int id,
1340 int transform) {
1341 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001342 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 switch (mStatus) {
1346 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001347 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 return INVALID_OPERATION;
1349 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001350 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001352 case STATUS_UNCONFIGURED:
1353 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 case STATUS_ACTIVE:
1355 // OK
1356 break;
1357 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001358 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 return INVALID_OPERATION;
1360 }
1361
1362 ssize_t idx = mOutputStreams.indexOfKey(id);
1363 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001364 CLOGE("Stream %d does not exist",
1365 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 return BAD_VALUE;
1367 }
1368
1369 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001370}
1371
1372status_t Camera3Device::deleteStream(int id) {
1373 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001374 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 Mutex::Autolock l(mLock);
1376 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001378 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 // CameraDevice semantics require device to already be idle before
1381 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001382 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001383 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001384 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 }
1386
Igor Murashkin2fba5842013-04-22 14:03:54 -07001387 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001388 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 if (mInputStream != NULL && id == mInputStream->getId()) {
1390 deletedStream = mInputStream;
1391 mInputStream.clear();
1392 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001393 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001394 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 return BAD_VALUE;
1396 }
Zhijun He5f446352014-01-22 09:49:33 -08001397 }
1398
1399 // Delete output stream or the output part of a bi-directional stream.
1400 if (outputStreamIdx != NAME_NOT_FOUND) {
1401 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 mOutputStreams.removeItem(id);
1403 }
1404
1405 // Free up the stream endpoint so that it can be used by some other stream
1406 res = deletedStream->disconnect();
1407 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001408 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001409 // fall through since we want to still list the stream as deleted.
1410 }
1411 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001412 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413
1414 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001415}
1416
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001417status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001418 ATRACE_CALL();
1419 ALOGV("%s: E", __FUNCTION__);
1420
1421 Mutex::Autolock il(mInterfaceLock);
1422 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001423
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001424 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001425}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001426
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001427status_t Camera3Device::getInputBufferProducer(
1428 sp<IGraphicBufferProducer> *producer) {
1429 Mutex::Autolock il(mInterfaceLock);
1430 Mutex::Autolock l(mLock);
1431
1432 if (producer == NULL) {
1433 return BAD_VALUE;
1434 } else if (mInputStream == NULL) {
1435 return INVALID_OPERATION;
1436 }
1437
1438 return mInputStream->getInputBufferProducer(producer);
1439}
1440
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001441status_t Camera3Device::createDefaultRequest(int templateId,
1442 CameraMetadata *request) {
1443 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001444 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001445
1446 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1447 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1448 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1449 return BAD_VALUE;
1450 }
1451
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001452 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 Mutex::Autolock l(mLock);
1454
1455 switch (mStatus) {
1456 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001457 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 return INVALID_OPERATION;
1459 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001460 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001462 case STATUS_UNCONFIGURED:
1463 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 case STATUS_ACTIVE:
1465 // OK
1466 break;
1467 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001468 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return INVALID_OPERATION;
1470 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471
Zhijun Hea1530f12014-09-14 12:44:20 -07001472 if (!mRequestTemplateCache[templateId].isEmpty()) {
1473 *request = mRequestTemplateCache[templateId];
1474 return OK;
1475 }
1476
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001477 camera_metadata_t *rawRequest;
1478 status_t res = mInterface->constructDefaultRequestSettings(
1479 (camera3_request_template_t) templateId, &rawRequest);
1480 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001481 ALOGI("%s: template %d is not supported on this camera device",
1482 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001483 return res;
1484 } else if (res != OK) {
1485 CLOGE("Unable to construct request template %d: %s (%d)",
1486 templateId, strerror(-res), res);
1487 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001488 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001489
Emilian Peev71c73a22017-03-21 16:35:51 +00001490 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001491 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001492
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001493 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494 return OK;
1495}
1496
1497status_t Camera3Device::waitUntilDrained() {
1498 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001501
Zhijun He69a37482014-03-23 18:44:49 -07001502 return waitUntilDrainedLocked();
1503}
1504
1505status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 switch (mStatus) {
1507 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001508 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 ALOGV("%s: Already idle", __FUNCTION__);
1510 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 case STATUS_CONFIGURED:
1512 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 case STATUS_ERROR:
1514 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 break;
1517 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001518 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return INVALID_OPERATION;
1520 }
1521
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001522 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001524 if (res != OK) {
1525 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1526 res);
1527 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 return res;
1529}
1530
Ruben Brunk183f0562015-08-12 12:55:02 -07001531
1532void Camera3Device::internalUpdateStatusLocked(Status status) {
1533 mStatus = status;
1534 mRecentStatusUpdates.add(mStatus);
1535 mStatusChanged.broadcast();
1536}
1537
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001538// Pause to reconfigure
1539status_t Camera3Device::internalPauseAndWaitLocked() {
1540 mRequestThread->setPaused(true);
1541 mPauseStateNotify = true;
1542
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001543 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1545 if (res != OK) {
1546 SET_ERR_L("Can't idle device in %f seconds!",
1547 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 }
1549
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 return res;
1551}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553// Resume after internalPauseAndWaitLocked
1554status_t Camera3Device::internalResumeLocked() {
1555 status_t res;
1556
1557 mRequestThread->setPaused(false);
1558
1559 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1560 if (res != OK) {
1561 SET_ERR_L("Can't transition to active in %f seconds!",
1562 kActiveTimeout/1e9);
1563 }
1564 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001566}
1567
Ruben Brunk183f0562015-08-12 12:55:02 -07001568status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001570
1571 size_t startIndex = 0;
1572 if (mStatusWaiters == 0) {
1573 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1574 // this status list
1575 mRecentStatusUpdates.clear();
1576 } else {
1577 // If other threads are waiting on updates to this status list, set the position of the
1578 // first element that this list will check rather than clearing the list.
1579 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001580 }
1581
Ruben Brunk183f0562015-08-12 12:55:02 -07001582 mStatusWaiters++;
1583
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 bool stateSeen = false;
1585 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001586 if (active == (mStatus == STATUS_ACTIVE)) {
1587 // Desired state is current
1588 break;
1589 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590
1591 res = mStatusChanged.waitRelative(mLock, timeout);
1592 if (res != OK) break;
1593
Ruben Brunk183f0562015-08-12 12:55:02 -07001594 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1595 // transitions.
1596 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1597 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1598 __FUNCTION__);
1599
1600 // Encountered desired state since we began waiting
1601 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1603 stateSeen = true;
1604 break;
1605 }
1606 }
1607 } while (!stateSeen);
1608
Ruben Brunk183f0562015-08-12 12:55:02 -07001609 mStatusWaiters--;
1610
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001611 return res;
1612}
1613
1614
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001615status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001617 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001619 if (listener != NULL && mListener != NULL) {
1620 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1621 }
1622 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001623 mRequestThread->setNotificationListener(listener);
1624 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001625
1626 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001627}
1628
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001629bool Camera3Device::willNotify3A() {
1630 return false;
1631}
1632
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001633status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001634 status_t res;
1635 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001636
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001637 while (mResultQueue.empty()) {
1638 res = mResultSignal.waitRelative(mOutputLock, timeout);
1639 if (res == TIMED_OUT) {
1640 return res;
1641 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001642 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1643 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001644 return res;
1645 }
1646 }
1647 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648}
1649
Jianing Weicb0652e2014-03-12 18:29:36 -07001650status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001652 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001654 if (mResultQueue.empty()) {
1655 return NOT_ENOUGH_DATA;
1656 }
1657
Jianing Weicb0652e2014-03-12 18:29:36 -07001658 if (frame == NULL) {
1659 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1660 return BAD_VALUE;
1661 }
1662
1663 CaptureResult &result = *(mResultQueue.begin());
1664 frame->mResultExtras = result.mResultExtras;
1665 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001666 mResultQueue.erase(mResultQueue.begin());
1667
1668 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001669}
1670
1671status_t Camera3Device::triggerAutofocus(uint32_t id) {
1672 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001675 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1676 // Mix-in this trigger into the next request and only the next request.
1677 RequestTrigger trigger[] = {
1678 {
1679 ANDROID_CONTROL_AF_TRIGGER,
1680 ANDROID_CONTROL_AF_TRIGGER_START
1681 },
1682 {
1683 ANDROID_CONTROL_AF_TRIGGER_ID,
1684 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001685 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 };
1687
1688 return mRequestThread->queueTrigger(trigger,
1689 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001690}
1691
1692status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1693 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001694 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001695
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001696 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1697 // Mix-in this trigger into the next request and only the next request.
1698 RequestTrigger trigger[] = {
1699 {
1700 ANDROID_CONTROL_AF_TRIGGER,
1701 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1702 },
1703 {
1704 ANDROID_CONTROL_AF_TRIGGER_ID,
1705 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001706 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001707 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001709 return mRequestThread->queueTrigger(trigger,
1710 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001711}
1712
1713status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1714 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001715 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001717 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1718 // Mix-in this trigger into the next request and only the next request.
1719 RequestTrigger trigger[] = {
1720 {
1721 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1722 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1723 },
1724 {
1725 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1726 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001727 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001728 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001730 return mRequestThread->queueTrigger(trigger,
1731 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732}
1733
Jianing Weicb0652e2014-03-12 18:29:36 -07001734status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001735 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001736 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001737 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001738
Zhijun He7ef20392014-04-21 16:04:17 -07001739 {
1740 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001741 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001742 }
1743
Emilian Peev08dd2452017-04-06 16:55:14 +01001744 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001745}
1746
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001747status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001748 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1749}
1750
1751status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001753 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001754 Mutex::Autolock il(mInterfaceLock);
1755 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001756
1757 sp<Camera3StreamInterface> stream;
1758 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1759 if (outputStreamIdx == NAME_NOT_FOUND) {
1760 CLOGE("Stream %d does not exist", streamId);
1761 return BAD_VALUE;
1762 }
1763
1764 stream = mOutputStreams.editValueAt(outputStreamIdx);
1765
1766 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001767 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001768 return BAD_VALUE;
1769 }
1770
1771 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001772 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001773 return BAD_VALUE;
1774 }
1775
Ruben Brunkc78ac262015-08-13 17:58:46 -07001776 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001777}
1778
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001779status_t Camera3Device::tearDown(int streamId) {
1780 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001781 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001782 Mutex::Autolock il(mInterfaceLock);
1783 Mutex::Autolock l(mLock);
1784
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001785 sp<Camera3StreamInterface> stream;
1786 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1787 if (outputStreamIdx == NAME_NOT_FOUND) {
1788 CLOGE("Stream %d does not exist", streamId);
1789 return BAD_VALUE;
1790 }
1791
1792 stream = mOutputStreams.editValueAt(outputStreamIdx);
1793
1794 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1795 CLOGE("Stream %d is a target of a in-progress request", streamId);
1796 return BAD_VALUE;
1797 }
1798
1799 return stream->tearDown();
1800}
1801
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001802status_t Camera3Device::addBufferListenerForStream(int streamId,
1803 wp<Camera3StreamBufferListener> listener) {
1804 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001805 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001806 Mutex::Autolock il(mInterfaceLock);
1807 Mutex::Autolock l(mLock);
1808
1809 sp<Camera3StreamInterface> stream;
1810 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1811 if (outputStreamIdx == NAME_NOT_FOUND) {
1812 CLOGE("Stream %d does not exist", streamId);
1813 return BAD_VALUE;
1814 }
1815
1816 stream = mOutputStreams.editValueAt(outputStreamIdx);
1817 stream->addBufferListener(listener);
1818
1819 return OK;
1820}
1821
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001822/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001823 * Methods called by subclasses
1824 */
1825
1826void Camera3Device::notifyStatus(bool idle) {
1827 {
1828 // Need mLock to safely update state and synchronize to current
1829 // state of methods in flight.
1830 Mutex::Autolock l(mLock);
1831 // We can get various system-idle notices from the status tracker
1832 // while starting up. Only care about them if we've actually sent
1833 // in some requests recently.
1834 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1835 return;
1836 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001837 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001838 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001839 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001840
1841 // Skip notifying listener if we're doing some user-transparent
1842 // state changes
1843 if (mPauseStateNotify) return;
1844 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001845
1846 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 {
1848 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001849 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 }
1851 if (idle && listener != NULL) {
1852 listener->notifyIdle();
1853 }
1854}
1855
Shuzhen Wang758c2152017-01-10 18:26:18 -08001856status_t Camera3Device::setConsumerSurfaces(int streamId,
1857 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001858 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001859 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1860 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001861 Mutex::Autolock il(mInterfaceLock);
1862 Mutex::Autolock l(mLock);
1863
Shuzhen Wang758c2152017-01-10 18:26:18 -08001864 if (consumers.size() == 0) {
1865 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001866 return BAD_VALUE;
1867 }
1868
1869 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1870 if (idx == NAME_NOT_FOUND) {
1871 CLOGE("Stream %d is unknown", streamId);
1872 return idx;
1873 }
1874 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001875 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001876 if (res != OK) {
1877 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1878 return res;
1879 }
1880
Shuzhen Wang0129d522016-10-30 22:43:41 -07001881 if (stream->isConsumerConfigurationDeferred()) {
1882 if (!stream->isConfiguring()) {
1883 CLOGE("Stream %d was already fully configured.", streamId);
1884 return INVALID_OPERATION;
1885 }
Zhijun He5d677d12016-05-29 16:52:39 -07001886
Shuzhen Wang0129d522016-10-30 22:43:41 -07001887 res = stream->finishConfiguration();
1888 if (res != OK) {
1889 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1890 stream->getId(), strerror(-res), res);
1891 return res;
1892 }
Zhijun He5d677d12016-05-29 16:52:39 -07001893 }
1894
1895 return OK;
1896}
1897
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899 * Camera3Device private methods
1900 */
1901
1902sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001903 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 ATRACE_CALL();
1905 status_t res;
1906
1907 sp<CaptureRequest> newRequest = new CaptureRequest;
1908 newRequest->mSettings = request;
1909
1910 camera_metadata_entry_t inputStreams =
1911 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1912 if (inputStreams.count > 0) {
1913 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001914 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001915 CLOGE("Request references unknown input stream %d",
1916 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001917 return NULL;
1918 }
1919 // Lazy completion of stream configuration (allocation/registration)
1920 // on first use
1921 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001922 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001923 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001924 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001925 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001926 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 return NULL;
1928 }
1929 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001930 // Check if stream is being prepared
1931 if (mInputStream->isPreparing()) {
1932 CLOGE("Request references an input stream that's being prepared!");
1933 return NULL;
1934 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001935
1936 newRequest->mInputStream = mInputStream;
1937 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1938 }
1939
1940 camera_metadata_entry_t streams =
1941 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1942 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001943 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001944 return NULL;
1945 }
1946
1947 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001948 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001949 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001950 CLOGE("Request references unknown stream %d",
1951 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001952 return NULL;
1953 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001954 sp<Camera3OutputStreamInterface> stream =
1955 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001956
Zhijun He5d677d12016-05-29 16:52:39 -07001957 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07001958 auto iter = surfaceMap.find(streams.data.i32[i]);
1959 if (iter != surfaceMap.end()) {
1960 const std::vector<size_t>& surfaces = iter->second;
1961 for (const auto& surface : surfaces) {
1962 if (stream->isConsumerConfigurationDeferred(surface)) {
1963 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
1964 "due to deferred consumer", stream->getId(), surface);
1965 return NULL;
1966 }
1967 }
1968 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07001969 }
1970
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001971 // Lazy completion of stream configuration (allocation/registration)
1972 // on first use
1973 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001974 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001975 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001976 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
1977 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001978 return NULL;
1979 }
1980 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001981 // Check if stream is being prepared
1982 if (stream->isPreparing()) {
1983 CLOGE("Request references an output stream that's being prepared!");
1984 return NULL;
1985 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986
1987 newRequest->mOutputStreams.push(stream);
1988 }
1989 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001990 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001991
1992 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001993}
1994
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001995bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
1996 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
1997 Size size = mSupportedOpaqueInputSizes[i];
1998 if (size.width == width && size.height == height) {
1999 return true;
2000 }
2001 }
2002
2003 return false;
2004}
2005
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002006void Camera3Device::cancelStreamsConfigurationLocked() {
2007 int res = OK;
2008 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2009 res = mInputStream->cancelConfiguration();
2010 if (res != OK) {
2011 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2012 mInputStream->getId(), strerror(-res), res);
2013 }
2014 }
2015
2016 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2017 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2018 if (outputStream->isConfiguring()) {
2019 res = outputStream->cancelConfiguration();
2020 if (res != OK) {
2021 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2022 outputStream->getId(), strerror(-res), res);
2023 }
2024 }
2025 }
2026
2027 // Return state to that at start of call, so that future configures
2028 // properly clean things up
2029 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2030 mNeedConfig = true;
2031}
2032
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002033status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002034 ATRACE_CALL();
2035 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002036
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002037 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002038 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002039 return INVALID_OPERATION;
2040 }
2041
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002042 if (operatingMode < 0) {
2043 CLOGE("Invalid operating mode: %d", operatingMode);
2044 return BAD_VALUE;
2045 }
2046
2047 bool isConstrainedHighSpeed =
2048 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2049 operatingMode;
2050
2051 if (mOperatingMode != operatingMode) {
2052 mNeedConfig = true;
2053 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2054 mOperatingMode = operatingMode;
2055 }
2056
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002057 if (!mNeedConfig) {
2058 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2059 return OK;
2060 }
2061
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002062 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2063 // adding a dummy stream instead.
2064 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2065 if (mOutputStreams.size() == 0) {
2066 addDummyStreamLocked();
2067 } else {
2068 tryRemoveDummyStreamLocked();
2069 }
2070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002072 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
2074 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002075 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2077
2078 Vector<camera3_stream_t*> streams;
2079 streams.setCapacity(config.num_streams);
2080
2081 if (mInputStream != NULL) {
2082 camera3_stream_t *inputStream;
2083 inputStream = mInputStream->startConfiguration();
2084 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002085 CLOGE("Can't start input stream configuration");
2086 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087 return INVALID_OPERATION;
2088 }
2089 streams.add(inputStream);
2090 }
2091
2092 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002093
2094 // Don't configure bidi streams twice, nor add them twice to the list
2095 if (mOutputStreams[i].get() ==
2096 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2097
2098 config.num_streams--;
2099 continue;
2100 }
2101
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 camera3_stream_t *outputStream;
2103 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2104 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002105 CLOGE("Can't start output stream configuration");
2106 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 return INVALID_OPERATION;
2108 }
2109 streams.add(outputStream);
2110 }
2111
2112 config.streams = streams.editArray();
2113
2114 // Do the HAL configuration; will potentially touch stream
2115 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002116
2117 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002118
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002119 if (res == BAD_VALUE) {
2120 // HAL rejected this set of streams as unsupported, clean up config
2121 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002122 CLOGE("Set of requested inputs/outputs not supported by HAL");
2123 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002124 return BAD_VALUE;
2125 } else if (res != OK) {
2126 // Some other kind of error from configure_streams - this is not
2127 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002128 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2129 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 return res;
2131 }
2132
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002133 // Finish all stream configuration immediately.
2134 // TODO: Try to relax this later back to lazy completion, which should be
2135 // faster
2136
Igor Murashkin073f8572013-05-02 14:59:28 -07002137 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002138 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002139 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002140 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002141 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002142 cancelStreamsConfigurationLocked();
2143 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002144 }
2145 }
2146
2147 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002148 sp<Camera3OutputStreamInterface> outputStream =
2149 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002150 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002151 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002152 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002153 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002154 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002155 cancelStreamsConfigurationLocked();
2156 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002157 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002158 }
2159 }
2160
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002161 // Request thread needs to know to avoid using repeat-last-settings protocol
2162 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002163 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164
Zhijun He90f7c372016-08-16 16:19:43 -07002165 char value[PROPERTY_VALUE_MAX];
2166 property_get("camera.fifo.disable", value, "0");
2167 int32_t disableFifo = atoi(value);
2168 if (disableFifo != 1) {
2169 // Boost priority of request thread to SCHED_FIFO.
2170 pid_t requestThreadTid = mRequestThread->getTid();
2171 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002172 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002173 if (res != OK) {
2174 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2175 strerror(-res), res);
2176 } else {
2177 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2178 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002179 }
2180
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002182
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002183 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002184
Ruben Brunk183f0562015-08-12 12:55:02 -07002185 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2186 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002187
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002188 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189
Zhijun He0a210512014-07-24 13:45:15 -07002190 // tear down the deleted streams after configure streams.
2191 mDeletedStreams.clear();
2192
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194}
2195
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002196status_t Camera3Device::addDummyStreamLocked() {
2197 ATRACE_CALL();
2198 status_t res;
2199
2200 if (mDummyStreamId != NO_STREAM) {
2201 // Should never be adding a second dummy stream when one is already
2202 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002203 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2204 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002205 return INVALID_OPERATION;
2206 }
2207
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002208 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002209
2210 sp<Camera3OutputStreamInterface> dummyStream =
2211 new Camera3DummyStream(mNextStreamId);
2212
2213 res = mOutputStreams.add(mNextStreamId, dummyStream);
2214 if (res < 0) {
2215 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2216 return res;
2217 }
2218
2219 mDummyStreamId = mNextStreamId;
2220 mNextStreamId++;
2221
2222 return OK;
2223}
2224
2225status_t Camera3Device::tryRemoveDummyStreamLocked() {
2226 ATRACE_CALL();
2227 status_t res;
2228
2229 if (mDummyStreamId == NO_STREAM) return OK;
2230 if (mOutputStreams.size() == 1) return OK;
2231
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002232 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002233
2234 // Ok, have a dummy stream and there's at least one other output stream,
2235 // so remove the dummy
2236
2237 sp<Camera3StreamInterface> deletedStream;
2238 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2239 if (outputStreamIdx == NAME_NOT_FOUND) {
2240 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2241 return INVALID_OPERATION;
2242 }
2243
2244 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2245 mOutputStreams.removeItemsAt(outputStreamIdx);
2246
2247 // Free up the stream endpoint so that it can be used by some other stream
2248 res = deletedStream->disconnect();
2249 if (res != OK) {
2250 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2251 // fall through since we want to still list the stream as deleted.
2252 }
2253 mDeletedStreams.add(deletedStream);
2254 mDummyStreamId = NO_STREAM;
2255
2256 return res;
2257}
2258
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002259void Camera3Device::setErrorState(const char *fmt, ...) {
2260 Mutex::Autolock l(mLock);
2261 va_list args;
2262 va_start(args, fmt);
2263
2264 setErrorStateLockedV(fmt, args);
2265
2266 va_end(args);
2267}
2268
2269void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2270 Mutex::Autolock l(mLock);
2271 setErrorStateLockedV(fmt, args);
2272}
2273
2274void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2275 va_list args;
2276 va_start(args, fmt);
2277
2278 setErrorStateLockedV(fmt, args);
2279
2280 va_end(args);
2281}
2282
2283void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002284 // Print out all error messages to log
2285 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002286 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002287
2288 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002289 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002290
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002291 mErrorCause = errorCause;
2292
2293 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002294 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002295
2296 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002297 sp<NotificationListener> listener = mListener.promote();
2298 if (listener != NULL) {
2299 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002300 CaptureResultExtras());
2301 }
2302
2303 // Save stack trace. View by dumping it later.
2304 CameraTraces::saveTrace();
2305 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002306}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307
2308/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002309 * In-flight request management
2310 */
2311
Jianing Weicb0652e2014-03-12 18:29:36 -07002312status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002313 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002314 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002315 ATRACE_CALL();
2316 Mutex::Autolock l(mInFlightLock);
2317
2318 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002319 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002320 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002321 if (res < 0) return res;
2322
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002323 if (mInFlightMap.size() == 1) {
2324 mStatusTracker->markComponentActive(mInFlightStatusId);
2325 }
2326
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002327 return OK;
2328}
2329
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002330void Camera3Device::returnOutputBuffers(
2331 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2332 nsecs_t timestamp) {
2333 for (size_t i = 0; i < numBuffers; i++)
2334 {
2335 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2336 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2337 // Note: stream may be deallocated at this point, if this buffer was
2338 // the last reference to it.
2339 if (res != OK) {
2340 ALOGE("Can't return buffer to its stream: %s (%d)",
2341 strerror(-res), res);
2342 }
2343 }
2344}
2345
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002346void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2347 mInFlightMap.removeItemsAt(idx, 1);
2348
2349 // Indicate idle inFlightMap to the status tracker
2350 if (mInFlightMap.size() == 0) {
2351 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2352 }
2353}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002354
2355void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2356
2357 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2358 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2359
2360 nsecs_t sensorTimestamp = request.sensorTimestamp;
2361 nsecs_t shutterTimestamp = request.shutterTimestamp;
2362
Emilian Peevc6747862017-06-12 15:57:26 +01002363 bool skipResultMetadata = false;
2364 if (request.requestStatus != OK) {
2365 switch (request.requestStatus) {
2366 case CAMERA3_MSG_ERROR_DEVICE:
2367 case CAMERA3_MSG_ERROR_REQUEST:
2368 case CAMERA3_MSG_ERROR_RESULT:
2369 skipResultMetadata = true;
2370 break;
2371 case CAMERA3_MSG_ERROR_BUFFER:
2372 //Result metadata should return in this case.
2373 skipResultMetadata = false;
2374 break;
2375 default:
2376 SET_ERR("Unknown error message: %d", request.requestStatus);
2377 skipResultMetadata = false;
2378 break;
2379 }
2380 }
2381
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002382 // Check if it's okay to remove the request from InFlightMap:
2383 // In the case of a successful request:
2384 // all input and output buffers, all result metadata, shutter callback
2385 // arrived.
2386 // In the case of a unsuccessful request:
2387 // all input and output buffers arrived.
2388 if (request.numBuffersLeft == 0 &&
Emilian Peevc6747862017-06-12 15:57:26 +01002389 (skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002390 (request.haveResultMetadata && shutterTimestamp != 0))) {
2391 ATRACE_ASYNC_END("frame capture", frameNumber);
2392
Shuzhen Wang403044a2017-02-26 23:29:04 -08002393 // Sanity check - if sensor timestamp matches shutter timestamp in the
2394 // case of request having callback.
2395 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002396 sensorTimestamp != shutterTimestamp) {
2397 SET_ERR("sensor timestamp (%" PRId64
2398 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2399 sensorTimestamp, frameNumber, shutterTimestamp);
2400 }
2401
2402 // for an unsuccessful request, it may have pending output buffers to
2403 // return.
2404 assert(request.requestStatus != OK ||
2405 request.pendingOutputBuffers.size() == 0);
2406 returnOutputBuffers(request.pendingOutputBuffers.array(),
2407 request.pendingOutputBuffers.size(), 0);
2408
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002409 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002410 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2411 }
2412
2413 // Sanity check - if we have too many in-flight frames, something has
2414 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002415 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002416 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002417 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2418 kInFlightWarnLimitHighSpeed) {
2419 CLOGE("In-flight list too large for high speed configuration: %zu",
2420 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002421 }
2422}
2423
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002424void Camera3Device::insertResultLocked(CaptureResult *result,
2425 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002426 if (result == nullptr) return;
2427
Emilian Peev71c73a22017-03-21 16:35:51 +00002428 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2429 result->mMetadata.getAndLock());
2430 set_camera_metadata_vendor_id(meta, mVendorTagId);
2431 result->mMetadata.unlock(meta);
2432
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002433 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2434 (int32_t*)&frameNumber, 1) != OK) {
2435 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2436 return;
2437 }
2438
2439 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2440 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2441 return;
2442 }
2443
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002444 // Valid result, insert into queue
2445 List<CaptureResult>::iterator queuedResult =
2446 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2447 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2448 ", burstId = %" PRId32, __FUNCTION__,
2449 queuedResult->mResultExtras.requestId,
2450 queuedResult->mResultExtras.frameNumber,
2451 queuedResult->mResultExtras.burstId);
2452
2453 mResultSignal.signal();
2454}
2455
2456
2457void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002458 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002459 Mutex::Autolock l(mOutputLock);
2460
2461 CaptureResult captureResult;
2462 captureResult.mResultExtras = resultExtras;
2463 captureResult.mMetadata = partialResult;
2464
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002465 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002466}
2467
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002468
2469void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2470 CaptureResultExtras &resultExtras,
2471 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002472 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002473 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002474 if (pendingMetadata.isEmpty())
2475 return;
2476
2477 Mutex::Autolock l(mOutputLock);
2478
2479 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002480 if (reprocess) {
2481 if (frameNumber < mNextReprocessResultFrameNumber) {
2482 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002483 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002484 frameNumber, mNextReprocessResultFrameNumber);
2485 return;
2486 }
2487 mNextReprocessResultFrameNumber = frameNumber + 1;
2488 } else {
2489 if (frameNumber < mNextResultFrameNumber) {
2490 SET_ERR("Out-of-order capture result metadata submitted! "
2491 "(got frame number %d, expecting %d)",
2492 frameNumber, mNextResultFrameNumber);
2493 return;
2494 }
2495 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002496 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002497
2498 CaptureResult captureResult;
2499 captureResult.mResultExtras = resultExtras;
2500 captureResult.mMetadata = pendingMetadata;
2501
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002502 // Append any previous partials to form a complete result
2503 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2504 captureResult.mMetadata.append(collectedPartialResult);
2505 }
2506
2507 captureResult.mMetadata.sort();
2508
2509 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002510 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2511 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002512 SET_ERR("No timestamp provided by HAL for frame %d!",
2513 frameNumber);
2514 return;
2515 }
2516
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002517 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2518 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2519
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002520 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002521}
2522
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002523/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524 * Camera HAL device callback methods
2525 */
2526
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002527void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002528 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002529
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002530 status_t res;
2531
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002532 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002533 if (result->result == NULL && result->num_output_buffers == 0 &&
2534 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002535 SET_ERR("No result data provided by HAL for frame %d",
2536 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002537 return;
2538 }
Zhijun He204e3292014-07-14 17:09:23 -07002539
Zhijun He204e3292014-07-14 17:09:23 -07002540 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002541 result->result != NULL &&
2542 result->partial_result != 1) {
2543 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2544 " if partial result is not supported",
2545 frameNumber, result->partial_result);
2546 return;
2547 }
2548
2549 bool isPartialResult = false;
2550 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002551 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002552 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002553
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002554 // Get shutter timestamp and resultExtras from list of in-flight requests,
2555 // where it was added by the shutter notification for this frame. If the
2556 // shutter timestamp isn't received yet, append the output buffers to the
2557 // in-flight request and they will be returned when the shutter timestamp
2558 // arrives. Update the in-flight status and remove the in-flight entry if
2559 // all result data and shutter timestamp have been received.
2560 nsecs_t shutterTimestamp = 0;
2561
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002562 {
2563 Mutex::Autolock l(mInFlightLock);
2564 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2565 if (idx == NAME_NOT_FOUND) {
2566 SET_ERR("Unknown frame number for capture result: %d",
2567 frameNumber);
2568 return;
2569 }
2570 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002571 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2572 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002573 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002574 __FUNCTION__, request.resultExtras.requestId,
2575 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002576 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002577 // Always update the partial count to the latest one if it's not 0
2578 // (buffers only). When framework aggregates adjacent partial results
2579 // into one, the latest partial count will be used.
2580 if (result->partial_result != 0)
2581 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002582
2583 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002584 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002585 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2586 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2587 " the range of [1, %d] when metadata is included in the result",
2588 frameNumber, result->partial_result, mNumPartialResults);
2589 return;
2590 }
2591 isPartialResult = (result->partial_result < mNumPartialResults);
2592 if (isPartialResult) {
2593 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002594 }
2595
Shuzhen Wang4a472662017-02-26 23:29:04 -08002596 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002597 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002598 sendPartialCaptureResult(result->result, request.resultExtras,
2599 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002600 }
2601 }
2602
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002603 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002604 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002605
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002606 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002607 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002608 if (request.haveResultMetadata) {
2609 SET_ERR("Called multiple times with metadata for frame %d",
2610 frameNumber);
2611 return;
2612 }
Zhijun He204e3292014-07-14 17:09:23 -07002613 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002614 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002615 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002616 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002617 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002618 request.haveResultMetadata = true;
2619 }
2620
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002621 uint32_t numBuffersReturned = result->num_output_buffers;
2622 if (result->input_buffer != NULL) {
2623 if (hasInputBufferInRequest) {
2624 numBuffersReturned += 1;
2625 } else {
2626 ALOGW("%s: Input buffer should be NULL if there is no input"
2627 " buffer sent in the request",
2628 __FUNCTION__);
2629 }
2630 }
2631 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002632 if (request.numBuffersLeft < 0) {
2633 SET_ERR("Too many buffers returned for frame %d",
2634 frameNumber);
2635 return;
2636 }
2637
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002638 camera_metadata_ro_entry_t entry;
2639 res = find_camera_metadata_ro_entry(result->result,
2640 ANDROID_SENSOR_TIMESTAMP, &entry);
2641 if (res == OK && entry.count == 1) {
2642 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002643 }
2644
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002645 // If shutter event isn't received yet, append the output buffers to
2646 // the in-flight request. Otherwise, return the output buffers to
2647 // streams.
2648 if (shutterTimestamp == 0) {
2649 request.pendingOutputBuffers.appendArray(result->output_buffers,
2650 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002651 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002652 returnOutputBuffers(result->output_buffers,
2653 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002654 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002655
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002656 if (result->result != NULL && !isPartialResult) {
2657 if (shutterTimestamp == 0) {
2658 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002659 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002660 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002661 CameraMetadata metadata;
2662 metadata = result->result;
2663 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002664 collectedPartialResult, frameNumber,
2665 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002666 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002667 }
2668
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002669 removeInFlightRequestIfReadyLocked(idx);
2670 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002671
Zhijun Hef0d962a2014-06-30 10:24:11 -07002672 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002673 if (hasInputBufferInRequest) {
2674 Camera3Stream *stream =
2675 Camera3Stream::cast(result->input_buffer->stream);
2676 res = stream->returnInputBuffer(*(result->input_buffer));
2677 // Note: stream may be deallocated at this point, if this buffer was the
2678 // last reference to it.
2679 if (res != OK) {
2680 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2681 " its stream:%s (%d)", __FUNCTION__,
2682 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002683 }
2684 } else {
2685 ALOGW("%s: Input buffer should be NULL if there is no input"
2686 " buffer sent in the request, skipping input buffer return.",
2687 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002688 }
2689 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002690}
2691
2692void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002693 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002694 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002695 {
2696 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002697 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002698 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002699
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002700 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002701 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002702 return;
2703 }
2704
2705 switch (msg->type) {
2706 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002707 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002708 break;
2709 }
2710 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002711 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002712 break;
2713 }
2714 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002715 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002716 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002717 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002718}
2719
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002720void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002721 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002722
2723 // Map camera HAL error codes to ICameraDeviceCallback error codes
2724 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002725 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002726 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002727 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002728 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002729 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002730 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002731 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002732 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002733 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002734 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002736 };
2737
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002738 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002739 ((msg.error_code >= 0) &&
2740 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2741 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002742 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002743
2744 int streamId = 0;
2745 if (msg.error_stream != NULL) {
2746 Camera3Stream *stream =
2747 Camera3Stream::cast(msg.error_stream);
2748 streamId = stream->getId();
2749 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002750 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2751 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002752 streamId, msg.error_code);
2753
2754 CaptureResultExtras resultExtras;
2755 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002756 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002757 // SET_ERR calls notifyError
2758 SET_ERR("Camera HAL reported serious device error");
2759 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002760 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2761 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2762 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002763 {
2764 Mutex::Autolock l(mInFlightLock);
2765 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2766 if (idx >= 0) {
2767 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2768 r.requestStatus = msg.error_code;
2769 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002770 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2771 errorCode) {
2772 // In case of missing result check whether the buffers
2773 // returned. If they returned, then remove inflight
2774 // request.
2775 removeInFlightRequestIfReadyLocked(idx);
2776 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002777 } else {
2778 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002779 ALOGE("Camera %s: %s: cannot find in-flight request on "
2780 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002781 resultExtras.frameNumber);
2782 }
2783 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002784 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002785 if (listener != NULL) {
2786 listener->notifyError(errorCode, resultExtras);
2787 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002788 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002789 }
2790 break;
2791 default:
2792 // SET_ERR calls notifyError
2793 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2794 break;
2795 }
2796}
2797
2798void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002799 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002800 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002801
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002802 // Set timestamp for the request in the in-flight tracking
2803 // and get the request ID to send upstream
2804 {
2805 Mutex::Autolock l(mInFlightLock);
2806 idx = mInFlightMap.indexOfKey(msg.frame_number);
2807 if (idx >= 0) {
2808 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002809
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002810 // Verify ordering of shutter notifications
2811 {
2812 Mutex::Autolock l(mOutputLock);
2813 // TODO: need to track errors for tighter bounds on expected frame number.
2814 if (r.hasInputBuffer) {
2815 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2816 SET_ERR("Shutter notification out-of-order. Expected "
2817 "notification for frame %d, got frame %d",
2818 mNextReprocessShutterFrameNumber, msg.frame_number);
2819 return;
2820 }
2821 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2822 } else {
2823 if (msg.frame_number < mNextShutterFrameNumber) {
2824 SET_ERR("Shutter notification out-of-order. Expected "
2825 "notification for frame %d, got frame %d",
2826 mNextShutterFrameNumber, msg.frame_number);
2827 return;
2828 }
2829 mNextShutterFrameNumber = msg.frame_number + 1;
2830 }
2831 }
2832
Shuzhen Wang4a472662017-02-26 23:29:04 -08002833 r.shutterTimestamp = msg.timestamp;
2834 if (r.hasCallback) {
2835 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002836 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002837 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002838 // Call listener, if any
2839 if (listener != NULL) {
2840 listener->notifyShutter(r.resultExtras, msg.timestamp);
2841 }
2842 // send pending result and buffers
2843 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2844 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002845 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002846 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002847 returnOutputBuffers(r.pendingOutputBuffers.array(),
2848 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2849 r.pendingOutputBuffers.clear();
2850
2851 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002852 }
2853 }
2854 if (idx < 0) {
2855 SET_ERR("Shutter notification for non-existent frame number %d",
2856 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857 }
2858}
2859
2860
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002861CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002862 ALOGV("%s", __FUNCTION__);
2863
Igor Murashkin1e479c02013-09-06 16:55:14 -07002864 CameraMetadata retVal;
2865
2866 if (mRequestThread != NULL) {
2867 retVal = mRequestThread->getLatestRequest();
2868 }
2869
Igor Murashkin1e479c02013-09-06 16:55:14 -07002870 return retVal;
2871}
2872
Jianing Weicb0652e2014-03-12 18:29:36 -07002873
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002874void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2875 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2876 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2877}
2878
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002879/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002880 * HalInterface inner class methods
2881 */
2882
Yifan Hongf79b5542017-04-11 14:44:25 -07002883Camera3Device::HalInterface::HalInterface(
2884 sp<ICameraDeviceSession> &session,
2885 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002886 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002887 mHidlSession(session),
2888 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002889
2890Camera3Device::HalInterface::HalInterface() :
2891 mHal3Device(nullptr) {}
2892
2893Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002894 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002895 mHidlSession(other.mHidlSession),
2896 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002897
2898bool Camera3Device::HalInterface::valid() {
2899 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2900}
2901
2902void Camera3Device::HalInterface::clear() {
2903 mHal3Device = nullptr;
2904 mHidlSession.clear();
2905}
2906
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002907bool Camera3Device::HalInterface::supportBatchRequest() {
2908 return mHidlSession != nullptr;
2909}
2910
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002911status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2912 camera3_request_template_t templateId,
2913 /*out*/ camera_metadata_t **requestTemplate) {
2914 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2915 if (!valid()) return INVALID_OPERATION;
2916 status_t res = OK;
2917
2918 if (mHal3Device != nullptr) {
2919 const camera_metadata *r;
2920 r = mHal3Device->ops->construct_default_request_settings(
2921 mHal3Device, templateId);
2922 if (r == nullptr) return BAD_VALUE;
2923 *requestTemplate = clone_camera_metadata(r);
2924 if (requestTemplate == nullptr) {
2925 ALOGE("%s: Unable to clone camera metadata received from HAL",
2926 __FUNCTION__);
2927 return INVALID_OPERATION;
2928 }
2929 } else {
2930 common::V1_0::Status status;
2931 RequestTemplate id;
2932 switch (templateId) {
2933 case CAMERA3_TEMPLATE_PREVIEW:
2934 id = RequestTemplate::PREVIEW;
2935 break;
2936 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2937 id = RequestTemplate::STILL_CAPTURE;
2938 break;
2939 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2940 id = RequestTemplate::VIDEO_RECORD;
2941 break;
2942 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2943 id = RequestTemplate::VIDEO_SNAPSHOT;
2944 break;
2945 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2946 id = RequestTemplate::ZERO_SHUTTER_LAG;
2947 break;
2948 case CAMERA3_TEMPLATE_MANUAL:
2949 id = RequestTemplate::MANUAL;
2950 break;
2951 default:
2952 // Unknown template ID
2953 return BAD_VALUE;
2954 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002955 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002956 [&status, &requestTemplate]
2957 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
2958 status = s;
2959 if (status == common::V1_0::Status::OK) {
2960 const camera_metadata *r =
2961 reinterpret_cast<const camera_metadata_t*>(request.data());
2962 size_t expectedSize = request.size();
2963 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07002964 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002965 *requestTemplate = clone_camera_metadata(r);
2966 if (*requestTemplate == nullptr) {
2967 ALOGE("%s: Unable to clone camera metadata received from HAL",
2968 __FUNCTION__);
2969 status = common::V1_0::Status::INTERNAL_ERROR;
2970 }
2971 } else {
2972 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2973 status = common::V1_0::Status::INTERNAL_ERROR;
2974 }
2975 }
2976 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002977 if (!err.isOk()) {
2978 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2979 res = DEAD_OBJECT;
2980 } else {
2981 res = CameraProviderManager::mapToStatusT(status);
2982 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002983 }
2984 return res;
2985}
2986
2987status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
2988 ATRACE_NAME("CameraHal::configureStreams");
2989 if (!valid()) return INVALID_OPERATION;
2990 status_t res = OK;
2991
2992 if (mHal3Device != nullptr) {
2993 res = mHal3Device->ops->configure_streams(mHal3Device, config);
2994 } else {
2995 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002996 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002997 StreamConfiguration requestedConfiguration;
2998 requestedConfiguration.streams.resize(config->num_streams);
2999 for (size_t i = 0; i < config->num_streams; i++) {
3000 Stream &dst = requestedConfiguration.streams[i];
3001 camera3_stream_t *src = config->streams[i];
3002
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003003 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3004 cam3stream->setBufferFreedListener(this);
3005 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 StreamType streamType;
3007 switch (src->stream_type) {
3008 case CAMERA3_STREAM_OUTPUT:
3009 streamType = StreamType::OUTPUT;
3010 break;
3011 case CAMERA3_STREAM_INPUT:
3012 streamType = StreamType::INPUT;
3013 break;
3014 default:
3015 ALOGE("%s: Stream %d: Unsupported stream type %d",
3016 __FUNCTION__, streamId, config->streams[i]->stream_type);
3017 return BAD_VALUE;
3018 }
3019 dst.id = streamId;
3020 dst.streamType = streamType;
3021 dst.width = src->width;
3022 dst.height = src->height;
3023 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003024 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003025 dst.dataSpace = mapToHidlDataspace(src->data_space);
3026 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003027
3028 activeStreams.insert(streamId);
3029 // Create Buffer ID map if necessary
3030 if (mBufferIdMaps.count(streamId) == 0) {
3031 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3032 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003033 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003034 // remove BufferIdMap for deleted streams
3035 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3036 int streamId = it->first;
3037 bool active = activeStreams.count(streamId) > 0;
3038 if (!active) {
3039 it = mBufferIdMaps.erase(it);
3040 } else {
3041 ++it;
3042 }
3043 }
3044
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003045 res = mapToStreamConfigurationMode(
3046 (camera3_stream_configuration_mode_t) config->operation_mode,
3047 /*out*/ &requestedConfiguration.operationMode);
3048 if (res != OK) {
3049 return res;
3050 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003051
3052 // Invoke configureStreams
3053
3054 HalStreamConfiguration finalConfiguration;
3055 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003056 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003057 [&status, &finalConfiguration]
3058 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3059 finalConfiguration = halConfiguration;
3060 status = s;
3061 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003062 if (!err.isOk()) {
3063 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3064 return DEAD_OBJECT;
3065 }
3066
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003067 if (status != common::V1_0::Status::OK ) {
3068 return CameraProviderManager::mapToStatusT(status);
3069 }
3070
3071 // And convert output stream configuration from HIDL
3072
3073 for (size_t i = 0; i < config->num_streams; i++) {
3074 camera3_stream_t *dst = config->streams[i];
3075 int streamId = Camera3Stream::cast(dst)->getId();
3076
3077 // Start scan at i, with the assumption that the stream order matches
3078 size_t realIdx = i;
3079 bool found = false;
3080 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3081 if (finalConfiguration.streams[realIdx].id == streamId) {
3082 found = true;
3083 break;
3084 }
3085 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3086 }
3087 if (!found) {
3088 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3089 __FUNCTION__, streamId);
3090 return INVALID_OPERATION;
3091 }
3092 HalStream &src = finalConfiguration.streams[realIdx];
3093
3094 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3095 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3096 if (dst->format != overrideFormat) {
3097 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3098 streamId, dst->format);
3099 }
3100 } else {
3101 // Override allowed with IMPLEMENTATION_DEFINED
3102 dst->format = overrideFormat;
3103 }
3104
3105 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3106 if (src.producerUsage != 0) {
3107 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3108 __FUNCTION__, streamId);
3109 return INVALID_OPERATION;
3110 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003111 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003112 } else {
3113 // OUTPUT
3114 if (src.consumerUsage != 0) {
3115 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3116 __FUNCTION__, streamId);
3117 return INVALID_OPERATION;
3118 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003119 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120 }
3121 dst->max_buffers = src.maxBuffers;
3122 }
3123 }
3124 return res;
3125}
3126
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003127void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3128 /*out*/device::V3_2::CaptureRequest* captureRequest,
3129 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3130
3131 if (captureRequest == nullptr || handlesCreated == nullptr) {
3132 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3133 __FUNCTION__, captureRequest, handlesCreated);
3134 return;
3135 }
3136
3137 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003138
3139 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003140
3141 {
3142 std::lock_guard<std::mutex> lock(mInflightLock);
3143 if (request->input_buffer != nullptr) {
3144 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3145 buffer_handle_t buf = *(request->input_buffer->buffer);
3146 auto pair = getBufferId(buf, streamId);
3147 bool isNewBuffer = pair.first;
3148 uint64_t bufferId = pair.second;
3149 captureRequest->inputBuffer.streamId = streamId;
3150 captureRequest->inputBuffer.bufferId = bufferId;
3151 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3152 captureRequest->inputBuffer.status = BufferStatus::OK;
3153 native_handle_t *acquireFence = nullptr;
3154 if (request->input_buffer->acquire_fence != -1) {
3155 acquireFence = native_handle_create(1,0);
3156 acquireFence->data[0] = request->input_buffer->acquire_fence;
3157 handlesCreated->push_back(acquireFence);
3158 }
3159 captureRequest->inputBuffer.acquireFence = acquireFence;
3160 captureRequest->inputBuffer.releaseFence = nullptr;
3161
3162 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3163 request->input_buffer->buffer,
3164 request->input_buffer->acquire_fence);
3165 } else {
3166 captureRequest->inputBuffer.streamId = -1;
3167 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3168 }
3169
3170 captureRequest->outputBuffers.resize(request->num_output_buffers);
3171 for (size_t i = 0; i < request->num_output_buffers; i++) {
3172 const camera3_stream_buffer_t *src = request->output_buffers + i;
3173 StreamBuffer &dst = captureRequest->outputBuffers[i];
3174 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3175 buffer_handle_t buf = *(src->buffer);
3176 auto pair = getBufferId(buf, streamId);
3177 bool isNewBuffer = pair.first;
3178 dst.streamId = streamId;
3179 dst.bufferId = pair.second;
3180 dst.buffer = isNewBuffer ? buf : nullptr;
3181 dst.status = BufferStatus::OK;
3182 native_handle_t *acquireFence = nullptr;
3183 if (src->acquire_fence != -1) {
3184 acquireFence = native_handle_create(1,0);
3185 acquireFence->data[0] = src->acquire_fence;
3186 handlesCreated->push_back(acquireFence);
3187 }
3188 dst.acquireFence = acquireFence;
3189 dst.releaseFence = nullptr;
3190
3191 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3192 src->buffer, src->acquire_fence);
3193 }
3194 }
3195}
3196
3197status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3198 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3199 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3200 if (!valid()) return INVALID_OPERATION;
3201
3202 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3203 size_t batchSize = requests.size();
3204 captureRequests.resize(batchSize);
3205 std::vector<native_handle_t*> handlesCreated;
3206
3207 for (size_t i = 0; i < batchSize; i++) {
3208 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3209 }
3210
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003211 std::vector<device::V3_2::BufferCache> cachesToRemove;
3212 {
3213 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3214 for (auto& pair : mFreedBuffers) {
3215 // The stream might have been removed since onBufferFreed
3216 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3217 cachesToRemove.push_back({pair.first, pair.second});
3218 }
3219 }
3220 mFreedBuffers.clear();
3221 }
3222
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003223 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3224 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003225
3226 // Write metadata to FMQ.
3227 for (size_t i = 0; i < batchSize; i++) {
3228 camera3_capture_request_t* request = requests[i];
3229 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3230
3231 if (request->settings != nullptr) {
3232 size_t settingsSize = get_camera_metadata_size(request->settings);
3233 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3234 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3235 captureRequest->settings.resize(0);
3236 captureRequest->fmqSettingsSize = settingsSize;
3237 } else {
3238 if (mRequestMetadataQueue != nullptr) {
3239 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3240 }
3241 captureRequest->settings.setToExternal(
3242 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3243 get_camera_metadata_size(request->settings));
3244 captureRequest->fmqSettingsSize = 0u;
3245 }
3246 } else {
3247 // A null request settings maps to a size-0 CameraMetadata
3248 captureRequest->settings.resize(0);
3249 captureRequest->fmqSettingsSize = 0u;
3250 }
3251 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003252 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003253 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3254 status = s;
3255 *numRequestProcessed = n;
3256 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003257 if (!err.isOk()) {
3258 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3259 return DEAD_OBJECT;
3260 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003261 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3262 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3263 __FUNCTION__, *numRequestProcessed, batchSize);
3264 status = common::V1_0::Status::INTERNAL_ERROR;
3265 }
3266
3267 for (auto& handle : handlesCreated) {
3268 native_handle_delete(handle);
3269 }
3270 return CameraProviderManager::mapToStatusT(status);
3271}
3272
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003273status_t Camera3Device::HalInterface::processCaptureRequest(
3274 camera3_capture_request_t *request) {
3275 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003276 if (!valid()) return INVALID_OPERATION;
3277 status_t res = OK;
3278
3279 if (mHal3Device != nullptr) {
3280 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3281 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003282 uint32_t numRequestProcessed = 0;
3283 std::vector<camera3_capture_request_t*> requests(1);
3284 requests[0] = request;
3285 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003286 }
3287 return res;
3288}
3289
3290status_t Camera3Device::HalInterface::flush() {
3291 ATRACE_NAME("CameraHal::flush");
3292 if (!valid()) return INVALID_OPERATION;
3293 status_t res = OK;
3294
3295 if (mHal3Device != nullptr) {
3296 res = mHal3Device->ops->flush(mHal3Device);
3297 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003298 auto err = mHidlSession->flush();
3299 if (!err.isOk()) {
3300 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3301 res = DEAD_OBJECT;
3302 } else {
3303 res = CameraProviderManager::mapToStatusT(err);
3304 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003305 }
3306 return res;
3307}
3308
3309status_t Camera3Device::HalInterface::dump(int fd) {
3310 ATRACE_NAME("CameraHal::dump");
3311 if (!valid()) return INVALID_OPERATION;
3312 status_t res = OK;
3313
3314 if (mHal3Device != nullptr) {
3315 mHal3Device->ops->dump(mHal3Device, fd);
3316 } else {
3317 // Handled by CameraProviderManager::dump
3318 }
3319 return res;
3320}
3321
3322status_t Camera3Device::HalInterface::close() {
3323 ATRACE_NAME("CameraHal::close()");
3324 if (!valid()) return INVALID_OPERATION;
3325 status_t res = OK;
3326
3327 if (mHal3Device != nullptr) {
3328 mHal3Device->common.close(&mHal3Device->common);
3329 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003330 auto err = mHidlSession->close();
3331 // Interface will be dead shortly anyway, so don't log errors
3332 if (!err.isOk()) {
3333 res = DEAD_OBJECT;
3334 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003335 }
3336 return res;
3337}
3338
3339status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003340 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003341 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003342 auto pair = std::make_pair(buffer, acquireFence);
3343 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003344 return OK;
3345}
3346
3347status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003348 int32_t frameNumber, int32_t streamId,
3349 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003350 std::lock_guard<std::mutex> lock(mInflightLock);
3351
3352 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3353 auto it = mInflightBufferMap.find(key);
3354 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003355 auto pair = it->second;
3356 *buffer = pair.first;
3357 int acquireFence = pair.second;
3358 if (acquireFence > 0) {
3359 ::close(acquireFence);
3360 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003361 mInflightBufferMap.erase(it);
3362 return OK;
3363}
3364
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003365std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3366 const buffer_handle_t& buf, int streamId) {
3367 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3368
3369 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3370 auto it = bIdMap.find(buf);
3371 if (it == bIdMap.end()) {
3372 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003373 ALOGV("stream %d now have %zu buffer caches, buf %p",
3374 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003375 return std::make_pair(true, mNextBufferId - 1);
3376 } else {
3377 return std::make_pair(false, it->second);
3378 }
3379}
3380
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003381void Camera3Device::HalInterface::onBufferFreed(
3382 int streamId, const native_handle_t* handle) {
3383 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3384 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3385 auto mapIt = mBufferIdMaps.find(streamId);
3386 if (mapIt == mBufferIdMaps.end()) {
3387 // streamId might be from a deleted stream here
3388 ALOGI("%s: stream %d has been removed",
3389 __FUNCTION__, streamId);
3390 return;
3391 }
3392 BufferIdMap& bIdMap = mapIt->second;
3393 auto it = bIdMap.find(handle);
3394 if (it == bIdMap.end()) {
3395 ALOGW("%s: cannot find buffer %p in stream %d",
3396 __FUNCTION__, handle, streamId);
3397 return;
3398 } else {
3399 bufferId = it->second;
3400 bIdMap.erase(it);
3401 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3402 __FUNCTION__, streamId, bIdMap.size(), handle);
3403 }
3404 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3405}
3406
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003407/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003408 * RequestThread inner class methods
3409 */
3410
3411Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003412 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003413 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003414 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003415 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003416 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003417 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003418 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003419 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003420 mReconfigured(false),
3421 mDoPause(false),
3422 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003423 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003424 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003425 mCurrentAfTriggerId(0),
3426 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003427 mRepeatingLastFrameNumber(
3428 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003429 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003430 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003431}
3432
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003433Camera3Device::RequestThread::~RequestThread() {}
3434
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003435void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003436 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003437 Mutex::Autolock l(mRequestLock);
3438 mListener = listener;
3439}
3440
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003441void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003442 Mutex::Autolock l(mRequestLock);
3443 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003444 // Prepare video stream for high speed recording.
3445 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446}
3447
Jianing Wei90e59c92014-03-12 18:29:36 -07003448status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003449 List<sp<CaptureRequest> > &requests,
3450 /*out*/
3451 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003452 Mutex::Autolock l(mRequestLock);
3453 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3454 ++it) {
3455 mRequestQueue.push_back(*it);
3456 }
3457
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003458 if (lastFrameNumber != NULL) {
3459 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3460 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3461 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3462 *lastFrameNumber);
3463 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003464
Jianing Wei90e59c92014-03-12 18:29:36 -07003465 unpauseForNewRequests();
3466
3467 return OK;
3468}
3469
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003470
3471status_t Camera3Device::RequestThread::queueTrigger(
3472 RequestTrigger trigger[],
3473 size_t count) {
3474
3475 Mutex::Autolock l(mTriggerMutex);
3476 status_t ret;
3477
3478 for (size_t i = 0; i < count; ++i) {
3479 ret = queueTriggerLocked(trigger[i]);
3480
3481 if (ret != OK) {
3482 return ret;
3483 }
3484 }
3485
3486 return OK;
3487}
3488
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003489const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3490 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003491 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492 if (d != nullptr) return d->mId;
3493 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003494}
3495
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003496status_t Camera3Device::RequestThread::queueTriggerLocked(
3497 RequestTrigger trigger) {
3498
3499 uint32_t tag = trigger.metadataTag;
3500 ssize_t index = mTriggerMap.indexOfKey(tag);
3501
3502 switch (trigger.getTagType()) {
3503 case TYPE_BYTE:
3504 // fall-through
3505 case TYPE_INT32:
3506 break;
3507 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003508 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3509 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003510 return INVALID_OPERATION;
3511 }
3512
3513 /**
3514 * Collect only the latest trigger, since we only have 1 field
3515 * in the request settings per trigger tag, and can't send more than 1
3516 * trigger per request.
3517 */
3518 if (index != NAME_NOT_FOUND) {
3519 mTriggerMap.editValueAt(index) = trigger;
3520 } else {
3521 mTriggerMap.add(tag, trigger);
3522 }
3523
3524 return OK;
3525}
3526
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003527status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003528 const RequestList &requests,
3529 /*out*/
3530 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003531 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003532 if (lastFrameNumber != NULL) {
3533 *lastFrameNumber = mRepeatingLastFrameNumber;
3534 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003535 mRepeatingRequests.clear();
3536 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3537 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003538
3539 unpauseForNewRequests();
3540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003542 return OK;
3543}
3544
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003545bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003546 if (mRepeatingRequests.empty()) {
3547 return false;
3548 }
3549 int32_t requestId = requestIn->mResultExtras.requestId;
3550 const RequestList &repeatRequests = mRepeatingRequests;
3551 // All repeating requests are guaranteed to have same id so only check first quest
3552 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3553 return (firstRequest->mResultExtras.requestId == requestId);
3554}
3555
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003556status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003557 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003558 return clearRepeatingRequestsLocked(lastFrameNumber);
3559
3560}
3561
3562status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003563 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003564 if (lastFrameNumber != NULL) {
3565 *lastFrameNumber = mRepeatingLastFrameNumber;
3566 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003567 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003568 return OK;
3569}
3570
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003571status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003572 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003573 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003574 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003575
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003576 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003577
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003578 // Send errors for all requests pending in the request queue, including
3579 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003580 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003581 if (listener != NULL) {
3582 for (RequestList::iterator it = mRequestQueue.begin();
3583 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003584 // Abort the input buffers for reprocess requests.
3585 if ((*it)->mInputStream != NULL) {
3586 camera3_stream_buffer_t inputBuffer;
3587 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3588 if (res != OK) {
3589 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3590 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3591 } else {
3592 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3593 if (res != OK) {
3594 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3595 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3596 }
3597 }
3598 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003599 // Set the frame number this request would have had, if it
3600 // had been submitted; this frame number will not be reused.
3601 // The requestId and burstId fields were set when the request was
3602 // submitted originally (in convertMetadataListToRequestListLocked)
3603 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003604 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003605 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003606 }
3607 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003608 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003609
3610 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003611 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003612 if (lastFrameNumber != NULL) {
3613 *lastFrameNumber = mRepeatingLastFrameNumber;
3614 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003615 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003616 return OK;
3617}
3618
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003619status_t Camera3Device::RequestThread::flush() {
3620 ATRACE_CALL();
3621 Mutex::Autolock l(mFlushLock);
3622
Emilian Peev08dd2452017-04-06 16:55:14 +01003623 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003624}
3625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003626void Camera3Device::RequestThread::setPaused(bool paused) {
3627 Mutex::Autolock l(mPauseLock);
3628 mDoPause = paused;
3629 mDoPauseSignal.signal();
3630}
3631
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003632status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3633 int32_t requestId, nsecs_t timeout) {
3634 Mutex::Autolock l(mLatestRequestMutex);
3635 status_t res;
3636 while (mLatestRequestId != requestId) {
3637 nsecs_t startTime = systemTime();
3638
3639 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3640 if (res != OK) return res;
3641
3642 timeout -= (systemTime() - startTime);
3643 }
3644
3645 return OK;
3646}
3647
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003648void Camera3Device::RequestThread::requestExit() {
3649 // Call parent to set up shutdown
3650 Thread::requestExit();
3651 // The exit from any possible waits
3652 mDoPauseSignal.signal();
3653 mRequestSignal.signal();
3654}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003655
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003656void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003657 bool surfaceAbandoned = false;
3658 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003659 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003660 {
3661 Mutex::Autolock l(mRequestLock);
3662 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3663 // repeating requests.
3664 for (const auto& request : mRepeatingRequests) {
3665 for (const auto& s : request->mOutputStreams) {
3666 if (s->isAbandoned()) {
3667 surfaceAbandoned = true;
3668 clearRepeatingRequestsLocked(&lastFrameNumber);
3669 break;
3670 }
3671 }
3672 if (surfaceAbandoned) {
3673 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003674 }
3675 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003676 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003677 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003678
3679 if (listener != NULL && surfaceAbandoned) {
3680 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003681 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003682}
3683
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003684bool Camera3Device::RequestThread::sendRequestsBatch() {
3685 status_t res;
3686 size_t batchSize = mNextRequests.size();
3687 std::vector<camera3_capture_request_t*> requests(batchSize);
3688 uint32_t numRequestProcessed = 0;
3689 for (size_t i = 0; i < batchSize; i++) {
3690 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3691 }
3692
3693 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3694 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3695
3696 bool triggerRemoveFailed = false;
3697 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3698 for (size_t i = 0; i < numRequestProcessed; i++) {
3699 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3700 nextRequest.submitted = true;
3701
3702
3703 // Update the latest request sent to HAL
3704 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3705 Mutex::Autolock al(mLatestRequestMutex);
3706
3707 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3708 mLatestRequest.acquire(cloned);
3709
3710 sp<Camera3Device> parent = mParent.promote();
3711 if (parent != NULL) {
3712 parent->monitorMetadata(TagMonitor::REQUEST,
3713 nextRequest.halRequest.frame_number,
3714 0, mLatestRequest);
3715 }
3716 }
3717
3718 if (nextRequest.halRequest.settings != NULL) {
3719 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3720 }
3721
3722 if (!triggerRemoveFailed) {
3723 // Remove any previously queued triggers (after unlock)
3724 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3725 if (removeTriggerRes != OK) {
3726 triggerRemoveFailed = true;
3727 triggerFailedRequest = nextRequest;
3728 }
3729 }
3730 }
3731
3732 if (triggerRemoveFailed) {
3733 SET_ERR("RequestThread: Unable to remove triggers "
3734 "(capture request %d, HAL device: %s (%d)",
3735 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3736 cleanUpFailedRequests(/*sendRequestError*/ false);
3737 return false;
3738 }
3739
3740 if (res != OK) {
3741 // Should only get a failure here for malformed requests or device-level
3742 // errors, so consider all errors fatal. Bad metadata failures should
3743 // come through notify.
3744 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3745 mNextRequests[numRequestProcessed].halRequest.frame_number,
3746 strerror(-res), res);
3747 cleanUpFailedRequests(/*sendRequestError*/ false);
3748 return false;
3749 }
3750 return true;
3751}
3752
3753bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3754 status_t res;
3755
3756 for (auto& nextRequest : mNextRequests) {
3757 // Submit request and block until ready for next one
3758 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3759 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3760
3761 if (res != OK) {
3762 // Should only get a failure here for malformed requests or device-level
3763 // errors, so consider all errors fatal. Bad metadata failures should
3764 // come through notify.
3765 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3766 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3767 res);
3768 cleanUpFailedRequests(/*sendRequestError*/ false);
3769 return false;
3770 }
3771
3772 // Mark that the request has be submitted successfully.
3773 nextRequest.submitted = true;
3774
3775 // Update the latest request sent to HAL
3776 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3777 Mutex::Autolock al(mLatestRequestMutex);
3778
3779 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3780 mLatestRequest.acquire(cloned);
3781
3782 sp<Camera3Device> parent = mParent.promote();
3783 if (parent != NULL) {
3784 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3785 0, mLatestRequest);
3786 }
3787 }
3788
3789 if (nextRequest.halRequest.settings != NULL) {
3790 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3791 }
3792
3793 // Remove any previously queued triggers (after unlock)
3794 res = removeTriggers(mPrevRequest);
3795 if (res != OK) {
3796 SET_ERR("RequestThread: Unable to remove triggers "
3797 "(capture request %d, HAL device: %s (%d)",
3798 nextRequest.halRequest.frame_number, strerror(-res), res);
3799 cleanUpFailedRequests(/*sendRequestError*/ false);
3800 return false;
3801 }
3802 }
3803 return true;
3804}
3805
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003806bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003807 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003808 status_t res;
3809
3810 // Handle paused state.
3811 if (waitIfPaused()) {
3812 return true;
3813 }
3814
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003815 // Wait for the next batch of requests.
3816 waitForNextRequestBatch();
3817 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003818 return true;
3819 }
3820
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003821 // Get the latest request ID, if any
3822 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003823 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003824 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003825 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003826 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003827 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003828 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3829 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003830 }
3831
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003832 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003833 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003834 if (res == TIMED_OUT) {
3835 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003836 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003837 // Check if any stream is abandoned.
3838 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003839 return true;
3840 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003841 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003842 return false;
3843 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003844
Zhijun Hecc27e112013-10-03 16:12:43 -07003845 // Inform waitUntilRequestProcessed thread of a new request ID
3846 {
3847 Mutex::Autolock al(mLatestRequestMutex);
3848
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003849 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003850 mLatestRequestSignal.signal();
3851 }
3852
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003853 // Submit a batch of requests to HAL.
3854 // Use flush lock only when submitting multilple requests in a batch.
3855 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3856 // which may take a long time to finish so synchronizing flush() and
3857 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3858 // For now, only synchronize for high speed recording and we should figure something out for
3859 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003860 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003861
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003862 if (useFlushLock) {
3863 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003864 }
3865
Zhijun Hef0645c12016-08-02 00:58:11 -07003866 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003867 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003868
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003869 bool submitRequestSuccess = false;
3870 if (mInterface->supportBatchRequest()) {
3871 submitRequestSuccess = sendRequestsBatch();
3872 } else {
3873 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003874 }
3875
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003876 if (useFlushLock) {
3877 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003878 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003879
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003880 // Unset as current request
3881 {
3882 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003883 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003884 }
3885
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003886 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003887}
3888
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003889status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003890 ATRACE_CALL();
3891
Shuzhen Wang4a472662017-02-26 23:29:04 -08003892 for (size_t i = 0; i < mNextRequests.size(); i++) {
3893 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003894 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3895 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3896 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3897
3898 // Prepare a request to HAL
3899 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3900
3901 // Insert any queued triggers (before metadata is locked)
3902 status_t res = insertTriggers(captureRequest);
3903
3904 if (res < 0) {
3905 SET_ERR("RequestThread: Unable to insert triggers "
3906 "(capture request %d, HAL device: %s (%d)",
3907 halRequest->frame_number, strerror(-res), res);
3908 return INVALID_OPERATION;
3909 }
3910 int triggerCount = res;
3911 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3912 mPrevTriggers = triggerCount;
3913
3914 // If the request is the same as last, or we had triggers last time
3915 if (mPrevRequest != captureRequest || triggersMixedIn) {
3916 /**
3917 * HAL workaround:
3918 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3919 */
3920 res = addDummyTriggerIds(captureRequest);
3921 if (res != OK) {
3922 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3923 "(capture request %d, HAL device: %s (%d)",
3924 halRequest->frame_number, strerror(-res), res);
3925 return INVALID_OPERATION;
3926 }
3927
3928 /**
3929 * The request should be presorted so accesses in HAL
3930 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3931 */
3932 captureRequest->mSettings.sort();
3933 halRequest->settings = captureRequest->mSettings.getAndLock();
3934 mPrevRequest = captureRequest;
3935 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3936
3937 IF_ALOGV() {
3938 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3939 find_camera_metadata_ro_entry(
3940 halRequest->settings,
3941 ANDROID_CONTROL_AF_TRIGGER,
3942 &e
3943 );
3944 if (e.count > 0) {
3945 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3946 __FUNCTION__,
3947 halRequest->frame_number,
3948 e.data.u8[0]);
3949 }
3950 }
3951 } else {
3952 // leave request.settings NULL to indicate 'reuse latest given'
3953 ALOGVV("%s: Request settings are REUSED",
3954 __FUNCTION__);
3955 }
3956
3957 uint32_t totalNumBuffers = 0;
3958
3959 // Fill in buffers
3960 if (captureRequest->mInputStream != NULL) {
3961 halRequest->input_buffer = &captureRequest->mInputBuffer;
3962 totalNumBuffers += 1;
3963 } else {
3964 halRequest->input_buffer = NULL;
3965 }
3966
3967 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3968 captureRequest->mOutputStreams.size());
3969 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08003970 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
3971 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003972
3973 // Prepare video buffers for high speed recording on the first video request.
3974 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3975 // Only try to prepare video stream on the first video request.
3976 mPrepareVideoStream = false;
3977
3978 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3979 while (res == NOT_ENOUGH_DATA) {
3980 res = outputStream->prepareNextBuffer();
3981 }
3982 if (res != OK) {
3983 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3984 __FUNCTION__, strerror(-res), res);
3985 outputStream->cancelPrepare();
3986 }
3987 }
3988
Shuzhen Wang4a472662017-02-26 23:29:04 -08003989 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3990 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003991 if (res != OK) {
3992 // Can't get output buffer from gralloc queue - this could be due to
3993 // abandoned queue or other consumer misbehavior, so not a fatal
3994 // error
3995 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3996 " %s (%d)", strerror(-res), res);
3997
3998 return TIMED_OUT;
3999 }
4000 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004001
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004002 }
4003 totalNumBuffers += halRequest->num_output_buffers;
4004
4005 // Log request in the in-flight queue
4006 sp<Camera3Device> parent = mParent.promote();
4007 if (parent == NULL) {
4008 // Should not happen, and nowhere to send errors to, so just log it
4009 CLOGE("RequestThread: Parent is gone");
4010 return INVALID_OPERATION;
4011 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004012
4013 // If this request list is for constrained high speed recording (not
4014 // preview), and the current request is not the last one in the batch,
4015 // do not send callback to the app.
4016 bool hasCallback = true;
4017 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4018 hasCallback = false;
4019 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004020 res = parent->registerInFlight(halRequest->frame_number,
4021 totalNumBuffers, captureRequest->mResultExtras,
4022 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004023 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004024 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4025 ", burstId = %" PRId32 ".",
4026 __FUNCTION__,
4027 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4028 captureRequest->mResultExtras.burstId);
4029 if (res != OK) {
4030 SET_ERR("RequestThread: Unable to register new in-flight request:"
4031 " %s (%d)", strerror(-res), res);
4032 return INVALID_OPERATION;
4033 }
4034 }
4035
4036 return OK;
4037}
4038
Igor Murashkin1e479c02013-09-06 16:55:14 -07004039CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4040 Mutex::Autolock al(mLatestRequestMutex);
4041
4042 ALOGV("RequestThread::%s", __FUNCTION__);
4043
4044 return mLatestRequest;
4045}
4046
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004047bool Camera3Device::RequestThread::isStreamPending(
4048 sp<Camera3StreamInterface>& stream) {
4049 Mutex::Autolock l(mRequestLock);
4050
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004051 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004052 if (!nextRequest.submitted) {
4053 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4054 if (stream == s) return true;
4055 }
4056 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004057 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004058 }
4059
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004060 for (const auto& request : mRequestQueue) {
4061 for (const auto& s : request->mOutputStreams) {
4062 if (stream == s) return true;
4063 }
4064 if (stream == request->mInputStream) return true;
4065 }
4066
4067 for (const auto& request : mRepeatingRequests) {
4068 for (const auto& s : request->mOutputStreams) {
4069 if (stream == s) return true;
4070 }
4071 if (stream == request->mInputStream) return true;
4072 }
4073
4074 return false;
4075}
Jianing Weicb0652e2014-03-12 18:29:36 -07004076
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004077void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4078 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004079 return;
4080 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004081
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004082 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 // Skip the ones that have been submitted successfully.
4084 if (nextRequest.submitted) {
4085 continue;
4086 }
4087
4088 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4089 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4090 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4091
4092 if (halRequest->settings != NULL) {
4093 captureRequest->mSettings.unlock(halRequest->settings);
4094 }
4095
4096 if (captureRequest->mInputStream != NULL) {
4097 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4098 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4099 }
4100
4101 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004102 //Buffers that failed processing could still have
4103 //valid acquire fence.
4104 int acquireFence = (*outputBuffers)[i].acquire_fence;
4105 if (0 <= acquireFence) {
4106 close(acquireFence);
4107 outputBuffers->editItemAt(i).acquire_fence = -1;
4108 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004109 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4110 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4111 }
4112
4113 if (sendRequestError) {
4114 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004115 sp<NotificationListener> listener = mListener.promote();
4116 if (listener != NULL) {
4117 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004118 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004119 captureRequest->mResultExtras);
4120 }
4121 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004122
4123 // Remove yet-to-be submitted inflight request from inflightMap
4124 {
4125 sp<Camera3Device> parent = mParent.promote();
4126 if (parent != NULL) {
4127 Mutex::Autolock l(parent->mInFlightLock);
4128 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4129 if (idx >= 0) {
4130 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4131 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4132 parent->removeInFlightMapEntryLocked(idx);
4133 }
4134 }
4135 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004136 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004137
4138 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004139 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004140}
4141
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004142void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004143 // Optimized a bit for the simple steady-state case (single repeating
4144 // request), to avoid putting that request in the queue temporarily.
4145 Mutex::Autolock l(mRequestLock);
4146
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004147 assert(mNextRequests.empty());
4148
4149 NextRequest nextRequest;
4150 nextRequest.captureRequest = waitForNextRequestLocked();
4151 if (nextRequest.captureRequest == nullptr) {
4152 return;
4153 }
4154
4155 nextRequest.halRequest = camera3_capture_request_t();
4156 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004157 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004158
4159 // Wait for additional requests
4160 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4161
4162 for (size_t i = 1; i < batchSize; i++) {
4163 NextRequest additionalRequest;
4164 additionalRequest.captureRequest = waitForNextRequestLocked();
4165 if (additionalRequest.captureRequest == nullptr) {
4166 break;
4167 }
4168
4169 additionalRequest.halRequest = camera3_capture_request_t();
4170 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004171 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004172 }
4173
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004174 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004175 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004176 mNextRequests.size(), batchSize);
4177 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004178 }
4179
4180 return;
4181}
4182
4183sp<Camera3Device::CaptureRequest>
4184 Camera3Device::RequestThread::waitForNextRequestLocked() {
4185 status_t res;
4186 sp<CaptureRequest> nextRequest;
4187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004188 while (mRequestQueue.empty()) {
4189 if (!mRepeatingRequests.empty()) {
4190 // Always atomically enqueue all requests in a repeating request
4191 // list. Guarantees a complete in-sequence set of captures to
4192 // application.
4193 const RequestList &requests = mRepeatingRequests;
4194 RequestList::const_iterator firstRequest =
4195 requests.begin();
4196 nextRequest = *firstRequest;
4197 mRequestQueue.insert(mRequestQueue.end(),
4198 ++firstRequest,
4199 requests.end());
4200 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004201
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004202 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004203
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004204 break;
4205 }
4206
4207 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4208
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004209 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4210 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004211 Mutex::Autolock pl(mPauseLock);
4212 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004213 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004215 // Let the tracker know
4216 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4217 if (statusTracker != 0) {
4218 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4219 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220 }
4221 // Stop waiting for now and let thread management happen
4222 return NULL;
4223 }
4224 }
4225
4226 if (nextRequest == NULL) {
4227 // Don't have a repeating request already in hand, so queue
4228 // must have an entry now.
4229 RequestList::iterator firstRequest =
4230 mRequestQueue.begin();
4231 nextRequest = *firstRequest;
4232 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004233 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4234 sp<NotificationListener> listener = mListener.promote();
4235 if (listener != NULL) {
4236 listener->notifyRequestQueueEmpty();
4237 }
4238 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004239 }
4240
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004241 // In case we've been unpaused by setPaused clearing mDoPause, need to
4242 // update internal pause state (capture/setRepeatingRequest unpause
4243 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004244 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004245 if (mPaused) {
4246 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4247 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4248 if (statusTracker != 0) {
4249 statusTracker->markComponentActive(mStatusId);
4250 }
4251 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004252 mPaused = false;
4253
4254 // Check if we've reconfigured since last time, and reset the preview
4255 // request if so. Can't use 'NULL request == repeat' across configure calls.
4256 if (mReconfigured) {
4257 mPrevRequest.clear();
4258 mReconfigured = false;
4259 }
4260
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004261 if (nextRequest != NULL) {
4262 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004263 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4264 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004265
4266 // Since RequestThread::clear() removes buffers from the input stream,
4267 // get the right buffer here before unlocking mRequestLock
4268 if (nextRequest->mInputStream != NULL) {
4269 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4270 if (res != OK) {
4271 // Can't get input buffer from gralloc queue - this could be due to
4272 // disconnected queue or other producer misbehavior, so not a fatal
4273 // error
4274 ALOGE("%s: Can't get input buffer, skipping request:"
4275 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004276
4277 sp<NotificationListener> listener = mListener.promote();
4278 if (listener != NULL) {
4279 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004280 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004281 nextRequest->mResultExtras);
4282 }
4283 return NULL;
4284 }
4285 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004286 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004287
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004288 return nextRequest;
4289}
4290
4291bool Camera3Device::RequestThread::waitIfPaused() {
4292 status_t res;
4293 Mutex::Autolock l(mPauseLock);
4294 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 if (mPaused == false) {
4296 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4298 // Let the tracker know
4299 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4300 if (statusTracker != 0) {
4301 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004303 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004305 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004306 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004307 return true;
4308 }
4309 }
4310 // We don't set mPaused to false here, because waitForNextRequest needs
4311 // to further manage the paused state in case of starvation.
4312 return false;
4313}
4314
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004315void Camera3Device::RequestThread::unpauseForNewRequests() {
4316 // With work to do, mark thread as unpaused.
4317 // If paused by request (setPaused), don't resume, to avoid
4318 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004319 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004320 Mutex::Autolock p(mPauseLock);
4321 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004322 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4323 if (mPaused) {
4324 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4325 if (statusTracker != 0) {
4326 statusTracker->markComponentActive(mStatusId);
4327 }
4328 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004329 mPaused = false;
4330 }
4331}
4332
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004333void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4334 sp<Camera3Device> parent = mParent.promote();
4335 if (parent != NULL) {
4336 va_list args;
4337 va_start(args, fmt);
4338
4339 parent->setErrorStateV(fmt, args);
4340
4341 va_end(args);
4342 }
4343}
4344
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004345status_t Camera3Device::RequestThread::insertTriggers(
4346 const sp<CaptureRequest> &request) {
4347
4348 Mutex::Autolock al(mTriggerMutex);
4349
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004350 sp<Camera3Device> parent = mParent.promote();
4351 if (parent == NULL) {
4352 CLOGE("RequestThread: Parent is gone");
4353 return DEAD_OBJECT;
4354 }
4355
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004356 CameraMetadata &metadata = request->mSettings;
4357 size_t count = mTriggerMap.size();
4358
4359 for (size_t i = 0; i < count; ++i) {
4360 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004361 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004362
4363 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4364 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4365 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004366 if (isAeTrigger) {
4367 request->mResultExtras.precaptureTriggerId = triggerId;
4368 mCurrentPreCaptureTriggerId = triggerId;
4369 } else {
4370 request->mResultExtras.afTriggerId = triggerId;
4371 mCurrentAfTriggerId = triggerId;
4372 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004373 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004374 }
4375
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004376 camera_metadata_entry entry = metadata.find(tag);
4377
4378 if (entry.count > 0) {
4379 /**
4380 * Already has an entry for this trigger in the request.
4381 * Rewrite it with our requested trigger value.
4382 */
4383 RequestTrigger oldTrigger = trigger;
4384
4385 oldTrigger.entryValue = entry.data.u8[0];
4386
4387 mTriggerReplacedMap.add(tag, oldTrigger);
4388 } else {
4389 /**
4390 * More typical, no trigger entry, so we just add it
4391 */
4392 mTriggerRemovedMap.add(tag, trigger);
4393 }
4394
4395 status_t res;
4396
4397 switch (trigger.getTagType()) {
4398 case TYPE_BYTE: {
4399 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4400 res = metadata.update(tag,
4401 &entryValue,
4402 /*count*/1);
4403 break;
4404 }
4405 case TYPE_INT32:
4406 res = metadata.update(tag,
4407 &trigger.entryValue,
4408 /*count*/1);
4409 break;
4410 default:
4411 ALOGE("%s: Type not supported: 0x%x",
4412 __FUNCTION__,
4413 trigger.getTagType());
4414 return INVALID_OPERATION;
4415 }
4416
4417 if (res != OK) {
4418 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4419 ", value %d", __FUNCTION__, trigger.getTagName(),
4420 trigger.entryValue);
4421 return res;
4422 }
4423
4424 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4425 trigger.getTagName(),
4426 trigger.entryValue);
4427 }
4428
4429 mTriggerMap.clear();
4430
4431 return count;
4432}
4433
4434status_t Camera3Device::RequestThread::removeTriggers(
4435 const sp<CaptureRequest> &request) {
4436 Mutex::Autolock al(mTriggerMutex);
4437
4438 CameraMetadata &metadata = request->mSettings;
4439
4440 /**
4441 * Replace all old entries with their old values.
4442 */
4443 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4444 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4445
4446 status_t res;
4447
4448 uint32_t tag = trigger.metadataTag;
4449 switch (trigger.getTagType()) {
4450 case TYPE_BYTE: {
4451 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4452 res = metadata.update(tag,
4453 &entryValue,
4454 /*count*/1);
4455 break;
4456 }
4457 case TYPE_INT32:
4458 res = metadata.update(tag,
4459 &trigger.entryValue,
4460 /*count*/1);
4461 break;
4462 default:
4463 ALOGE("%s: Type not supported: 0x%x",
4464 __FUNCTION__,
4465 trigger.getTagType());
4466 return INVALID_OPERATION;
4467 }
4468
4469 if (res != OK) {
4470 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4471 ", trigger value %d", __FUNCTION__,
4472 trigger.getTagName(), trigger.entryValue);
4473 return res;
4474 }
4475 }
4476 mTriggerReplacedMap.clear();
4477
4478 /**
4479 * Remove all new entries.
4480 */
4481 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4482 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4483 status_t res = metadata.erase(trigger.metadataTag);
4484
4485 if (res != OK) {
4486 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4487 ", trigger value %d", __FUNCTION__,
4488 trigger.getTagName(), trigger.entryValue);
4489 return res;
4490 }
4491 }
4492 mTriggerRemovedMap.clear();
4493
4494 return OK;
4495}
4496
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004497status_t Camera3Device::RequestThread::addDummyTriggerIds(
4498 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004499 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004500 static const int32_t dummyTriggerId = 1;
4501 status_t res;
4502
4503 CameraMetadata &metadata = request->mSettings;
4504
4505 // If AF trigger is active, insert a dummy AF trigger ID if none already
4506 // exists
4507 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4508 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4509 if (afTrigger.count > 0 &&
4510 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4511 afId.count == 0) {
4512 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4513 if (res != OK) return res;
4514 }
4515
4516 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4517 // if none already exists
4518 camera_metadata_entry pcTrigger =
4519 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4520 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4521 if (pcTrigger.count > 0 &&
4522 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4523 pcId.count == 0) {
4524 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4525 &dummyTriggerId, 1);
4526 if (res != OK) return res;
4527 }
4528
4529 return OK;
4530}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004531
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004532/**
4533 * PreparerThread inner class methods
4534 */
4535
4536Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004537 Thread(/*canCallJava*/false), mListener(nullptr),
4538 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004539}
4540
4541Camera3Device::PreparerThread::~PreparerThread() {
4542 Thread::requestExitAndWait();
4543 if (mCurrentStream != nullptr) {
4544 mCurrentStream->cancelPrepare();
4545 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4546 mCurrentStream.clear();
4547 }
4548 clear();
4549}
4550
Ruben Brunkc78ac262015-08-13 17:58:46 -07004551status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004552 status_t res;
4553
4554 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004555 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004556
Ruben Brunkc78ac262015-08-13 17:58:46 -07004557 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004558 if (res == OK) {
4559 // No preparation needed, fire listener right off
4560 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004561 if (listener != NULL) {
4562 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004563 }
4564 return OK;
4565 } else if (res != NOT_ENOUGH_DATA) {
4566 return res;
4567 }
4568
4569 // Need to prepare, start up thread if necessary
4570 if (!mActive) {
4571 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4572 // isn't running
4573 Thread::requestExitAndWait();
4574 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4575 if (res != OK) {
4576 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004577 if (listener != NULL) {
4578 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004579 }
4580 return res;
4581 }
4582 mCancelNow = false;
4583 mActive = true;
4584 ALOGV("%s: Preparer stream started", __FUNCTION__);
4585 }
4586
4587 // queue up the work
4588 mPendingStreams.push_back(stream);
4589 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4590
4591 return OK;
4592}
4593
4594status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004595 Mutex::Autolock l(mLock);
4596
4597 for (const auto& stream : mPendingStreams) {
4598 stream->cancelPrepare();
4599 }
4600 mPendingStreams.clear();
4601 mCancelNow = true;
4602
4603 return OK;
4604}
4605
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004606void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004607 Mutex::Autolock l(mLock);
4608 mListener = listener;
4609}
4610
4611bool Camera3Device::PreparerThread::threadLoop() {
4612 status_t res;
4613 {
4614 Mutex::Autolock l(mLock);
4615 if (mCurrentStream == nullptr) {
4616 // End thread if done with work
4617 if (mPendingStreams.empty()) {
4618 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4619 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4620 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4621 mActive = false;
4622 return false;
4623 }
4624
4625 // Get next stream to prepare
4626 auto it = mPendingStreams.begin();
4627 mCurrentStream = *it;
4628 mPendingStreams.erase(it);
4629 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4630 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4631 } else if (mCancelNow) {
4632 mCurrentStream->cancelPrepare();
4633 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4634 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4635 mCurrentStream.clear();
4636 mCancelNow = false;
4637 return true;
4638 }
4639 }
4640
4641 res = mCurrentStream->prepareNextBuffer();
4642 if (res == NOT_ENOUGH_DATA) return true;
4643 if (res != OK) {
4644 // Something bad happened; try to recover by cancelling prepare and
4645 // signalling listener anyway
4646 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4647 mCurrentStream->getId(), res, strerror(-res));
4648 mCurrentStream->cancelPrepare();
4649 }
4650
4651 // This stream has finished, notify listener
4652 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004653 sp<NotificationListener> listener = mListener.promote();
4654 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004655 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4656 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004657 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004658 }
4659
4660 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4661 mCurrentStream.clear();
4662
4663 return true;
4664}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004666/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004667 * Static callback forwarding methods from HAL to instance
4668 */
4669
4670void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4671 const camera3_capture_result *result) {
4672 Camera3Device *d =
4673 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004674
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004675 d->processCaptureResult(result);
4676}
4677
4678void Camera3Device::sNotify(const camera3_callback_ops *cb,
4679 const camera3_notify_msg *msg) {
4680 Camera3Device *d =
4681 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4682 d->notify(msg);
4683}
4684
4685}; // namespace android