blob: 4571db8c5c51cc785f66744b554f184062a57f89 [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
2363 // Check if it's okay to remove the request from InFlightMap:
2364 // In the case of a successful request:
2365 // all input and output buffers, all result metadata, shutter callback
2366 // arrived.
2367 // In the case of a unsuccessful request:
2368 // all input and output buffers arrived.
2369 if (request.numBuffersLeft == 0 &&
2370 (request.requestStatus != OK ||
2371 (request.haveResultMetadata && shutterTimestamp != 0))) {
2372 ATRACE_ASYNC_END("frame capture", frameNumber);
2373
Shuzhen Wang403044a2017-02-26 23:29:04 -08002374 // Sanity check - if sensor timestamp matches shutter timestamp in the
2375 // case of request having callback.
2376 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002377 sensorTimestamp != shutterTimestamp) {
2378 SET_ERR("sensor timestamp (%" PRId64
2379 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2380 sensorTimestamp, frameNumber, shutterTimestamp);
2381 }
2382
2383 // for an unsuccessful request, it may have pending output buffers to
2384 // return.
2385 assert(request.requestStatus != OK ||
2386 request.pendingOutputBuffers.size() == 0);
2387 returnOutputBuffers(request.pendingOutputBuffers.array(),
2388 request.pendingOutputBuffers.size(), 0);
2389
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002390 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002391 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2392 }
2393
2394 // Sanity check - if we have too many in-flight frames, something has
2395 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002396 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002397 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002398 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2399 kInFlightWarnLimitHighSpeed) {
2400 CLOGE("In-flight list too large for high speed configuration: %zu",
2401 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002402 }
2403}
2404
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002405void Camera3Device::insertResultLocked(CaptureResult *result,
2406 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002407 if (result == nullptr) return;
2408
Emilian Peev71c73a22017-03-21 16:35:51 +00002409 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2410 result->mMetadata.getAndLock());
2411 set_camera_metadata_vendor_id(meta, mVendorTagId);
2412 result->mMetadata.unlock(meta);
2413
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002414 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2415 (int32_t*)&frameNumber, 1) != OK) {
2416 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2417 return;
2418 }
2419
2420 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2421 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2422 return;
2423 }
2424
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002425 // Valid result, insert into queue
2426 List<CaptureResult>::iterator queuedResult =
2427 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2428 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2429 ", burstId = %" PRId32, __FUNCTION__,
2430 queuedResult->mResultExtras.requestId,
2431 queuedResult->mResultExtras.frameNumber,
2432 queuedResult->mResultExtras.burstId);
2433
2434 mResultSignal.signal();
2435}
2436
2437
2438void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002439 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002440 Mutex::Autolock l(mOutputLock);
2441
2442 CaptureResult captureResult;
2443 captureResult.mResultExtras = resultExtras;
2444 captureResult.mMetadata = partialResult;
2445
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002446 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002447}
2448
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002449
2450void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2451 CaptureResultExtras &resultExtras,
2452 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002453 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002454 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002455 if (pendingMetadata.isEmpty())
2456 return;
2457
2458 Mutex::Autolock l(mOutputLock);
2459
2460 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002461 if (reprocess) {
2462 if (frameNumber < mNextReprocessResultFrameNumber) {
2463 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002464 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002465 frameNumber, mNextReprocessResultFrameNumber);
2466 return;
2467 }
2468 mNextReprocessResultFrameNumber = frameNumber + 1;
2469 } else {
2470 if (frameNumber < mNextResultFrameNumber) {
2471 SET_ERR("Out-of-order capture result metadata submitted! "
2472 "(got frame number %d, expecting %d)",
2473 frameNumber, mNextResultFrameNumber);
2474 return;
2475 }
2476 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002477 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002478
2479 CaptureResult captureResult;
2480 captureResult.mResultExtras = resultExtras;
2481 captureResult.mMetadata = pendingMetadata;
2482
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002483 // Append any previous partials to form a complete result
2484 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2485 captureResult.mMetadata.append(collectedPartialResult);
2486 }
2487
2488 captureResult.mMetadata.sort();
2489
2490 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002491 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2492 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002493 SET_ERR("No timestamp provided by HAL for frame %d!",
2494 frameNumber);
2495 return;
2496 }
2497
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002498 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2499 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2500
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002501 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002502}
2503
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002504/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002505 * Camera HAL device callback methods
2506 */
2507
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002508void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002509 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002510
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002511 status_t res;
2512
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002513 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002514 if (result->result == NULL && result->num_output_buffers == 0 &&
2515 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002516 SET_ERR("No result data provided by HAL for frame %d",
2517 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002518 return;
2519 }
Zhijun He204e3292014-07-14 17:09:23 -07002520
Zhijun He204e3292014-07-14 17:09:23 -07002521 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002522 result->result != NULL &&
2523 result->partial_result != 1) {
2524 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2525 " if partial result is not supported",
2526 frameNumber, result->partial_result);
2527 return;
2528 }
2529
2530 bool isPartialResult = false;
2531 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002532 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002533 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002534
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002535 // Get shutter timestamp and resultExtras from list of in-flight requests,
2536 // where it was added by the shutter notification for this frame. If the
2537 // shutter timestamp isn't received yet, append the output buffers to the
2538 // in-flight request and they will be returned when the shutter timestamp
2539 // arrives. Update the in-flight status and remove the in-flight entry if
2540 // all result data and shutter timestamp have been received.
2541 nsecs_t shutterTimestamp = 0;
2542
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002543 {
2544 Mutex::Autolock l(mInFlightLock);
2545 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2546 if (idx == NAME_NOT_FOUND) {
2547 SET_ERR("Unknown frame number for capture result: %d",
2548 frameNumber);
2549 return;
2550 }
2551 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002552 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2553 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002554 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002555 __FUNCTION__, request.resultExtras.requestId,
2556 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002557 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002558 // Always update the partial count to the latest one if it's not 0
2559 // (buffers only). When framework aggregates adjacent partial results
2560 // into one, the latest partial count will be used.
2561 if (result->partial_result != 0)
2562 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002563
2564 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002565 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002566 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2567 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2568 " the range of [1, %d] when metadata is included in the result",
2569 frameNumber, result->partial_result, mNumPartialResults);
2570 return;
2571 }
2572 isPartialResult = (result->partial_result < mNumPartialResults);
2573 if (isPartialResult) {
2574 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002575 }
2576
Shuzhen Wang4a472662017-02-26 23:29:04 -08002577 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002578 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002579 sendPartialCaptureResult(result->result, request.resultExtras,
2580 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002581 }
2582 }
2583
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002584 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002585 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002586
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002587 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002588 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002589 if (request.haveResultMetadata) {
2590 SET_ERR("Called multiple times with metadata for frame %d",
2591 frameNumber);
2592 return;
2593 }
Zhijun He204e3292014-07-14 17:09:23 -07002594 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002595 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002596 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002597 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002598 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002599 request.haveResultMetadata = true;
2600 }
2601
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002602 uint32_t numBuffersReturned = result->num_output_buffers;
2603 if (result->input_buffer != NULL) {
2604 if (hasInputBufferInRequest) {
2605 numBuffersReturned += 1;
2606 } else {
2607 ALOGW("%s: Input buffer should be NULL if there is no input"
2608 " buffer sent in the request",
2609 __FUNCTION__);
2610 }
2611 }
2612 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002613 if (request.numBuffersLeft < 0) {
2614 SET_ERR("Too many buffers returned for frame %d",
2615 frameNumber);
2616 return;
2617 }
2618
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002619 camera_metadata_ro_entry_t entry;
2620 res = find_camera_metadata_ro_entry(result->result,
2621 ANDROID_SENSOR_TIMESTAMP, &entry);
2622 if (res == OK && entry.count == 1) {
2623 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002624 }
2625
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002626 // If shutter event isn't received yet, append the output buffers to
2627 // the in-flight request. Otherwise, return the output buffers to
2628 // streams.
2629 if (shutterTimestamp == 0) {
2630 request.pendingOutputBuffers.appendArray(result->output_buffers,
2631 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002632 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002633 returnOutputBuffers(result->output_buffers,
2634 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002635 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002636
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002637 if (result->result != NULL && !isPartialResult) {
2638 if (shutterTimestamp == 0) {
2639 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002640 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002641 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002642 CameraMetadata metadata;
2643 metadata = result->result;
2644 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002645 collectedPartialResult, frameNumber,
2646 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002647 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002648 }
2649
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002650 removeInFlightRequestIfReadyLocked(idx);
2651 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002652
Zhijun Hef0d962a2014-06-30 10:24:11 -07002653 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002654 if (hasInputBufferInRequest) {
2655 Camera3Stream *stream =
2656 Camera3Stream::cast(result->input_buffer->stream);
2657 res = stream->returnInputBuffer(*(result->input_buffer));
2658 // Note: stream may be deallocated at this point, if this buffer was the
2659 // last reference to it.
2660 if (res != OK) {
2661 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2662 " its stream:%s (%d)", __FUNCTION__,
2663 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002664 }
2665 } else {
2666 ALOGW("%s: Input buffer should be NULL if there is no input"
2667 " buffer sent in the request, skipping input buffer return.",
2668 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002669 }
2670 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002671}
2672
2673void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002674 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002675 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002676 {
2677 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002678 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002679 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002680
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002681 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002682 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002683 return;
2684 }
2685
2686 switch (msg->type) {
2687 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002688 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002689 break;
2690 }
2691 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002692 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002693 break;
2694 }
2695 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002696 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002697 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002698 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002699}
2700
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002701void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002702 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002703
2704 // Map camera HAL error codes to ICameraDeviceCallback error codes
2705 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002706 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002707 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002708 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002709 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002710 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002711 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002712 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002713 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002714 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002715 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002716 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002717 };
2718
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002719 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002720 ((msg.error_code >= 0) &&
2721 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2722 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002723 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002724
2725 int streamId = 0;
2726 if (msg.error_stream != NULL) {
2727 Camera3Stream *stream =
2728 Camera3Stream::cast(msg.error_stream);
2729 streamId = stream->getId();
2730 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002731 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2732 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002733 streamId, msg.error_code);
2734
2735 CaptureResultExtras resultExtras;
2736 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002737 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002738 // SET_ERR calls notifyError
2739 SET_ERR("Camera HAL reported serious device error");
2740 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002741 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2742 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2743 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002744 {
2745 Mutex::Autolock l(mInFlightLock);
2746 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2747 if (idx >= 0) {
2748 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2749 r.requestStatus = msg.error_code;
2750 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002751 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2752 errorCode) {
2753 // In case of missing result check whether the buffers
2754 // returned. If they returned, then remove inflight
2755 // request.
2756 removeInFlightRequestIfReadyLocked(idx);
2757 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002758 } else {
2759 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002760 ALOGE("Camera %s: %s: cannot find in-flight request on "
2761 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002762 resultExtras.frameNumber);
2763 }
2764 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002765 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002766 if (listener != NULL) {
2767 listener->notifyError(errorCode, resultExtras);
2768 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002769 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002770 }
2771 break;
2772 default:
2773 // SET_ERR calls notifyError
2774 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2775 break;
2776 }
2777}
2778
2779void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002780 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002781 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002782
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002783 // Set timestamp for the request in the in-flight tracking
2784 // and get the request ID to send upstream
2785 {
2786 Mutex::Autolock l(mInFlightLock);
2787 idx = mInFlightMap.indexOfKey(msg.frame_number);
2788 if (idx >= 0) {
2789 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002791 // Verify ordering of shutter notifications
2792 {
2793 Mutex::Autolock l(mOutputLock);
2794 // TODO: need to track errors for tighter bounds on expected frame number.
2795 if (r.hasInputBuffer) {
2796 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2797 SET_ERR("Shutter notification out-of-order. Expected "
2798 "notification for frame %d, got frame %d",
2799 mNextReprocessShutterFrameNumber, msg.frame_number);
2800 return;
2801 }
2802 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2803 } else {
2804 if (msg.frame_number < mNextShutterFrameNumber) {
2805 SET_ERR("Shutter notification out-of-order. Expected "
2806 "notification for frame %d, got frame %d",
2807 mNextShutterFrameNumber, msg.frame_number);
2808 return;
2809 }
2810 mNextShutterFrameNumber = msg.frame_number + 1;
2811 }
2812 }
2813
Shuzhen Wang4a472662017-02-26 23:29:04 -08002814 r.shutterTimestamp = msg.timestamp;
2815 if (r.hasCallback) {
2816 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002817 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002818 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002819 // Call listener, if any
2820 if (listener != NULL) {
2821 listener->notifyShutter(r.resultExtras, msg.timestamp);
2822 }
2823 // send pending result and buffers
2824 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2825 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002826 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002827 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002828 returnOutputBuffers(r.pendingOutputBuffers.array(),
2829 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2830 r.pendingOutputBuffers.clear();
2831
2832 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002833 }
2834 }
2835 if (idx < 0) {
2836 SET_ERR("Shutter notification for non-existent frame number %d",
2837 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002838 }
2839}
2840
2841
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002842CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002843 ALOGV("%s", __FUNCTION__);
2844
Igor Murashkin1e479c02013-09-06 16:55:14 -07002845 CameraMetadata retVal;
2846
2847 if (mRequestThread != NULL) {
2848 retVal = mRequestThread->getLatestRequest();
2849 }
2850
Igor Murashkin1e479c02013-09-06 16:55:14 -07002851 return retVal;
2852}
2853
Jianing Weicb0652e2014-03-12 18:29:36 -07002854
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002855void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2856 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2857 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2858}
2859
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002860/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002861 * HalInterface inner class methods
2862 */
2863
Yifan Hongf79b5542017-04-11 14:44:25 -07002864Camera3Device::HalInterface::HalInterface(
2865 sp<ICameraDeviceSession> &session,
2866 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002867 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002868 mHidlSession(session),
2869 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002870
2871Camera3Device::HalInterface::HalInterface() :
2872 mHal3Device(nullptr) {}
2873
2874Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002875 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002876 mHidlSession(other.mHidlSession),
2877 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002878
2879bool Camera3Device::HalInterface::valid() {
2880 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2881}
2882
2883void Camera3Device::HalInterface::clear() {
2884 mHal3Device = nullptr;
2885 mHidlSession.clear();
2886}
2887
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002888bool Camera3Device::HalInterface::supportBatchRequest() {
2889 return mHidlSession != nullptr;
2890}
2891
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002892status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2893 camera3_request_template_t templateId,
2894 /*out*/ camera_metadata_t **requestTemplate) {
2895 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2896 if (!valid()) return INVALID_OPERATION;
2897 status_t res = OK;
2898
2899 if (mHal3Device != nullptr) {
2900 const camera_metadata *r;
2901 r = mHal3Device->ops->construct_default_request_settings(
2902 mHal3Device, templateId);
2903 if (r == nullptr) return BAD_VALUE;
2904 *requestTemplate = clone_camera_metadata(r);
2905 if (requestTemplate == nullptr) {
2906 ALOGE("%s: Unable to clone camera metadata received from HAL",
2907 __FUNCTION__);
2908 return INVALID_OPERATION;
2909 }
2910 } else {
2911 common::V1_0::Status status;
2912 RequestTemplate id;
2913 switch (templateId) {
2914 case CAMERA3_TEMPLATE_PREVIEW:
2915 id = RequestTemplate::PREVIEW;
2916 break;
2917 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2918 id = RequestTemplate::STILL_CAPTURE;
2919 break;
2920 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2921 id = RequestTemplate::VIDEO_RECORD;
2922 break;
2923 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2924 id = RequestTemplate::VIDEO_SNAPSHOT;
2925 break;
2926 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2927 id = RequestTemplate::ZERO_SHUTTER_LAG;
2928 break;
2929 case CAMERA3_TEMPLATE_MANUAL:
2930 id = RequestTemplate::MANUAL;
2931 break;
2932 default:
2933 // Unknown template ID
2934 return BAD_VALUE;
2935 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002936 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002937 [&status, &requestTemplate]
2938 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
2939 status = s;
2940 if (status == common::V1_0::Status::OK) {
2941 const camera_metadata *r =
2942 reinterpret_cast<const camera_metadata_t*>(request.data());
2943 size_t expectedSize = request.size();
2944 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07002945 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002946 *requestTemplate = clone_camera_metadata(r);
2947 if (*requestTemplate == nullptr) {
2948 ALOGE("%s: Unable to clone camera metadata received from HAL",
2949 __FUNCTION__);
2950 status = common::V1_0::Status::INTERNAL_ERROR;
2951 }
2952 } else {
2953 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2954 status = common::V1_0::Status::INTERNAL_ERROR;
2955 }
2956 }
2957 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07002958 if (!err.isOk()) {
2959 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2960 res = DEAD_OBJECT;
2961 } else {
2962 res = CameraProviderManager::mapToStatusT(status);
2963 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002964 }
2965 return res;
2966}
2967
2968status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
2969 ATRACE_NAME("CameraHal::configureStreams");
2970 if (!valid()) return INVALID_OPERATION;
2971 status_t res = OK;
2972
2973 if (mHal3Device != nullptr) {
2974 res = mHal3Device->ops->configure_streams(mHal3Device, config);
2975 } else {
2976 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002977 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002978 StreamConfiguration requestedConfiguration;
2979 requestedConfiguration.streams.resize(config->num_streams);
2980 for (size_t i = 0; i < config->num_streams; i++) {
2981 Stream &dst = requestedConfiguration.streams[i];
2982 camera3_stream_t *src = config->streams[i];
2983
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002984 Camera3Stream* cam3stream = Camera3Stream::cast(src);
2985 cam3stream->setBufferFreedListener(this);
2986 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002987 StreamType streamType;
2988 switch (src->stream_type) {
2989 case CAMERA3_STREAM_OUTPUT:
2990 streamType = StreamType::OUTPUT;
2991 break;
2992 case CAMERA3_STREAM_INPUT:
2993 streamType = StreamType::INPUT;
2994 break;
2995 default:
2996 ALOGE("%s: Stream %d: Unsupported stream type %d",
2997 __FUNCTION__, streamId, config->streams[i]->stream_type);
2998 return BAD_VALUE;
2999 }
3000 dst.id = streamId;
3001 dst.streamType = streamType;
3002 dst.width = src->width;
3003 dst.height = src->height;
3004 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003005 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 dst.dataSpace = mapToHidlDataspace(src->data_space);
3007 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003008
3009 activeStreams.insert(streamId);
3010 // Create Buffer ID map if necessary
3011 if (mBufferIdMaps.count(streamId) == 0) {
3012 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3013 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003014 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003015 // remove BufferIdMap for deleted streams
3016 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3017 int streamId = it->first;
3018 bool active = activeStreams.count(streamId) > 0;
3019 if (!active) {
3020 it = mBufferIdMaps.erase(it);
3021 } else {
3022 ++it;
3023 }
3024 }
3025
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003026 res = mapToStreamConfigurationMode(
3027 (camera3_stream_configuration_mode_t) config->operation_mode,
3028 /*out*/ &requestedConfiguration.operationMode);
3029 if (res != OK) {
3030 return res;
3031 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003032
3033 // Invoke configureStreams
3034
3035 HalStreamConfiguration finalConfiguration;
3036 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003037 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003038 [&status, &finalConfiguration]
3039 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3040 finalConfiguration = halConfiguration;
3041 status = s;
3042 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003043 if (!err.isOk()) {
3044 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3045 return DEAD_OBJECT;
3046 }
3047
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003048 if (status != common::V1_0::Status::OK ) {
3049 return CameraProviderManager::mapToStatusT(status);
3050 }
3051
3052 // And convert output stream configuration from HIDL
3053
3054 for (size_t i = 0; i < config->num_streams; i++) {
3055 camera3_stream_t *dst = config->streams[i];
3056 int streamId = Camera3Stream::cast(dst)->getId();
3057
3058 // Start scan at i, with the assumption that the stream order matches
3059 size_t realIdx = i;
3060 bool found = false;
3061 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3062 if (finalConfiguration.streams[realIdx].id == streamId) {
3063 found = true;
3064 break;
3065 }
3066 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3067 }
3068 if (!found) {
3069 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3070 __FUNCTION__, streamId);
3071 return INVALID_OPERATION;
3072 }
3073 HalStream &src = finalConfiguration.streams[realIdx];
3074
3075 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3076 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3077 if (dst->format != overrideFormat) {
3078 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3079 streamId, dst->format);
3080 }
3081 } else {
3082 // Override allowed with IMPLEMENTATION_DEFINED
3083 dst->format = overrideFormat;
3084 }
3085
3086 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3087 if (src.producerUsage != 0) {
3088 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3089 __FUNCTION__, streamId);
3090 return INVALID_OPERATION;
3091 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003092 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003093 } else {
3094 // OUTPUT
3095 if (src.consumerUsage != 0) {
3096 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3097 __FUNCTION__, streamId);
3098 return INVALID_OPERATION;
3099 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003100 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003101 }
3102 dst->max_buffers = src.maxBuffers;
3103 }
3104 }
3105 return res;
3106}
3107
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003108void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3109 /*out*/device::V3_2::CaptureRequest* captureRequest,
3110 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3111
3112 if (captureRequest == nullptr || handlesCreated == nullptr) {
3113 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3114 __FUNCTION__, captureRequest, handlesCreated);
3115 return;
3116 }
3117
3118 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003119
3120 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003121
3122 {
3123 std::lock_guard<std::mutex> lock(mInflightLock);
3124 if (request->input_buffer != nullptr) {
3125 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3126 buffer_handle_t buf = *(request->input_buffer->buffer);
3127 auto pair = getBufferId(buf, streamId);
3128 bool isNewBuffer = pair.first;
3129 uint64_t bufferId = pair.second;
3130 captureRequest->inputBuffer.streamId = streamId;
3131 captureRequest->inputBuffer.bufferId = bufferId;
3132 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3133 captureRequest->inputBuffer.status = BufferStatus::OK;
3134 native_handle_t *acquireFence = nullptr;
3135 if (request->input_buffer->acquire_fence != -1) {
3136 acquireFence = native_handle_create(1,0);
3137 acquireFence->data[0] = request->input_buffer->acquire_fence;
3138 handlesCreated->push_back(acquireFence);
3139 }
3140 captureRequest->inputBuffer.acquireFence = acquireFence;
3141 captureRequest->inputBuffer.releaseFence = nullptr;
3142
3143 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3144 request->input_buffer->buffer,
3145 request->input_buffer->acquire_fence);
3146 } else {
3147 captureRequest->inputBuffer.streamId = -1;
3148 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3149 }
3150
3151 captureRequest->outputBuffers.resize(request->num_output_buffers);
3152 for (size_t i = 0; i < request->num_output_buffers; i++) {
3153 const camera3_stream_buffer_t *src = request->output_buffers + i;
3154 StreamBuffer &dst = captureRequest->outputBuffers[i];
3155 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3156 buffer_handle_t buf = *(src->buffer);
3157 auto pair = getBufferId(buf, streamId);
3158 bool isNewBuffer = pair.first;
3159 dst.streamId = streamId;
3160 dst.bufferId = pair.second;
3161 dst.buffer = isNewBuffer ? buf : nullptr;
3162 dst.status = BufferStatus::OK;
3163 native_handle_t *acquireFence = nullptr;
3164 if (src->acquire_fence != -1) {
3165 acquireFence = native_handle_create(1,0);
3166 acquireFence->data[0] = src->acquire_fence;
3167 handlesCreated->push_back(acquireFence);
3168 }
3169 dst.acquireFence = acquireFence;
3170 dst.releaseFence = nullptr;
3171
3172 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3173 src->buffer, src->acquire_fence);
3174 }
3175 }
3176}
3177
3178status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3179 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3180 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3181 if (!valid()) return INVALID_OPERATION;
3182
3183 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3184 size_t batchSize = requests.size();
3185 captureRequests.resize(batchSize);
3186 std::vector<native_handle_t*> handlesCreated;
3187
3188 for (size_t i = 0; i < batchSize; i++) {
3189 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3190 }
3191
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003192 std::vector<device::V3_2::BufferCache> cachesToRemove;
3193 {
3194 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3195 for (auto& pair : mFreedBuffers) {
3196 // The stream might have been removed since onBufferFreed
3197 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3198 cachesToRemove.push_back({pair.first, pair.second});
3199 }
3200 }
3201 mFreedBuffers.clear();
3202 }
3203
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003204 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3205 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003206
3207 // Write metadata to FMQ.
3208 for (size_t i = 0; i < batchSize; i++) {
3209 camera3_capture_request_t* request = requests[i];
3210 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3211
3212 if (request->settings != nullptr) {
3213 size_t settingsSize = get_camera_metadata_size(request->settings);
3214 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3215 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3216 captureRequest->settings.resize(0);
3217 captureRequest->fmqSettingsSize = settingsSize;
3218 } else {
3219 if (mRequestMetadataQueue != nullptr) {
3220 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3221 }
3222 captureRequest->settings.setToExternal(
3223 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3224 get_camera_metadata_size(request->settings));
3225 captureRequest->fmqSettingsSize = 0u;
3226 }
3227 } else {
3228 // A null request settings maps to a size-0 CameraMetadata
3229 captureRequest->settings.resize(0);
3230 captureRequest->fmqSettingsSize = 0u;
3231 }
3232 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003233 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003234 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3235 status = s;
3236 *numRequestProcessed = n;
3237 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003238 if (!err.isOk()) {
3239 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3240 return DEAD_OBJECT;
3241 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003242 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3243 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3244 __FUNCTION__, *numRequestProcessed, batchSize);
3245 status = common::V1_0::Status::INTERNAL_ERROR;
3246 }
3247
3248 for (auto& handle : handlesCreated) {
3249 native_handle_delete(handle);
3250 }
3251 return CameraProviderManager::mapToStatusT(status);
3252}
3253
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003254status_t Camera3Device::HalInterface::processCaptureRequest(
3255 camera3_capture_request_t *request) {
3256 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003257 if (!valid()) return INVALID_OPERATION;
3258 status_t res = OK;
3259
3260 if (mHal3Device != nullptr) {
3261 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3262 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003263 uint32_t numRequestProcessed = 0;
3264 std::vector<camera3_capture_request_t*> requests(1);
3265 requests[0] = request;
3266 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003267 }
3268 return res;
3269}
3270
3271status_t Camera3Device::HalInterface::flush() {
3272 ATRACE_NAME("CameraHal::flush");
3273 if (!valid()) return INVALID_OPERATION;
3274 status_t res = OK;
3275
3276 if (mHal3Device != nullptr) {
3277 res = mHal3Device->ops->flush(mHal3Device);
3278 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003279 auto err = mHidlSession->flush();
3280 if (!err.isOk()) {
3281 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3282 res = DEAD_OBJECT;
3283 } else {
3284 res = CameraProviderManager::mapToStatusT(err);
3285 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003286 }
3287 return res;
3288}
3289
3290status_t Camera3Device::HalInterface::dump(int fd) {
3291 ATRACE_NAME("CameraHal::dump");
3292 if (!valid()) return INVALID_OPERATION;
3293 status_t res = OK;
3294
3295 if (mHal3Device != nullptr) {
3296 mHal3Device->ops->dump(mHal3Device, fd);
3297 } else {
3298 // Handled by CameraProviderManager::dump
3299 }
3300 return res;
3301}
3302
3303status_t Camera3Device::HalInterface::close() {
3304 ATRACE_NAME("CameraHal::close()");
3305 if (!valid()) return INVALID_OPERATION;
3306 status_t res = OK;
3307
3308 if (mHal3Device != nullptr) {
3309 mHal3Device->common.close(&mHal3Device->common);
3310 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003311 auto err = mHidlSession->close();
3312 // Interface will be dead shortly anyway, so don't log errors
3313 if (!err.isOk()) {
3314 res = DEAD_OBJECT;
3315 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003316 }
3317 return res;
3318}
3319
3320status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003321 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003322 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003323 auto pair = std::make_pair(buffer, acquireFence);
3324 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003325 return OK;
3326}
3327
3328status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003329 int32_t frameNumber, int32_t streamId,
3330 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003331 std::lock_guard<std::mutex> lock(mInflightLock);
3332
3333 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3334 auto it = mInflightBufferMap.find(key);
3335 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003336 auto pair = it->second;
3337 *buffer = pair.first;
3338 int acquireFence = pair.second;
3339 if (acquireFence > 0) {
3340 ::close(acquireFence);
3341 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003342 mInflightBufferMap.erase(it);
3343 return OK;
3344}
3345
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003346std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3347 const buffer_handle_t& buf, int streamId) {
3348 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3349
3350 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3351 auto it = bIdMap.find(buf);
3352 if (it == bIdMap.end()) {
3353 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003354 ALOGV("stream %d now have %zu buffer caches, buf %p",
3355 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003356 return std::make_pair(true, mNextBufferId - 1);
3357 } else {
3358 return std::make_pair(false, it->second);
3359 }
3360}
3361
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003362void Camera3Device::HalInterface::onBufferFreed(
3363 int streamId, const native_handle_t* handle) {
3364 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3365 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3366 auto mapIt = mBufferIdMaps.find(streamId);
3367 if (mapIt == mBufferIdMaps.end()) {
3368 // streamId might be from a deleted stream here
3369 ALOGI("%s: stream %d has been removed",
3370 __FUNCTION__, streamId);
3371 return;
3372 }
3373 BufferIdMap& bIdMap = mapIt->second;
3374 auto it = bIdMap.find(handle);
3375 if (it == bIdMap.end()) {
3376 ALOGW("%s: cannot find buffer %p in stream %d",
3377 __FUNCTION__, handle, streamId);
3378 return;
3379 } else {
3380 bufferId = it->second;
3381 bIdMap.erase(it);
3382 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3383 __FUNCTION__, streamId, bIdMap.size(), handle);
3384 }
3385 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3386}
3387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003388/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003389 * RequestThread inner class methods
3390 */
3391
3392Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003393 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003394 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003395 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003396 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003397 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003398 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003399 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003400 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003401 mReconfigured(false),
3402 mDoPause(false),
3403 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003404 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003405 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003406 mCurrentAfTriggerId(0),
3407 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003408 mRepeatingLastFrameNumber(
3409 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003410 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003411 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003412}
3413
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003414Camera3Device::RequestThread::~RequestThread() {}
3415
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003416void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003417 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003418 Mutex::Autolock l(mRequestLock);
3419 mListener = listener;
3420}
3421
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003422void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003423 Mutex::Autolock l(mRequestLock);
3424 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003425 // Prepare video stream for high speed recording.
3426 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003427}
3428
Jianing Wei90e59c92014-03-12 18:29:36 -07003429status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003430 List<sp<CaptureRequest> > &requests,
3431 /*out*/
3432 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003433 Mutex::Autolock l(mRequestLock);
3434 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3435 ++it) {
3436 mRequestQueue.push_back(*it);
3437 }
3438
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003439 if (lastFrameNumber != NULL) {
3440 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3441 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3442 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3443 *lastFrameNumber);
3444 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003445
Jianing Wei90e59c92014-03-12 18:29:36 -07003446 unpauseForNewRequests();
3447
3448 return OK;
3449}
3450
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003451
3452status_t Camera3Device::RequestThread::queueTrigger(
3453 RequestTrigger trigger[],
3454 size_t count) {
3455
3456 Mutex::Autolock l(mTriggerMutex);
3457 status_t ret;
3458
3459 for (size_t i = 0; i < count; ++i) {
3460 ret = queueTriggerLocked(trigger[i]);
3461
3462 if (ret != OK) {
3463 return ret;
3464 }
3465 }
3466
3467 return OK;
3468}
3469
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003470const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3471 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003472 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003473 if (d != nullptr) return d->mId;
3474 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003475}
3476
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003477status_t Camera3Device::RequestThread::queueTriggerLocked(
3478 RequestTrigger trigger) {
3479
3480 uint32_t tag = trigger.metadataTag;
3481 ssize_t index = mTriggerMap.indexOfKey(tag);
3482
3483 switch (trigger.getTagType()) {
3484 case TYPE_BYTE:
3485 // fall-through
3486 case TYPE_INT32:
3487 break;
3488 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003489 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3490 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003491 return INVALID_OPERATION;
3492 }
3493
3494 /**
3495 * Collect only the latest trigger, since we only have 1 field
3496 * in the request settings per trigger tag, and can't send more than 1
3497 * trigger per request.
3498 */
3499 if (index != NAME_NOT_FOUND) {
3500 mTriggerMap.editValueAt(index) = trigger;
3501 } else {
3502 mTriggerMap.add(tag, trigger);
3503 }
3504
3505 return OK;
3506}
3507
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003508status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003509 const RequestList &requests,
3510 /*out*/
3511 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003512 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003513 if (lastFrameNumber != NULL) {
3514 *lastFrameNumber = mRepeatingLastFrameNumber;
3515 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003516 mRepeatingRequests.clear();
3517 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3518 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003519
3520 unpauseForNewRequests();
3521
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003522 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003523 return OK;
3524}
3525
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003526bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003527 if (mRepeatingRequests.empty()) {
3528 return false;
3529 }
3530 int32_t requestId = requestIn->mResultExtras.requestId;
3531 const RequestList &repeatRequests = mRepeatingRequests;
3532 // All repeating requests are guaranteed to have same id so only check first quest
3533 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3534 return (firstRequest->mResultExtras.requestId == requestId);
3535}
3536
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003537status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003538 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003539 return clearRepeatingRequestsLocked(lastFrameNumber);
3540
3541}
3542
3543status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003544 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003545 if (lastFrameNumber != NULL) {
3546 *lastFrameNumber = mRepeatingLastFrameNumber;
3547 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003548 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003549 return OK;
3550}
3551
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003552status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003553 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003554 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003555 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003556
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003557 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003558
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003559 // Send errors for all requests pending in the request queue, including
3560 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003561 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003562 if (listener != NULL) {
3563 for (RequestList::iterator it = mRequestQueue.begin();
3564 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003565 // Abort the input buffers for reprocess requests.
3566 if ((*it)->mInputStream != NULL) {
3567 camera3_stream_buffer_t inputBuffer;
3568 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3569 if (res != OK) {
3570 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3571 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3572 } else {
3573 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3574 if (res != OK) {
3575 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3576 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3577 }
3578 }
3579 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003580 // Set the frame number this request would have had, if it
3581 // had been submitted; this frame number will not be reused.
3582 // The requestId and burstId fields were set when the request was
3583 // submitted originally (in convertMetadataListToRequestListLocked)
3584 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003585 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003586 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003587 }
3588 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003589 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003590
3591 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003592 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003593 if (lastFrameNumber != NULL) {
3594 *lastFrameNumber = mRepeatingLastFrameNumber;
3595 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003596 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003597 return OK;
3598}
3599
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003600status_t Camera3Device::RequestThread::flush() {
3601 ATRACE_CALL();
3602 Mutex::Autolock l(mFlushLock);
3603
Emilian Peev08dd2452017-04-06 16:55:14 +01003604 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003605}
3606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003607void Camera3Device::RequestThread::setPaused(bool paused) {
3608 Mutex::Autolock l(mPauseLock);
3609 mDoPause = paused;
3610 mDoPauseSignal.signal();
3611}
3612
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003613status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3614 int32_t requestId, nsecs_t timeout) {
3615 Mutex::Autolock l(mLatestRequestMutex);
3616 status_t res;
3617 while (mLatestRequestId != requestId) {
3618 nsecs_t startTime = systemTime();
3619
3620 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3621 if (res != OK) return res;
3622
3623 timeout -= (systemTime() - startTime);
3624 }
3625
3626 return OK;
3627}
3628
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003629void Camera3Device::RequestThread::requestExit() {
3630 // Call parent to set up shutdown
3631 Thread::requestExit();
3632 // The exit from any possible waits
3633 mDoPauseSignal.signal();
3634 mRequestSignal.signal();
3635}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003636
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003637void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003638 bool surfaceAbandoned = false;
3639 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003640 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003641 {
3642 Mutex::Autolock l(mRequestLock);
3643 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3644 // repeating requests.
3645 for (const auto& request : mRepeatingRequests) {
3646 for (const auto& s : request->mOutputStreams) {
3647 if (s->isAbandoned()) {
3648 surfaceAbandoned = true;
3649 clearRepeatingRequestsLocked(&lastFrameNumber);
3650 break;
3651 }
3652 }
3653 if (surfaceAbandoned) {
3654 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003655 }
3656 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003657 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003658 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003659
3660 if (listener != NULL && surfaceAbandoned) {
3661 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003662 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003663}
3664
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003665bool Camera3Device::RequestThread::sendRequestsBatch() {
3666 status_t res;
3667 size_t batchSize = mNextRequests.size();
3668 std::vector<camera3_capture_request_t*> requests(batchSize);
3669 uint32_t numRequestProcessed = 0;
3670 for (size_t i = 0; i < batchSize; i++) {
3671 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3672 }
3673
3674 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3675 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3676
3677 bool triggerRemoveFailed = false;
3678 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3679 for (size_t i = 0; i < numRequestProcessed; i++) {
3680 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3681 nextRequest.submitted = true;
3682
3683
3684 // Update the latest request sent to HAL
3685 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3686 Mutex::Autolock al(mLatestRequestMutex);
3687
3688 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3689 mLatestRequest.acquire(cloned);
3690
3691 sp<Camera3Device> parent = mParent.promote();
3692 if (parent != NULL) {
3693 parent->monitorMetadata(TagMonitor::REQUEST,
3694 nextRequest.halRequest.frame_number,
3695 0, mLatestRequest);
3696 }
3697 }
3698
3699 if (nextRequest.halRequest.settings != NULL) {
3700 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3701 }
3702
3703 if (!triggerRemoveFailed) {
3704 // Remove any previously queued triggers (after unlock)
3705 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3706 if (removeTriggerRes != OK) {
3707 triggerRemoveFailed = true;
3708 triggerFailedRequest = nextRequest;
3709 }
3710 }
3711 }
3712
3713 if (triggerRemoveFailed) {
3714 SET_ERR("RequestThread: Unable to remove triggers "
3715 "(capture request %d, HAL device: %s (%d)",
3716 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3717 cleanUpFailedRequests(/*sendRequestError*/ false);
3718 return false;
3719 }
3720
3721 if (res != OK) {
3722 // Should only get a failure here for malformed requests or device-level
3723 // errors, so consider all errors fatal. Bad metadata failures should
3724 // come through notify.
3725 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3726 mNextRequests[numRequestProcessed].halRequest.frame_number,
3727 strerror(-res), res);
3728 cleanUpFailedRequests(/*sendRequestError*/ false);
3729 return false;
3730 }
3731 return true;
3732}
3733
3734bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3735 status_t res;
3736
3737 for (auto& nextRequest : mNextRequests) {
3738 // Submit request and block until ready for next one
3739 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3740 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3741
3742 if (res != OK) {
3743 // Should only get a failure here for malformed requests or device-level
3744 // errors, so consider all errors fatal. Bad metadata failures should
3745 // come through notify.
3746 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3747 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3748 res);
3749 cleanUpFailedRequests(/*sendRequestError*/ false);
3750 return false;
3751 }
3752
3753 // Mark that the request has be submitted successfully.
3754 nextRequest.submitted = true;
3755
3756 // Update the latest request sent to HAL
3757 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3758 Mutex::Autolock al(mLatestRequestMutex);
3759
3760 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3761 mLatestRequest.acquire(cloned);
3762
3763 sp<Camera3Device> parent = mParent.promote();
3764 if (parent != NULL) {
3765 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3766 0, mLatestRequest);
3767 }
3768 }
3769
3770 if (nextRequest.halRequest.settings != NULL) {
3771 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3772 }
3773
3774 // Remove any previously queued triggers (after unlock)
3775 res = removeTriggers(mPrevRequest);
3776 if (res != OK) {
3777 SET_ERR("RequestThread: Unable to remove triggers "
3778 "(capture request %d, HAL device: %s (%d)",
3779 nextRequest.halRequest.frame_number, strerror(-res), res);
3780 cleanUpFailedRequests(/*sendRequestError*/ false);
3781 return false;
3782 }
3783 }
3784 return true;
3785}
3786
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003787bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003788 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003789 status_t res;
3790
3791 // Handle paused state.
3792 if (waitIfPaused()) {
3793 return true;
3794 }
3795
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003796 // Wait for the next batch of requests.
3797 waitForNextRequestBatch();
3798 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003799 return true;
3800 }
3801
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003802 // Get the latest request ID, if any
3803 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003804 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003805 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003806 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003807 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003808 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003809 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3810 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003811 }
3812
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003813 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003814 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003815 if (res == TIMED_OUT) {
3816 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003817 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003818 // Check if any stream is abandoned.
3819 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003820 return true;
3821 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003822 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003823 return false;
3824 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003825
Zhijun Hecc27e112013-10-03 16:12:43 -07003826 // Inform waitUntilRequestProcessed thread of a new request ID
3827 {
3828 Mutex::Autolock al(mLatestRequestMutex);
3829
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003830 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003831 mLatestRequestSignal.signal();
3832 }
3833
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003834 // Submit a batch of requests to HAL.
3835 // Use flush lock only when submitting multilple requests in a batch.
3836 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3837 // which may take a long time to finish so synchronizing flush() and
3838 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3839 // For now, only synchronize for high speed recording and we should figure something out for
3840 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003841 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003842
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003843 if (useFlushLock) {
3844 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003845 }
3846
Zhijun Hef0645c12016-08-02 00:58:11 -07003847 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003848 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003849
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003850 bool submitRequestSuccess = false;
3851 if (mInterface->supportBatchRequest()) {
3852 submitRequestSuccess = sendRequestsBatch();
3853 } else {
3854 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003855 }
3856
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003857 if (useFlushLock) {
3858 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003859 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003860
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003861 // Unset as current request
3862 {
3863 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003864 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003865 }
3866
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003867 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003868}
3869
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003870status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003871 ATRACE_CALL();
3872
Shuzhen Wang4a472662017-02-26 23:29:04 -08003873 for (size_t i = 0; i < mNextRequests.size(); i++) {
3874 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003875 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3876 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3877 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3878
3879 // Prepare a request to HAL
3880 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3881
3882 // Insert any queued triggers (before metadata is locked)
3883 status_t res = insertTriggers(captureRequest);
3884
3885 if (res < 0) {
3886 SET_ERR("RequestThread: Unable to insert triggers "
3887 "(capture request %d, HAL device: %s (%d)",
3888 halRequest->frame_number, strerror(-res), res);
3889 return INVALID_OPERATION;
3890 }
3891 int triggerCount = res;
3892 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3893 mPrevTriggers = triggerCount;
3894
3895 // If the request is the same as last, or we had triggers last time
3896 if (mPrevRequest != captureRequest || triggersMixedIn) {
3897 /**
3898 * HAL workaround:
3899 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3900 */
3901 res = addDummyTriggerIds(captureRequest);
3902 if (res != OK) {
3903 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3904 "(capture request %d, HAL device: %s (%d)",
3905 halRequest->frame_number, strerror(-res), res);
3906 return INVALID_OPERATION;
3907 }
3908
3909 /**
3910 * The request should be presorted so accesses in HAL
3911 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3912 */
3913 captureRequest->mSettings.sort();
3914 halRequest->settings = captureRequest->mSettings.getAndLock();
3915 mPrevRequest = captureRequest;
3916 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3917
3918 IF_ALOGV() {
3919 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3920 find_camera_metadata_ro_entry(
3921 halRequest->settings,
3922 ANDROID_CONTROL_AF_TRIGGER,
3923 &e
3924 );
3925 if (e.count > 0) {
3926 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3927 __FUNCTION__,
3928 halRequest->frame_number,
3929 e.data.u8[0]);
3930 }
3931 }
3932 } else {
3933 // leave request.settings NULL to indicate 'reuse latest given'
3934 ALOGVV("%s: Request settings are REUSED",
3935 __FUNCTION__);
3936 }
3937
3938 uint32_t totalNumBuffers = 0;
3939
3940 // Fill in buffers
3941 if (captureRequest->mInputStream != NULL) {
3942 halRequest->input_buffer = &captureRequest->mInputBuffer;
3943 totalNumBuffers += 1;
3944 } else {
3945 halRequest->input_buffer = NULL;
3946 }
3947
3948 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3949 captureRequest->mOutputStreams.size());
3950 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08003951 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
3952 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003953
3954 // Prepare video buffers for high speed recording on the first video request.
3955 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3956 // Only try to prepare video stream on the first video request.
3957 mPrepareVideoStream = false;
3958
3959 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3960 while (res == NOT_ENOUGH_DATA) {
3961 res = outputStream->prepareNextBuffer();
3962 }
3963 if (res != OK) {
3964 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3965 __FUNCTION__, strerror(-res), res);
3966 outputStream->cancelPrepare();
3967 }
3968 }
3969
Shuzhen Wang4a472662017-02-26 23:29:04 -08003970 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3971 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003972 if (res != OK) {
3973 // Can't get output buffer from gralloc queue - this could be due to
3974 // abandoned queue or other consumer misbehavior, so not a fatal
3975 // error
3976 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3977 " %s (%d)", strerror(-res), res);
3978
3979 return TIMED_OUT;
3980 }
3981 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07003982
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003983 }
3984 totalNumBuffers += halRequest->num_output_buffers;
3985
3986 // Log request in the in-flight queue
3987 sp<Camera3Device> parent = mParent.promote();
3988 if (parent == NULL) {
3989 // Should not happen, and nowhere to send errors to, so just log it
3990 CLOGE("RequestThread: Parent is gone");
3991 return INVALID_OPERATION;
3992 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08003993
3994 // If this request list is for constrained high speed recording (not
3995 // preview), and the current request is not the last one in the batch,
3996 // do not send callback to the app.
3997 bool hasCallback = true;
3998 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
3999 hasCallback = false;
4000 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004001 res = parent->registerInFlight(halRequest->frame_number,
4002 totalNumBuffers, captureRequest->mResultExtras,
4003 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004004 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004005 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4006 ", burstId = %" PRId32 ".",
4007 __FUNCTION__,
4008 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4009 captureRequest->mResultExtras.burstId);
4010 if (res != OK) {
4011 SET_ERR("RequestThread: Unable to register new in-flight request:"
4012 " %s (%d)", strerror(-res), res);
4013 return INVALID_OPERATION;
4014 }
4015 }
4016
4017 return OK;
4018}
4019
Igor Murashkin1e479c02013-09-06 16:55:14 -07004020CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4021 Mutex::Autolock al(mLatestRequestMutex);
4022
4023 ALOGV("RequestThread::%s", __FUNCTION__);
4024
4025 return mLatestRequest;
4026}
4027
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004028bool Camera3Device::RequestThread::isStreamPending(
4029 sp<Camera3StreamInterface>& stream) {
4030 Mutex::Autolock l(mRequestLock);
4031
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004032 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004033 if (!nextRequest.submitted) {
4034 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4035 if (stream == s) return true;
4036 }
4037 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004038 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004039 }
4040
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004041 for (const auto& request : mRequestQueue) {
4042 for (const auto& s : request->mOutputStreams) {
4043 if (stream == s) return true;
4044 }
4045 if (stream == request->mInputStream) return true;
4046 }
4047
4048 for (const auto& request : mRepeatingRequests) {
4049 for (const auto& s : request->mOutputStreams) {
4050 if (stream == s) return true;
4051 }
4052 if (stream == request->mInputStream) return true;
4053 }
4054
4055 return false;
4056}
Jianing Weicb0652e2014-03-12 18:29:36 -07004057
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004058void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4059 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004060 return;
4061 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004062
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004063 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004064 // Skip the ones that have been submitted successfully.
4065 if (nextRequest.submitted) {
4066 continue;
4067 }
4068
4069 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4070 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4071 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4072
4073 if (halRequest->settings != NULL) {
4074 captureRequest->mSettings.unlock(halRequest->settings);
4075 }
4076
4077 if (captureRequest->mInputStream != NULL) {
4078 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4079 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4080 }
4081
4082 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004083 //Buffers that failed processing could still have
4084 //valid acquire fence.
4085 int acquireFence = (*outputBuffers)[i].acquire_fence;
4086 if (0 <= acquireFence) {
4087 close(acquireFence);
4088 outputBuffers->editItemAt(i).acquire_fence = -1;
4089 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004090 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4091 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4092 }
4093
4094 if (sendRequestError) {
4095 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004096 sp<NotificationListener> listener = mListener.promote();
4097 if (listener != NULL) {
4098 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004099 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 captureRequest->mResultExtras);
4101 }
4102 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004103
4104 // Remove yet-to-be submitted inflight request from inflightMap
4105 {
4106 sp<Camera3Device> parent = mParent.promote();
4107 if (parent != NULL) {
4108 Mutex::Autolock l(parent->mInFlightLock);
4109 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4110 if (idx >= 0) {
4111 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4112 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4113 parent->removeInFlightMapEntryLocked(idx);
4114 }
4115 }
4116 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004117 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004118
4119 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004120 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004121}
4122
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004123void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004124 // Optimized a bit for the simple steady-state case (single repeating
4125 // request), to avoid putting that request in the queue temporarily.
4126 Mutex::Autolock l(mRequestLock);
4127
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004128 assert(mNextRequests.empty());
4129
4130 NextRequest nextRequest;
4131 nextRequest.captureRequest = waitForNextRequestLocked();
4132 if (nextRequest.captureRequest == nullptr) {
4133 return;
4134 }
4135
4136 nextRequest.halRequest = camera3_capture_request_t();
4137 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004138 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004139
4140 // Wait for additional requests
4141 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4142
4143 for (size_t i = 1; i < batchSize; i++) {
4144 NextRequest additionalRequest;
4145 additionalRequest.captureRequest = waitForNextRequestLocked();
4146 if (additionalRequest.captureRequest == nullptr) {
4147 break;
4148 }
4149
4150 additionalRequest.halRequest = camera3_capture_request_t();
4151 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004152 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004153 }
4154
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004155 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004156 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004157 mNextRequests.size(), batchSize);
4158 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004159 }
4160
4161 return;
4162}
4163
4164sp<Camera3Device::CaptureRequest>
4165 Camera3Device::RequestThread::waitForNextRequestLocked() {
4166 status_t res;
4167 sp<CaptureRequest> nextRequest;
4168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004169 while (mRequestQueue.empty()) {
4170 if (!mRepeatingRequests.empty()) {
4171 // Always atomically enqueue all requests in a repeating request
4172 // list. Guarantees a complete in-sequence set of captures to
4173 // application.
4174 const RequestList &requests = mRepeatingRequests;
4175 RequestList::const_iterator firstRequest =
4176 requests.begin();
4177 nextRequest = *firstRequest;
4178 mRequestQueue.insert(mRequestQueue.end(),
4179 ++firstRequest,
4180 requests.end());
4181 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004182
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004183 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004184
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004185 break;
4186 }
4187
4188 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4189
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004190 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4191 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004192 Mutex::Autolock pl(mPauseLock);
4193 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004194 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004195 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004196 // Let the tracker know
4197 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4198 if (statusTracker != 0) {
4199 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4200 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004201 }
4202 // Stop waiting for now and let thread management happen
4203 return NULL;
4204 }
4205 }
4206
4207 if (nextRequest == NULL) {
4208 // Don't have a repeating request already in hand, so queue
4209 // must have an entry now.
4210 RequestList::iterator firstRequest =
4211 mRequestQueue.begin();
4212 nextRequest = *firstRequest;
4213 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004214 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4215 sp<NotificationListener> listener = mListener.promote();
4216 if (listener != NULL) {
4217 listener->notifyRequestQueueEmpty();
4218 }
4219 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220 }
4221
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004222 // In case we've been unpaused by setPaused clearing mDoPause, need to
4223 // update internal pause state (capture/setRepeatingRequest unpause
4224 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004225 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004226 if (mPaused) {
4227 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4228 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4229 if (statusTracker != 0) {
4230 statusTracker->markComponentActive(mStatusId);
4231 }
4232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004233 mPaused = false;
4234
4235 // Check if we've reconfigured since last time, and reset the preview
4236 // request if so. Can't use 'NULL request == repeat' across configure calls.
4237 if (mReconfigured) {
4238 mPrevRequest.clear();
4239 mReconfigured = false;
4240 }
4241
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004242 if (nextRequest != NULL) {
4243 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004244 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4245 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004246
4247 // Since RequestThread::clear() removes buffers from the input stream,
4248 // get the right buffer here before unlocking mRequestLock
4249 if (nextRequest->mInputStream != NULL) {
4250 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4251 if (res != OK) {
4252 // Can't get input buffer from gralloc queue - this could be due to
4253 // disconnected queue or other producer misbehavior, so not a fatal
4254 // error
4255 ALOGE("%s: Can't get input buffer, skipping request:"
4256 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004257
4258 sp<NotificationListener> listener = mListener.promote();
4259 if (listener != NULL) {
4260 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004261 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004262 nextRequest->mResultExtras);
4263 }
4264 return NULL;
4265 }
4266 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004267 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004269 return nextRequest;
4270}
4271
4272bool Camera3Device::RequestThread::waitIfPaused() {
4273 status_t res;
4274 Mutex::Autolock l(mPauseLock);
4275 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276 if (mPaused == false) {
4277 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004278 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4279 // Let the tracker know
4280 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4281 if (statusTracker != 0) {
4282 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4283 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004284 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004285
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004286 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004287 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004288 return true;
4289 }
4290 }
4291 // We don't set mPaused to false here, because waitForNextRequest needs
4292 // to further manage the paused state in case of starvation.
4293 return false;
4294}
4295
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004296void Camera3Device::RequestThread::unpauseForNewRequests() {
4297 // With work to do, mark thread as unpaused.
4298 // If paused by request (setPaused), don't resume, to avoid
4299 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004300 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004301 Mutex::Autolock p(mPauseLock);
4302 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004303 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4304 if (mPaused) {
4305 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4306 if (statusTracker != 0) {
4307 statusTracker->markComponentActive(mStatusId);
4308 }
4309 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004310 mPaused = false;
4311 }
4312}
4313
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004314void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4315 sp<Camera3Device> parent = mParent.promote();
4316 if (parent != NULL) {
4317 va_list args;
4318 va_start(args, fmt);
4319
4320 parent->setErrorStateV(fmt, args);
4321
4322 va_end(args);
4323 }
4324}
4325
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004326status_t Camera3Device::RequestThread::insertTriggers(
4327 const sp<CaptureRequest> &request) {
4328
4329 Mutex::Autolock al(mTriggerMutex);
4330
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004331 sp<Camera3Device> parent = mParent.promote();
4332 if (parent == NULL) {
4333 CLOGE("RequestThread: Parent is gone");
4334 return DEAD_OBJECT;
4335 }
4336
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004337 CameraMetadata &metadata = request->mSettings;
4338 size_t count = mTriggerMap.size();
4339
4340 for (size_t i = 0; i < count; ++i) {
4341 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004342 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004343
4344 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4345 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4346 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004347 if (isAeTrigger) {
4348 request->mResultExtras.precaptureTriggerId = triggerId;
4349 mCurrentPreCaptureTriggerId = triggerId;
4350 } else {
4351 request->mResultExtras.afTriggerId = triggerId;
4352 mCurrentAfTriggerId = triggerId;
4353 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004354 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004355 }
4356
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004357 camera_metadata_entry entry = metadata.find(tag);
4358
4359 if (entry.count > 0) {
4360 /**
4361 * Already has an entry for this trigger in the request.
4362 * Rewrite it with our requested trigger value.
4363 */
4364 RequestTrigger oldTrigger = trigger;
4365
4366 oldTrigger.entryValue = entry.data.u8[0];
4367
4368 mTriggerReplacedMap.add(tag, oldTrigger);
4369 } else {
4370 /**
4371 * More typical, no trigger entry, so we just add it
4372 */
4373 mTriggerRemovedMap.add(tag, trigger);
4374 }
4375
4376 status_t res;
4377
4378 switch (trigger.getTagType()) {
4379 case TYPE_BYTE: {
4380 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4381 res = metadata.update(tag,
4382 &entryValue,
4383 /*count*/1);
4384 break;
4385 }
4386 case TYPE_INT32:
4387 res = metadata.update(tag,
4388 &trigger.entryValue,
4389 /*count*/1);
4390 break;
4391 default:
4392 ALOGE("%s: Type not supported: 0x%x",
4393 __FUNCTION__,
4394 trigger.getTagType());
4395 return INVALID_OPERATION;
4396 }
4397
4398 if (res != OK) {
4399 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4400 ", value %d", __FUNCTION__, trigger.getTagName(),
4401 trigger.entryValue);
4402 return res;
4403 }
4404
4405 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4406 trigger.getTagName(),
4407 trigger.entryValue);
4408 }
4409
4410 mTriggerMap.clear();
4411
4412 return count;
4413}
4414
4415status_t Camera3Device::RequestThread::removeTriggers(
4416 const sp<CaptureRequest> &request) {
4417 Mutex::Autolock al(mTriggerMutex);
4418
4419 CameraMetadata &metadata = request->mSettings;
4420
4421 /**
4422 * Replace all old entries with their old values.
4423 */
4424 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4425 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4426
4427 status_t res;
4428
4429 uint32_t tag = trigger.metadataTag;
4430 switch (trigger.getTagType()) {
4431 case TYPE_BYTE: {
4432 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4433 res = metadata.update(tag,
4434 &entryValue,
4435 /*count*/1);
4436 break;
4437 }
4438 case TYPE_INT32:
4439 res = metadata.update(tag,
4440 &trigger.entryValue,
4441 /*count*/1);
4442 break;
4443 default:
4444 ALOGE("%s: Type not supported: 0x%x",
4445 __FUNCTION__,
4446 trigger.getTagType());
4447 return INVALID_OPERATION;
4448 }
4449
4450 if (res != OK) {
4451 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4452 ", trigger value %d", __FUNCTION__,
4453 trigger.getTagName(), trigger.entryValue);
4454 return res;
4455 }
4456 }
4457 mTriggerReplacedMap.clear();
4458
4459 /**
4460 * Remove all new entries.
4461 */
4462 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4463 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4464 status_t res = metadata.erase(trigger.metadataTag);
4465
4466 if (res != OK) {
4467 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4468 ", trigger value %d", __FUNCTION__,
4469 trigger.getTagName(), trigger.entryValue);
4470 return res;
4471 }
4472 }
4473 mTriggerRemovedMap.clear();
4474
4475 return OK;
4476}
4477
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004478status_t Camera3Device::RequestThread::addDummyTriggerIds(
4479 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004480 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004481 static const int32_t dummyTriggerId = 1;
4482 status_t res;
4483
4484 CameraMetadata &metadata = request->mSettings;
4485
4486 // If AF trigger is active, insert a dummy AF trigger ID if none already
4487 // exists
4488 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4489 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4490 if (afTrigger.count > 0 &&
4491 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4492 afId.count == 0) {
4493 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4494 if (res != OK) return res;
4495 }
4496
4497 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4498 // if none already exists
4499 camera_metadata_entry pcTrigger =
4500 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4501 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4502 if (pcTrigger.count > 0 &&
4503 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4504 pcId.count == 0) {
4505 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4506 &dummyTriggerId, 1);
4507 if (res != OK) return res;
4508 }
4509
4510 return OK;
4511}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004512
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004513/**
4514 * PreparerThread inner class methods
4515 */
4516
4517Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004518 Thread(/*canCallJava*/false), mListener(nullptr),
4519 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004520}
4521
4522Camera3Device::PreparerThread::~PreparerThread() {
4523 Thread::requestExitAndWait();
4524 if (mCurrentStream != nullptr) {
4525 mCurrentStream->cancelPrepare();
4526 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4527 mCurrentStream.clear();
4528 }
4529 clear();
4530}
4531
Ruben Brunkc78ac262015-08-13 17:58:46 -07004532status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004533 status_t res;
4534
4535 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004536 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004537
Ruben Brunkc78ac262015-08-13 17:58:46 -07004538 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004539 if (res == OK) {
4540 // No preparation needed, fire listener right off
4541 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004542 if (listener != NULL) {
4543 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004544 }
4545 return OK;
4546 } else if (res != NOT_ENOUGH_DATA) {
4547 return res;
4548 }
4549
4550 // Need to prepare, start up thread if necessary
4551 if (!mActive) {
4552 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4553 // isn't running
4554 Thread::requestExitAndWait();
4555 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4556 if (res != OK) {
4557 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004558 if (listener != NULL) {
4559 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004560 }
4561 return res;
4562 }
4563 mCancelNow = false;
4564 mActive = true;
4565 ALOGV("%s: Preparer stream started", __FUNCTION__);
4566 }
4567
4568 // queue up the work
4569 mPendingStreams.push_back(stream);
4570 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4571
4572 return OK;
4573}
4574
4575status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004576 Mutex::Autolock l(mLock);
4577
4578 for (const auto& stream : mPendingStreams) {
4579 stream->cancelPrepare();
4580 }
4581 mPendingStreams.clear();
4582 mCancelNow = true;
4583
4584 return OK;
4585}
4586
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004587void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004588 Mutex::Autolock l(mLock);
4589 mListener = listener;
4590}
4591
4592bool Camera3Device::PreparerThread::threadLoop() {
4593 status_t res;
4594 {
4595 Mutex::Autolock l(mLock);
4596 if (mCurrentStream == nullptr) {
4597 // End thread if done with work
4598 if (mPendingStreams.empty()) {
4599 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4600 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4601 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4602 mActive = false;
4603 return false;
4604 }
4605
4606 // Get next stream to prepare
4607 auto it = mPendingStreams.begin();
4608 mCurrentStream = *it;
4609 mPendingStreams.erase(it);
4610 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4611 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4612 } else if (mCancelNow) {
4613 mCurrentStream->cancelPrepare();
4614 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4615 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4616 mCurrentStream.clear();
4617 mCancelNow = false;
4618 return true;
4619 }
4620 }
4621
4622 res = mCurrentStream->prepareNextBuffer();
4623 if (res == NOT_ENOUGH_DATA) return true;
4624 if (res != OK) {
4625 // Something bad happened; try to recover by cancelling prepare and
4626 // signalling listener anyway
4627 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4628 mCurrentStream->getId(), res, strerror(-res));
4629 mCurrentStream->cancelPrepare();
4630 }
4631
4632 // This stream has finished, notify listener
4633 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004634 sp<NotificationListener> listener = mListener.promote();
4635 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004636 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4637 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004638 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004639 }
4640
4641 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4642 mCurrentStream.clear();
4643
4644 return true;
4645}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004646
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004647/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004648 * Static callback forwarding methods from HAL to instance
4649 */
4650
4651void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4652 const camera3_capture_result *result) {
4653 Camera3Device *d =
4654 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004655
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004656 d->processCaptureResult(result);
4657}
4658
4659void Camera3Device::sNotify(const camera3_callback_ops *cb,
4660 const camera3_notify_msg *msg) {
4661 Camera3Device *d =
4662 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4663 d->notify(msg);
4664}
4665
4666}; // namespace android