blob: 2bdb00812c221d60ebe0793b681022063f30d3e7 [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 Talvalaf76e0272013-02-27 18:02:26 -080097/**
98 * CameraDeviceBase interface
99 */
100
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800101status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102{
103 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700104 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800105 Mutex::Autolock l(mLock);
106
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800108 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700109 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110 return INVALID_OPERATION;
111 }
112
113 /** Open HAL device */
114
115 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800116
117 camera3_device_t *device;
118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119 ATRACE_BEGIN("CameraHal::open");
120 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800121 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800122 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800123
124 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700125 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800126 return res;
127 }
128
129 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700131 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700132 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800134 device->common.version);
135 device->common.close(&device->common);
136 return BAD_VALUE;
137 }
138
139 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800141 if (res != OK) return res;
142
143 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700144 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
145 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700146 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800147 device->common.close(&device->common);
148 return BAD_VALUE;
149 }
150
151 /** Initialize device with callback functions */
152
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800153 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800154 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700155 ATRACE_END();
156
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800157 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700158 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
159 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800160 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800161 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800162 }
163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800164 /** Everything is good to go */
165
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800166 mDeviceInfo = info.static_camera_characteristics;
167 mInterface = std::make_unique<HalInterface>(device);
168
169 return initializeCommonLocked();
170}
171
172status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
173 ATRACE_CALL();
174 Mutex::Autolock il(mInterfaceLock);
175 Mutex::Autolock l(mLock);
176
177 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
178 if (mStatus != STATUS_UNINITIALIZED) {
179 CLOGE("Already initialized!");
180 return INVALID_OPERATION;
181 }
182 if (manager == nullptr) return INVALID_OPERATION;
183
184 sp<ICameraDeviceSession> session;
185 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800186 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800187 /*out*/ &session);
188 ATRACE_END();
189 if (res != OK) {
190 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
191 return res;
192 }
193
Steven Moreland5ff9c912017-03-09 23:13:00 -0800194 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800195 if (res != OK) {
196 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
197 session->close();
198 return res;
199 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800200
Yifan Hongf79b5542017-04-11 14:44:25 -0700201 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
203 [&queue](const auto& descriptor) {
204 queue = std::make_shared<RequestMetadataQueue>(descriptor);
205 if (!queue->isValid() || queue->availableToWrite() <= 0) {
206 ALOGE("HAL returns empty request metadata fmq, not use it");
207 queue = nullptr;
208 // don't use the queue onwards.
209 }
210 });
211 if (!requestQueueRet.isOk()) {
212 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
213 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700214 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700215 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700216 auto resultQueueRet = session->getCaptureResultMetadataQueue(
217 [&queue = mResultMetadataQueue](const auto& descriptor) {
218 queue = std::make_unique<ResultMetadataQueue>(descriptor);
219 if (!queue->isValid() || queue->availableToWrite() <= 0) {
220 ALOGE("HAL returns empty result metadata fmq, not use it");
221 queue = nullptr;
222 // Don't use the queue onwards.
223 }
224 });
225 if (!resultQueueRet.isOk()) {
226 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
227 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700228 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700229 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700230
Yifan Hongf79b5542017-04-11 14:44:25 -0700231 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000232 std::string providerType;
233 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234
235 return initializeCommonLocked();
236}
237
238status_t Camera3Device::initializeCommonLocked() {
239
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700240 /** Start up status tracker thread */
241 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800242 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700243 if (res != OK) {
244 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
245 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800246 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700247 mStatusTracker.clear();
248 return res;
249 }
250
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700251 /** Register in-flight map to the status tracker */
252 mInFlightStatusId = mStatusTracker->addComponent();
253
Zhijun He125684a2015-12-26 15:07:30 -0800254 /** Create buffer manager */
255 mBufferManager = new Camera3BufferManager();
256
Emilian Peev71c73a22017-03-21 16:35:51 +0000257 mTagMonitor.initialize(mVendorTagId);
258
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700259 /** Start up request queue thread */
Emilian Peev7e25e5e2017-04-07 15:48:49 +0100260 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800261 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800262 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700263 SET_ERR_L("Unable to start request queue thread: %s (%d)",
264 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800265 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800266 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800267 return res;
268 }
269
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700270 mPreparerThread = new PreparerThread();
271
Ruben Brunk183f0562015-08-12 12:55:02 -0700272 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800273 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700274 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700275 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800277
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800278 // Measure the clock domain offset between camera and video/hw_composer
279 camera_metadata_entry timestampSource =
280 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
281 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
282 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
283 mTimestampOffset = getMonoToBoottimeOffset();
284 }
285
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700286 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100287 camera_metadata_entry partialResultsCount =
288 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
289 if (partialResultsCount.count > 0) {
290 mNumPartialResults = partialResultsCount.data.i32[0];
291 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700292 }
293
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700294 camera_metadata_entry configs =
295 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
296 for (uint32_t i = 0; i < configs.count; i += 4) {
297 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
298 configs.data.i32[i + 3] ==
299 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
300 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
301 configs.data.i32[i + 2]));
302 }
303 }
304
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800305 return OK;
306}
307
308status_t Camera3Device::disconnect() {
309 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800311
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700312 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800313
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700314 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 {
317 Mutex::Autolock l(mLock);
318 if (mStatus == STATUS_UNINITIALIZED) return res;
319
320 if (mStatus == STATUS_ACTIVE ||
321 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
322 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700323 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700325 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 } else {
327 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
328 if (res != OK) {
329 SET_ERR_L("Timeout waiting for HAL to drain");
330 // Continue to close device even in case of error
331 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700332 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800334
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700335 if (mStatus == STATUS_ERROR) {
336 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700337 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700338
339 if (mStatusTracker != NULL) {
340 mStatusTracker->requestExit();
341 }
342
343 if (mRequestThread != NULL) {
344 mRequestThread->requestExit();
345 }
346
347 mOutputStreams.clear();
348 mInputStream.clear();
349 }
350
351 // Joining done without holding mLock, otherwise deadlocks may ensue
352 // as the threads try to access parent state
353 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
354 // HAL may be in a bad state, so waiting for request thread
355 // (which may be stuck in the HAL processCaptureRequest call)
356 // could be dangerous.
357 mRequestThread->join();
358 }
359
360 if (mStatusTracker != NULL) {
361 mStatusTracker->join();
362 }
363
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800364 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700365 {
366 Mutex::Autolock l(mLock);
367
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800370 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800371
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800372 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700373 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800374
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700375 // Call close without internal mutex held, as the HAL close may need to
376 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800377 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700378
379 {
380 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800381 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700382 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800384
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700385 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700386 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800387}
388
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700389// For dumping/debugging only -
390// try to acquire a lock a few times, eventually give up to proceed with
391// debug/dump operations
392bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
393 bool gotLock = false;
394 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
395 if (lock.tryLock() == NO_ERROR) {
396 gotLock = true;
397 break;
398 } else {
399 usleep(kDumpSleepDuration);
400 }
401 }
402 return gotLock;
403}
404
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
406 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100407 const int STREAM_CONFIGURATION_SIZE = 4;
408 const int STREAM_FORMAT_OFFSET = 0;
409 const int STREAM_WIDTH_OFFSET = 1;
410 const int STREAM_HEIGHT_OFFSET = 2;
411 const int STREAM_IS_INPUT_OFFSET = 3;
412 camera_metadata_ro_entry_t availableStreamConfigs =
413 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
414 if (availableStreamConfigs.count == 0 ||
415 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
416 return Size(0, 0);
417 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700418
Emilian Peev08dd2452017-04-06 16:55:14 +0100419 // Get max jpeg size (area-wise).
420 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
421 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
422 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
423 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
424 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
425 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
426 && format == HAL_PIXEL_FORMAT_BLOB &&
427 (width * height > maxJpegWidth * maxJpegHeight)) {
428 maxJpegWidth = width;
429 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700430 }
431 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100432
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700433 return Size(maxJpegWidth, maxJpegHeight);
434}
435
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800436nsecs_t Camera3Device::getMonoToBoottimeOffset() {
437 // try three times to get the clock offset, choose the one
438 // with the minimum gap in measurements.
439 const int tries = 3;
440 nsecs_t bestGap, measured;
441 for (int i = 0; i < tries; ++i) {
442 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
443 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
444 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
445 const nsecs_t gap = tmono2 - tmono;
446 if (i == 0 || gap < bestGap) {
447 bestGap = gap;
448 measured = tbase - ((tmono + tmono2) >> 1);
449 }
450 }
451 return measured;
452}
453
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800454hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
455 int frameworkFormat) {
456 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
457}
458
459DataspaceFlags Camera3Device::mapToHidlDataspace(
460 android_dataspace dataSpace) {
461 return dataSpace;
462}
463
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700464BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700465 uint32_t usage) {
466 return usage;
467}
468
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800469StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
470 switch (rotation) {
471 case CAMERA3_STREAM_ROTATION_0:
472 return StreamRotation::ROTATION_0;
473 case CAMERA3_STREAM_ROTATION_90:
474 return StreamRotation::ROTATION_90;
475 case CAMERA3_STREAM_ROTATION_180:
476 return StreamRotation::ROTATION_180;
477 case CAMERA3_STREAM_ROTATION_270:
478 return StreamRotation::ROTATION_270;
479 }
480 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
481 return StreamRotation::ROTATION_0;
482}
483
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800484status_t Camera3Device::mapToStreamConfigurationMode(
485 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
486 if (mode == nullptr) return BAD_VALUE;
487 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
488 switch(operationMode) {
489 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
490 *mode = StreamConfigurationMode::NORMAL_MODE;
491 break;
492 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
493 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
494 break;
495 default:
496 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
497 return BAD_VALUE;
498 }
499 } else {
500 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800501 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800502 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800503}
504
505camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
506 switch (status) {
507 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
508 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
509 }
510 return CAMERA3_BUFFER_STATUS_ERROR;
511}
512
513int Camera3Device::mapToFrameworkFormat(
514 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
515 return static_cast<uint32_t>(pixelFormat);
516}
517
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700518uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700519 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700520 return usage;
521}
522
523uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700524 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700525 return usage;
526}
527
Zhijun Hef7da0962014-04-24 13:27:56 -0700528ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700529 // Get max jpeg size (area-wise).
530 Size maxJpegResolution = getMaxJpegResolution();
531 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800532 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
533 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700534 return BAD_VALUE;
535 }
536
Zhijun Hef7da0962014-04-24 13:27:56 -0700537 // Get max jpeg buffer size
538 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700539 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
540 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800541 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
542 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700543 return BAD_VALUE;
544 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700545 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800546 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700547
548 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700549 float scaleFactor = ((float) (width * height)) /
550 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800551 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
552 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700553 if (jpegBufferSize > maxJpegBufferSize) {
554 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700555 }
556
557 return jpegBufferSize;
558}
559
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700560ssize_t Camera3Device::getPointCloudBufferSize() const {
561 const int FLOATS_PER_POINT=4;
562 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
563 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800564 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
565 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700566 return BAD_VALUE;
567 }
568 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
569 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
570 return maxBytesForPointCloud;
571}
572
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800573ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800574 const int PER_CONFIGURATION_SIZE = 3;
575 const int WIDTH_OFFSET = 0;
576 const int HEIGHT_OFFSET = 1;
577 const int SIZE_OFFSET = 2;
578 camera_metadata_ro_entry rawOpaqueSizes =
579 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800580 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800581 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
583 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800584 return BAD_VALUE;
585 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700586
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800587 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
588 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
589 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
590 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
591 }
592 }
593
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800594 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
595 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800596 return BAD_VALUE;
597}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700598
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800599status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
600 ATRACE_CALL();
601 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700602
603 // Try to lock, but continue in case of failure (to avoid blocking in
604 // deadlocks)
605 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
606 bool gotLock = tryLockSpinRightRound(mLock);
607
608 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
610 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700611 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800612 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
613 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700614
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800615 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700616
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800617 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700618 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800619 int n = args.size();
620 for (int i = 0; i < n; i++) {
621 if (args[i] == templatesOption) {
622 dumpTemplates = true;
623 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700624 if (args[i] == monitorOption) {
625 if (i + 1 < n) {
626 String8 monitorTags = String8(args[i + 1]);
627 if (monitorTags == "off") {
628 mTagMonitor.disableMonitoring();
629 } else {
630 mTagMonitor.parseTagsToMonitor(monitorTags);
631 }
632 } else {
633 mTagMonitor.disableMonitoring();
634 }
635 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800636 }
637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800638 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 const char *status =
641 mStatus == STATUS_ERROR ? "ERROR" :
642 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700643 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
644 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800645 mStatus == STATUS_ACTIVE ? "ACTIVE" :
646 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700647
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800648 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700649 if (mStatus == STATUS_ERROR) {
650 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
651 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800652 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800653 const char *mode =
654 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
655 mOperatingMode == static_cast<int>(
656 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
657 "CUSTOM";
658 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800659
660 if (mInputStream != NULL) {
661 write(fd, lines.string(), lines.size());
662 mInputStream->dump(fd, args);
663 } else {
664 lines.appendFormat(" No input stream.\n");
665 write(fd, lines.string(), lines.size());
666 }
667 for (size_t i = 0; i < mOutputStreams.size(); i++) {
668 mOutputStreams[i]->dump(fd,args);
669 }
670
Zhijun He431503c2016-03-07 17:30:16 -0800671 if (mBufferManager != NULL) {
672 lines = String8(" Camera3 Buffer Manager:\n");
673 write(fd, lines.string(), lines.size());
674 mBufferManager->dump(fd, args);
675 }
Zhijun He125684a2015-12-26 15:07:30 -0800676
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700677 lines = String8(" In-flight requests:\n");
678 if (mInFlightMap.size() == 0) {
679 lines.append(" None\n");
680 } else {
681 for (size_t i = 0; i < mInFlightMap.size(); i++) {
682 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700683 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700684 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800685 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700686 r.numBuffersLeft);
687 }
688 }
689 write(fd, lines.string(), lines.size());
690
Igor Murashkin1e479c02013-09-06 16:55:14 -0700691 {
692 lines = String8(" Last request sent:\n");
693 write(fd, lines.string(), lines.size());
694
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700695 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700696 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
697 }
698
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800699 if (dumpTemplates) {
700 const char *templateNames[] = {
701 "TEMPLATE_PREVIEW",
702 "TEMPLATE_STILL_CAPTURE",
703 "TEMPLATE_VIDEO_RECORD",
704 "TEMPLATE_VIDEO_SNAPSHOT",
705 "TEMPLATE_ZERO_SHUTTER_LAG",
706 "TEMPLATE_MANUAL"
707 };
708
709 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800710 camera_metadata_t *templateRequest = nullptr;
711 mInterface->constructDefaultRequestSettings(
712 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800713 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800714 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800715 lines.append(" Not supported\n");
716 write(fd, lines.string(), lines.size());
717 } else {
718 write(fd, lines.string(), lines.size());
719 dump_indented_camera_metadata(templateRequest,
720 fd, /*verbosity*/2, /*indentation*/8);
721 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800722 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800723 }
724 }
725
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700726 mTagMonitor.dumpMonitoredMetadata(fd);
727
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800728 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800729 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800730 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800731 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800732 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800733
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700734 if (gotLock) mLock.unlock();
735 if (gotInterfaceLock) mInterfaceLock.unlock();
736
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800737 return OK;
738}
739
740const CameraMetadata& Camera3Device::info() const {
741 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
743 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700744 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800745 mStatus == STATUS_ERROR ?
746 "when in error state" : "before init");
747 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800748 return mDeviceInfo;
749}
750
Jianing Wei90e59c92014-03-12 18:29:36 -0700751status_t Camera3Device::checkStatusOkToCaptureLocked() {
752 switch (mStatus) {
753 case STATUS_ERROR:
754 CLOGE("Device has encountered a serious error");
755 return INVALID_OPERATION;
756 case STATUS_UNINITIALIZED:
757 CLOGE("Device not initialized");
758 return INVALID_OPERATION;
759 case STATUS_UNCONFIGURED:
760 case STATUS_CONFIGURED:
761 case STATUS_ACTIVE:
762 // OK
763 break;
764 default:
765 SET_ERR_L("Unexpected status: %d", mStatus);
766 return INVALID_OPERATION;
767 }
768 return OK;
769}
770
771status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700772 const List<const CameraMetadata> &metadataList,
773 const std::list<const SurfaceMap> &surfaceMaps,
774 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700775 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700776 if (requestList == NULL) {
777 CLOGE("requestList cannot be NULL.");
778 return BAD_VALUE;
779 }
780
Jianing Weicb0652e2014-03-12 18:29:36 -0700781 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700782 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
783 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
784 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
785 ++metadataIt, ++surfaceMapIt) {
786 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700787 if (newRequest == 0) {
788 CLOGE("Can't create capture request");
789 return BAD_VALUE;
790 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700791
Shuzhen Wang9d066012016-09-30 11:30:20 -0700792 newRequest->mRepeating = repeating;
793
Jianing Weicb0652e2014-03-12 18:29:36 -0700794 // Setup burst Id and request Id
795 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
797 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700798 CLOGE("RequestID entry exists; but must not be empty in metadata");
799 return BAD_VALUE;
800 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700801 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700802 } else {
803 CLOGE("RequestID does not exist in metadata");
804 return BAD_VALUE;
805 }
806
Jianing Wei90e59c92014-03-12 18:29:36 -0700807 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700808
809 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
812 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
813 return BAD_VALUE;
814 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700815
816 // Setup batch size if this is a high speed video recording request.
817 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
818 auto firstRequest = requestList->begin();
819 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
820 if (outputStream->isVideoStream()) {
821 (*firstRequest)->mBatchSize = requestList->size();
822 break;
823 }
824 }
825 }
826
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 return OK;
828}
829
Jianing Weicb0652e2014-03-12 18:29:36 -0700830status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700833 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 std::list<const SurfaceMap> surfaceMaps;
835 convertToRequestList(requests, surfaceMaps, request);
836
837 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
838}
839
840void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
841 std::list<const SurfaceMap>& surfaceMaps,
842 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700843 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700844
845 SurfaceMap surfaceMap;
846 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
847 // With no surface list passed in, stream and surface will have 1-to-1
848 // mapping. So the surface index is 0 for each stream in the surfaceMap.
849 for (size_t i = 0; i < streams.count; i++) {
850 surfaceMap[streams.data.i32[i]].push_back(0);
851 }
852 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800853}
854
Jianing Wei90e59c92014-03-12 18:29:36 -0700855status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700856 const List<const CameraMetadata> &requests,
857 const std::list<const SurfaceMap> &surfaceMaps,
858 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700859 /*out*/
860 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700861 ATRACE_CALL();
862 Mutex::Autolock il(mInterfaceLock);
863 Mutex::Autolock l(mLock);
864
865 status_t res = checkStatusOkToCaptureLocked();
866 if (res != OK) {
867 // error logged by previous call
868 return res;
869 }
870
871 RequestList requestList;
872
Shuzhen Wang0129d522016-10-30 22:43:41 -0700873 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
874 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700875 if (res != OK) {
876 // error logged by previous call
877 return res;
878 }
879
880 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700881 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700883 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 }
885
886 if (res == OK) {
887 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
888 if (res != OK) {
889 SET_ERR_L("Can't transition to active in %f seconds!",
890 kActiveTimeout/1e9);
891 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800892 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700893 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700894 } else {
895 CLOGE("Cannot queue request. Impossible.");
896 return BAD_VALUE;
897 }
898
899 return res;
900}
901
Yifan Honga640c5a2017-04-12 16:30:31 -0700902// Only one processCaptureResult should be called at a time, so
903// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800904hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800905 const hardware::hidl_vec<
906 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700907
908 if (mProcessCaptureResultLock.tryLock() != OK) {
909 // This should never happen; it indicates a wrong client implementation
910 // that doesn't follow the contract. But, we can be tolerant here.
911 ALOGE("%s: callback overlapped! waiting 1s...",
912 __FUNCTION__);
913 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
914 ALOGE("%s: cannot acquire lock in 1s, dropping results",
915 __FUNCTION__);
916 // really don't know what to do, so bail out.
917 return hardware::Void();
918 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800919 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700920 for (const auto& result : results) {
921 processOneCaptureResultLocked(result);
922 }
923 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800924 return hardware::Void();
925}
926
Yifan Honga640c5a2017-04-12 16:30:31 -0700927void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800928 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800929 camera3_capture_result r;
930 status_t res;
931 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700932
933 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
934 if (result.fmqResultSize > 0) {
935 resultMetadata.resize(result.fmqResultSize);
936 if (mResultMetadataQueue == nullptr) {
937 return; // logged in initialize()
938 }
939 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
940 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
941 __FUNCTION__, result.frameNumber, result.fmqResultSize);
942 return;
943 }
944 } else {
945 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
946 result.result.size());
947 }
948
949 if (resultMetadata.size() != 0) {
950 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
951 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800952 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
953 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
954 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800955 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800956 }
957 } else {
958 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800959 }
960
961 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
962 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
963 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
964 auto& bDst = outputBuffers[i];
965 const StreamBuffer &bSrc = result.outputBuffers[i];
966
967 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100968 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800969 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
970 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800971 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800972 }
973 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
974
975 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800976 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800977 if (res != OK) {
978 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
979 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800980 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 }
982 bDst.buffer = buffer;
983 bDst.status = mapHidlBufferStatus(bSrc.status);
984 bDst.acquire_fence = -1;
985 if (bSrc.releaseFence == nullptr) {
986 bDst.release_fence = -1;
987 } else if (bSrc.releaseFence->numFds == 1) {
988 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
989 } else {
990 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
991 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800992 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800993 }
994 }
995 r.num_output_buffers = outputBuffers.size();
996 r.output_buffers = outputBuffers.data();
997
998 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800999 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 r.input_buffer = nullptr;
1001 } else {
1002 if (mInputStream->getId() != result.inputBuffer.streamId) {
1003 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1004 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001005 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001006 }
1007 inputBuffer.stream = mInputStream->asHalStream();
1008 buffer_handle_t *buffer;
1009 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1010 &buffer);
1011 if (res != OK) {
1012 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1013 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001014 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001015 }
1016 inputBuffer.buffer = buffer;
1017 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1018 inputBuffer.acquire_fence = -1;
1019 if (result.inputBuffer.releaseFence == nullptr) {
1020 inputBuffer.release_fence = -1;
1021 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1022 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1023 } else {
1024 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1025 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001026 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001027 }
1028 r.input_buffer = &inputBuffer;
1029 }
1030
1031 r.partial_result = result.partialResult;
1032
1033 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001034}
1035
1036hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001037 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1038 for (const auto& msg : msgs) {
1039 notify(msg);
1040 }
1041 return hardware::Void();
1042}
1043
1044void Camera3Device::notify(
1045 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1046
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001047 camera3_notify_msg m;
1048 switch (msg.type) {
1049 case MsgType::ERROR:
1050 m.type = CAMERA3_MSG_ERROR;
1051 m.message.error.frame_number = msg.msg.error.frameNumber;
1052 if (msg.msg.error.errorStreamId >= 0) {
1053 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001054 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001055 ALOGE("%s: Frame %d: Invalid error stream id %d",
1056 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001057 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001058 }
1059 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1060 } else {
1061 m.message.error.error_stream = nullptr;
1062 }
1063 switch (msg.msg.error.errorCode) {
1064 case ErrorCode::ERROR_DEVICE:
1065 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1066 break;
1067 case ErrorCode::ERROR_REQUEST:
1068 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1069 break;
1070 case ErrorCode::ERROR_RESULT:
1071 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1072 break;
1073 case ErrorCode::ERROR_BUFFER:
1074 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1075 break;
1076 }
1077 break;
1078 case MsgType::SHUTTER:
1079 m.type = CAMERA3_MSG_SHUTTER;
1080 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1081 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1082 break;
1083 }
1084 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001085}
1086
Jianing Weicb0652e2014-03-12 18:29:36 -07001087status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001088 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001089 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001090 ATRACE_CALL();
1091
Shuzhen Wang0129d522016-10-30 22:43:41 -07001092 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001093}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001094
Jianing Weicb0652e2014-03-12 18:29:36 -07001095status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1096 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001097 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001098
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001099 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001100 std::list<const SurfaceMap> surfaceMaps;
1101 convertToRequestList(requests, surfaceMaps, request);
1102
1103 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1104 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001105}
1106
Jianing Weicb0652e2014-03-12 18:29:36 -07001107status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001108 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001109 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001110 ATRACE_CALL();
1111
Shuzhen Wang0129d522016-10-30 22:43:41 -07001112 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001113}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001114
1115sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001116 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 status_t res;
1118
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001119 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001120 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1121 // so unilaterally select normal operating mode.
1122 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001123 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001124 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001125 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001127 } else if (mStatus == STATUS_UNCONFIGURED) {
1128 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001129 CLOGE("No streams configured");
1130 return NULL;
1131 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 }
1133
Shuzhen Wang0129d522016-10-30 22:43:41 -07001134 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001135 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001136}
1137
Jianing Weicb0652e2014-03-12 18:29:36 -07001138status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001139 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001140 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001141 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 switch (mStatus) {
1144 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001145 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001146 return INVALID_OPERATION;
1147 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001148 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001150 case STATUS_UNCONFIGURED:
1151 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 case STATUS_ACTIVE:
1153 // OK
1154 break;
1155 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001156 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001157 return INVALID_OPERATION;
1158 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001159 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001160
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001161 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001162}
1163
1164status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1165 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001166 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001167
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001168 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169}
1170
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001171status_t Camera3Device::createInputStream(
1172 uint32_t width, uint32_t height, int format, int *id) {
1173 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001175 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001176 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1177 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001178
1179 status_t res;
1180 bool wasActive = false;
1181
1182 switch (mStatus) {
1183 case STATUS_ERROR:
1184 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1185 return INVALID_OPERATION;
1186 case STATUS_UNINITIALIZED:
1187 ALOGE("%s: Device not initialized", __FUNCTION__);
1188 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 case STATUS_UNCONFIGURED:
1190 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001191 // OK
1192 break;
1193 case STATUS_ACTIVE:
1194 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001197 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001198 return res;
1199 }
1200 wasActive = true;
1201 break;
1202 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001203 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001204 return INVALID_OPERATION;
1205 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001207
1208 if (mInputStream != 0) {
1209 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1210 return INVALID_OPERATION;
1211 }
1212
1213 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1214 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001216
1217 mInputStream = newStream;
1218
1219 *id = mNextStreamId++;
1220
1221 // Continue captures if active at start
1222 if (wasActive) {
1223 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001224 // Reuse current operating mode for new stream config
1225 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001226 if (res != OK) {
1227 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1228 __FUNCTION__, mNextStreamId, strerror(-res), res);
1229 return res;
1230 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001231 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001232 }
1233
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001234 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001235 return OK;
1236}
1237
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001238status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001239 uint32_t width, uint32_t height, int format,
1240 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001241 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001242 ATRACE_CALL();
1243
1244 if (consumer == nullptr) {
1245 ALOGE("%s: consumer must not be null", __FUNCTION__);
1246 return BAD_VALUE;
1247 }
1248
1249 std::vector<sp<Surface>> consumers;
1250 consumers.push_back(consumer);
1251
1252 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001253 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001254}
1255
1256status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1257 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1258 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001259 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001260 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001263 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001264 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1265 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001266
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 status_t res;
1268 bool wasActive = false;
1269
1270 switch (mStatus) {
1271 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001272 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 return INVALID_OPERATION;
1274 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001275 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 case STATUS_UNCONFIGURED:
1278 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279 // OK
1280 break;
1281 case STATUS_ACTIVE:
1282 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001285 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 return res;
1287 }
1288 wasActive = true;
1289 break;
1290 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001291 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 return INVALID_OPERATION;
1293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001294 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001295
1296 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001297
Shuzhen Wang0129d522016-10-30 22:43:41 -07001298 if (consumers.size() == 0 && !hasDeferredConsumer) {
1299 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1300 return BAD_VALUE;
1301 }
Zhijun He5d677d12016-05-29 16:52:39 -07001302
Shuzhen Wang0129d522016-10-30 22:43:41 -07001303 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001304 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1305 return BAD_VALUE;
1306 }
1307
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001309 ssize_t blobBufferSize;
1310 if (dataSpace != HAL_DATASPACE_DEPTH) {
1311 blobBufferSize = getJpegBufferSize(width, height);
1312 if (blobBufferSize <= 0) {
1313 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1314 return BAD_VALUE;
1315 }
1316 } else {
1317 blobBufferSize = getPointCloudBufferSize();
1318 if (blobBufferSize <= 0) {
1319 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1320 return BAD_VALUE;
1321 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001322 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001323 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001324 width, height, blobBufferSize, format, dataSpace, rotation,
1325 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001326 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1327 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1328 if (rawOpaqueBufferSize <= 0) {
1329 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1330 return BAD_VALUE;
1331 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001332 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001333 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1334 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001335 } else if (isShared) {
1336 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1337 width, height, format, consumerUsage, dataSpace, rotation,
1338 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001339 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001340 newStream = new Camera3OutputStream(mNextStreamId,
1341 width, height, format, consumerUsage, dataSpace, rotation,
1342 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001344 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001345 width, height, format, dataSpace, rotation,
1346 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001348 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001349
Emilian Peev08dd2452017-04-06 16:55:14 +01001350 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001351
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 res = mOutputStreams.add(mNextStreamId, newStream);
1353 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001354 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001355 return res;
1356 }
1357
1358 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001359 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001360
1361 // Continue captures if active at start
1362 if (wasActive) {
1363 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001364 // Reuse current operating mode for new stream config
1365 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001367 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1368 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 return res;
1370 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001371 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001373 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001374 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001375}
1376
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001378 uint32_t *width, uint32_t *height,
1379 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001380 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001381 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 switch (mStatus) {
1385 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001386 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 return INVALID_OPERATION;
1388 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001389 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001391 case STATUS_UNCONFIGURED:
1392 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 case STATUS_ACTIVE:
1394 // OK
1395 break;
1396 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001397 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 return INVALID_OPERATION;
1399 }
1400
1401 ssize_t idx = mOutputStreams.indexOfKey(id);
1402 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001403 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 return idx;
1405 }
1406
1407 if (width) *width = mOutputStreams[idx]->getWidth();
1408 if (height) *height = mOutputStreams[idx]->getHeight();
1409 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001410 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001412}
1413
1414status_t Camera3Device::setStreamTransform(int id,
1415 int transform) {
1416 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001417 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001418 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 switch (mStatus) {
1421 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001422 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return INVALID_OPERATION;
1424 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001425 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001427 case STATUS_UNCONFIGURED:
1428 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 case STATUS_ACTIVE:
1430 // OK
1431 break;
1432 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001433 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 return INVALID_OPERATION;
1435 }
1436
1437 ssize_t idx = mOutputStreams.indexOfKey(id);
1438 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001439 CLOGE("Stream %d does not exist",
1440 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 return BAD_VALUE;
1442 }
1443
1444 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001445}
1446
1447status_t Camera3Device::deleteStream(int id) {
1448 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 Mutex::Autolock l(mLock);
1451 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001452
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001453 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001454
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 // CameraDevice semantics require device to already be idle before
1456 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001458 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001459 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 }
1461
Igor Murashkin2fba5842013-04-22 14:03:54 -07001462 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001463 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 if (mInputStream != NULL && id == mInputStream->getId()) {
1465 deletedStream = mInputStream;
1466 mInputStream.clear();
1467 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001468 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001469 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 return BAD_VALUE;
1471 }
Zhijun He5f446352014-01-22 09:49:33 -08001472 }
1473
1474 // Delete output stream or the output part of a bi-directional stream.
1475 if (outputStreamIdx != NAME_NOT_FOUND) {
1476 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 mOutputStreams.removeItem(id);
1478 }
1479
1480 // Free up the stream endpoint so that it can be used by some other stream
1481 res = deletedStream->disconnect();
1482 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 // fall through since we want to still list the stream as deleted.
1485 }
1486 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001487 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488
1489 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001490}
1491
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001492status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001493 ATRACE_CALL();
1494 ALOGV("%s: E", __FUNCTION__);
1495
1496 Mutex::Autolock il(mInterfaceLock);
1497 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001498
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001499 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001500}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001501
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001502status_t Camera3Device::getInputBufferProducer(
1503 sp<IGraphicBufferProducer> *producer) {
1504 Mutex::Autolock il(mInterfaceLock);
1505 Mutex::Autolock l(mLock);
1506
1507 if (producer == NULL) {
1508 return BAD_VALUE;
1509 } else if (mInputStream == NULL) {
1510 return INVALID_OPERATION;
1511 }
1512
1513 return mInputStream->getInputBufferProducer(producer);
1514}
1515
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516status_t Camera3Device::createDefaultRequest(int templateId,
1517 CameraMetadata *request) {
1518 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001519 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001520
1521 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1522 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1523 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1524 return BAD_VALUE;
1525 }
1526
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001527 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 Mutex::Autolock l(mLock);
1529
1530 switch (mStatus) {
1531 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001532 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 return INVALID_OPERATION;
1534 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001535 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 case STATUS_UNCONFIGURED:
1538 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 case STATUS_ACTIVE:
1540 // OK
1541 break;
1542 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001543 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return INVALID_OPERATION;
1545 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546
Zhijun Hea1530f12014-09-14 12:44:20 -07001547 if (!mRequestTemplateCache[templateId].isEmpty()) {
1548 *request = mRequestTemplateCache[templateId];
1549 return OK;
1550 }
1551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 camera_metadata_t *rawRequest;
1553 status_t res = mInterface->constructDefaultRequestSettings(
1554 (camera3_request_template_t) templateId, &rawRequest);
1555 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001556 ALOGI("%s: template %d is not supported on this camera device",
1557 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001558 return res;
1559 } else if (res != OK) {
1560 CLOGE("Unable to construct request template %d: %s (%d)",
1561 templateId, strerror(-res), res);
1562 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001564
Emilian Peev71c73a22017-03-21 16:35:51 +00001565 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001566 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001567
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001568 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001569 return OK;
1570}
1571
1572status_t Camera3Device::waitUntilDrained() {
1573 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Zhijun He69a37482014-03-23 18:44:49 -07001577 return waitUntilDrainedLocked();
1578}
1579
1580status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 switch (mStatus) {
1582 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 ALOGV("%s: Already idle", __FUNCTION__);
1585 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 case STATUS_CONFIGURED:
1587 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 case STATUS_ERROR:
1589 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 break;
1592 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001593 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 return INVALID_OPERATION;
1595 }
1596
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001597 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001598 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001599 if (res != OK) {
1600 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1601 res);
1602 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 return res;
1604}
1605
Ruben Brunk183f0562015-08-12 12:55:02 -07001606
1607void Camera3Device::internalUpdateStatusLocked(Status status) {
1608 mStatus = status;
1609 mRecentStatusUpdates.add(mStatus);
1610 mStatusChanged.broadcast();
1611}
1612
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613// Pause to reconfigure
1614status_t Camera3Device::internalPauseAndWaitLocked() {
1615 mRequestThread->setPaused(true);
1616 mPauseStateNotify = true;
1617
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001618 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001619 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1620 if (res != OK) {
1621 SET_ERR_L("Can't idle device in %f seconds!",
1622 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 }
1624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 return res;
1626}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628// Resume after internalPauseAndWaitLocked
1629status_t Camera3Device::internalResumeLocked() {
1630 status_t res;
1631
1632 mRequestThread->setPaused(false);
1633
1634 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1635 if (res != OK) {
1636 SET_ERR_L("Can't transition to active in %f seconds!",
1637 kActiveTimeout/1e9);
1638 }
1639 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001640 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641}
1642
Ruben Brunk183f0562015-08-12 12:55:02 -07001643status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001645
1646 size_t startIndex = 0;
1647 if (mStatusWaiters == 0) {
1648 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1649 // this status list
1650 mRecentStatusUpdates.clear();
1651 } else {
1652 // If other threads are waiting on updates to this status list, set the position of the
1653 // first element that this list will check rather than clearing the list.
1654 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001655 }
1656
Ruben Brunk183f0562015-08-12 12:55:02 -07001657 mStatusWaiters++;
1658
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001659 bool stateSeen = false;
1660 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001661 if (active == (mStatus == STATUS_ACTIVE)) {
1662 // Desired state is current
1663 break;
1664 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001665
1666 res = mStatusChanged.waitRelative(mLock, timeout);
1667 if (res != OK) break;
1668
Ruben Brunk183f0562015-08-12 12:55:02 -07001669 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1670 // transitions.
1671 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1672 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1673 __FUNCTION__);
1674
1675 // Encountered desired state since we began waiting
1676 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001677 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1678 stateSeen = true;
1679 break;
1680 }
1681 }
1682 } while (!stateSeen);
1683
Ruben Brunk183f0562015-08-12 12:55:02 -07001684 mStatusWaiters--;
1685
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 return res;
1687}
1688
1689
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001690status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001691 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001692 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001694 if (listener != NULL && mListener != NULL) {
1695 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1696 }
1697 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001698 mRequestThread->setNotificationListener(listener);
1699 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001700
1701 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001702}
1703
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001704bool Camera3Device::willNotify3A() {
1705 return false;
1706}
1707
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001709 status_t res;
1710 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001711
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001712 while (mResultQueue.empty()) {
1713 res = mResultSignal.waitRelative(mOutputLock, timeout);
1714 if (res == TIMED_OUT) {
1715 return res;
1716 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001717 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1718 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001719 return res;
1720 }
1721 }
1722 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723}
1724
Jianing Weicb0652e2014-03-12 18:29:36 -07001725status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001726 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001727 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001729 if (mResultQueue.empty()) {
1730 return NOT_ENOUGH_DATA;
1731 }
1732
Jianing Weicb0652e2014-03-12 18:29:36 -07001733 if (frame == NULL) {
1734 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1735 return BAD_VALUE;
1736 }
1737
1738 CaptureResult &result = *(mResultQueue.begin());
1739 frame->mResultExtras = result.mResultExtras;
1740 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001741 mResultQueue.erase(mResultQueue.begin());
1742
1743 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744}
1745
1746status_t Camera3Device::triggerAutofocus(uint32_t id) {
1747 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001748 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001750 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1751 // Mix-in this trigger into the next request and only the next request.
1752 RequestTrigger trigger[] = {
1753 {
1754 ANDROID_CONTROL_AF_TRIGGER,
1755 ANDROID_CONTROL_AF_TRIGGER_START
1756 },
1757 {
1758 ANDROID_CONTROL_AF_TRIGGER_ID,
1759 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001760 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001761 };
1762
1763 return mRequestThread->queueTrigger(trigger,
1764 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765}
1766
1767status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1768 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001769 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001771 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1772 // Mix-in this trigger into the next request and only the next request.
1773 RequestTrigger trigger[] = {
1774 {
1775 ANDROID_CONTROL_AF_TRIGGER,
1776 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1777 },
1778 {
1779 ANDROID_CONTROL_AF_TRIGGER_ID,
1780 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001781 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001782 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001784 return mRequestThread->queueTrigger(trigger,
1785 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001786}
1787
1788status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1789 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001790 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001791
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001792 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1793 // Mix-in this trigger into the next request and only the next request.
1794 RequestTrigger trigger[] = {
1795 {
1796 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1797 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1798 },
1799 {
1800 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1801 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001802 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001803 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001804
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001805 return mRequestThread->queueTrigger(trigger,
1806 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001807}
1808
Jianing Weicb0652e2014-03-12 18:29:36 -07001809status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001810 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001811 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001813
Zhijun He7ef20392014-04-21 16:04:17 -07001814 {
1815 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001816 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001817 }
1818
Emilian Peev08dd2452017-04-06 16:55:14 +01001819 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001820}
1821
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001822status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001823 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1824}
1825
1826status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001827 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001828 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001829 Mutex::Autolock il(mInterfaceLock);
1830 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001831
1832 sp<Camera3StreamInterface> stream;
1833 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1834 if (outputStreamIdx == NAME_NOT_FOUND) {
1835 CLOGE("Stream %d does not exist", streamId);
1836 return BAD_VALUE;
1837 }
1838
1839 stream = mOutputStreams.editValueAt(outputStreamIdx);
1840
1841 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001842 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001843 return BAD_VALUE;
1844 }
1845
1846 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001847 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001848 return BAD_VALUE;
1849 }
1850
Ruben Brunkc78ac262015-08-13 17:58:46 -07001851 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001852}
1853
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001854status_t Camera3Device::tearDown(int streamId) {
1855 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001856 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001857 Mutex::Autolock il(mInterfaceLock);
1858 Mutex::Autolock l(mLock);
1859
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001860 sp<Camera3StreamInterface> stream;
1861 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1862 if (outputStreamIdx == NAME_NOT_FOUND) {
1863 CLOGE("Stream %d does not exist", streamId);
1864 return BAD_VALUE;
1865 }
1866
1867 stream = mOutputStreams.editValueAt(outputStreamIdx);
1868
1869 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1870 CLOGE("Stream %d is a target of a in-progress request", streamId);
1871 return BAD_VALUE;
1872 }
1873
1874 return stream->tearDown();
1875}
1876
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001877status_t Camera3Device::addBufferListenerForStream(int streamId,
1878 wp<Camera3StreamBufferListener> listener) {
1879 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001880 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001881 Mutex::Autolock il(mInterfaceLock);
1882 Mutex::Autolock l(mLock);
1883
1884 sp<Camera3StreamInterface> stream;
1885 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1886 if (outputStreamIdx == NAME_NOT_FOUND) {
1887 CLOGE("Stream %d does not exist", streamId);
1888 return BAD_VALUE;
1889 }
1890
1891 stream = mOutputStreams.editValueAt(outputStreamIdx);
1892 stream->addBufferListener(listener);
1893
1894 return OK;
1895}
1896
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001897/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898 * Methods called by subclasses
1899 */
1900
1901void Camera3Device::notifyStatus(bool idle) {
1902 {
1903 // Need mLock to safely update state and synchronize to current
1904 // state of methods in flight.
1905 Mutex::Autolock l(mLock);
1906 // We can get various system-idle notices from the status tracker
1907 // while starting up. Only care about them if we've actually sent
1908 // in some requests recently.
1909 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1910 return;
1911 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001912 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001914 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915
1916 // Skip notifying listener if we're doing some user-transparent
1917 // state changes
1918 if (mPauseStateNotify) return;
1919 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001920
1921 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001922 {
1923 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001924 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001925 }
1926 if (idle && listener != NULL) {
1927 listener->notifyIdle();
1928 }
1929}
1930
Shuzhen Wang758c2152017-01-10 18:26:18 -08001931status_t Camera3Device::setConsumerSurfaces(int streamId,
1932 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001933 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001934 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1935 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001936 Mutex::Autolock il(mInterfaceLock);
1937 Mutex::Autolock l(mLock);
1938
Shuzhen Wang758c2152017-01-10 18:26:18 -08001939 if (consumers.size() == 0) {
1940 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001941 return BAD_VALUE;
1942 }
1943
1944 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1945 if (idx == NAME_NOT_FOUND) {
1946 CLOGE("Stream %d is unknown", streamId);
1947 return idx;
1948 }
1949 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001950 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001951 if (res != OK) {
1952 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1953 return res;
1954 }
1955
Shuzhen Wang0129d522016-10-30 22:43:41 -07001956 if (stream->isConsumerConfigurationDeferred()) {
1957 if (!stream->isConfiguring()) {
1958 CLOGE("Stream %d was already fully configured.", streamId);
1959 return INVALID_OPERATION;
1960 }
Zhijun He5d677d12016-05-29 16:52:39 -07001961
Shuzhen Wang0129d522016-10-30 22:43:41 -07001962 res = stream->finishConfiguration();
1963 if (res != OK) {
1964 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1965 stream->getId(), strerror(-res), res);
1966 return res;
1967 }
Zhijun He5d677d12016-05-29 16:52:39 -07001968 }
1969
1970 return OK;
1971}
1972
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001973/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001974 * Camera3Device private methods
1975 */
1976
1977sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001978 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001979 ATRACE_CALL();
1980 status_t res;
1981
1982 sp<CaptureRequest> newRequest = new CaptureRequest;
1983 newRequest->mSettings = request;
1984
1985 camera_metadata_entry_t inputStreams =
1986 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1987 if (inputStreams.count > 0) {
1988 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001989 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001990 CLOGE("Request references unknown input stream %d",
1991 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992 return NULL;
1993 }
1994 // Lazy completion of stream configuration (allocation/registration)
1995 // on first use
1996 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001997 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001999 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002000 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002001 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002002 return NULL;
2003 }
2004 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002005 // Check if stream is being prepared
2006 if (mInputStream->isPreparing()) {
2007 CLOGE("Request references an input stream that's being prepared!");
2008 return NULL;
2009 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002010
2011 newRequest->mInputStream = mInputStream;
2012 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2013 }
2014
2015 camera_metadata_entry_t streams =
2016 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2017 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002018 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019 return NULL;
2020 }
2021
2022 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002023 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002024 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002025 CLOGE("Request references unknown stream %d",
2026 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027 return NULL;
2028 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002029 sp<Camera3OutputStreamInterface> stream =
2030 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002031
Zhijun He5d677d12016-05-29 16:52:39 -07002032 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002033 auto iter = surfaceMap.find(streams.data.i32[i]);
2034 if (iter != surfaceMap.end()) {
2035 const std::vector<size_t>& surfaces = iter->second;
2036 for (const auto& surface : surfaces) {
2037 if (stream->isConsumerConfigurationDeferred(surface)) {
2038 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2039 "due to deferred consumer", stream->getId(), surface);
2040 return NULL;
2041 }
2042 }
2043 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002044 }
2045
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046 // Lazy completion of stream configuration (allocation/registration)
2047 // on first use
2048 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002049 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002050 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002051 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2052 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053 return NULL;
2054 }
2055 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002056 // Check if stream is being prepared
2057 if (stream->isPreparing()) {
2058 CLOGE("Request references an output stream that's being prepared!");
2059 return NULL;
2060 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061
2062 newRequest->mOutputStreams.push(stream);
2063 }
2064 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002065 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066
2067 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002068}
2069
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002070bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2071 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2072 Size size = mSupportedOpaqueInputSizes[i];
2073 if (size.width == width && size.height == height) {
2074 return true;
2075 }
2076 }
2077
2078 return false;
2079}
2080
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002081void Camera3Device::cancelStreamsConfigurationLocked() {
2082 int res = OK;
2083 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2084 res = mInputStream->cancelConfiguration();
2085 if (res != OK) {
2086 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2087 mInputStream->getId(), strerror(-res), res);
2088 }
2089 }
2090
2091 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2092 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2093 if (outputStream->isConfiguring()) {
2094 res = outputStream->cancelConfiguration();
2095 if (res != OK) {
2096 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2097 outputStream->getId(), strerror(-res), res);
2098 }
2099 }
2100 }
2101
2102 // Return state to that at start of call, so that future configures
2103 // properly clean things up
2104 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2105 mNeedConfig = true;
2106}
2107
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002108status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 ATRACE_CALL();
2110 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002111
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002112 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002113 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114 return INVALID_OPERATION;
2115 }
2116
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002117 if (operatingMode < 0) {
2118 CLOGE("Invalid operating mode: %d", operatingMode);
2119 return BAD_VALUE;
2120 }
2121
2122 bool isConstrainedHighSpeed =
2123 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2124 operatingMode;
2125
2126 if (mOperatingMode != operatingMode) {
2127 mNeedConfig = true;
2128 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2129 mOperatingMode = operatingMode;
2130 }
2131
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002132 if (!mNeedConfig) {
2133 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2134 return OK;
2135 }
2136
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002137 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2138 // adding a dummy stream instead.
2139 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2140 if (mOutputStreams.size() == 0) {
2141 addDummyStreamLocked();
2142 } else {
2143 tryRemoveDummyStreamLocked();
2144 }
2145
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002147 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148
2149 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002150 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2152
2153 Vector<camera3_stream_t*> streams;
2154 streams.setCapacity(config.num_streams);
2155
2156 if (mInputStream != NULL) {
2157 camera3_stream_t *inputStream;
2158 inputStream = mInputStream->startConfiguration();
2159 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002160 CLOGE("Can't start input stream configuration");
2161 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162 return INVALID_OPERATION;
2163 }
2164 streams.add(inputStream);
2165 }
2166
2167 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002168
2169 // Don't configure bidi streams twice, nor add them twice to the list
2170 if (mOutputStreams[i].get() ==
2171 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2172
2173 config.num_streams--;
2174 continue;
2175 }
2176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002177 camera3_stream_t *outputStream;
2178 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2179 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002180 CLOGE("Can't start output stream configuration");
2181 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002182 return INVALID_OPERATION;
2183 }
2184 streams.add(outputStream);
2185 }
2186
2187 config.streams = streams.editArray();
2188
2189 // Do the HAL configuration; will potentially touch stream
2190 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002191
2192 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002194 if (res == BAD_VALUE) {
2195 // HAL rejected this set of streams as unsupported, clean up config
2196 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002197 CLOGE("Set of requested inputs/outputs not supported by HAL");
2198 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002199 return BAD_VALUE;
2200 } else if (res != OK) {
2201 // Some other kind of error from configure_streams - this is not
2202 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002203 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2204 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 return res;
2206 }
2207
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002208 // Finish all stream configuration immediately.
2209 // TODO: Try to relax this later back to lazy completion, which should be
2210 // faster
2211
Igor Murashkin073f8572013-05-02 14:59:28 -07002212 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002213 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002214 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002215 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002216 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002217 cancelStreamsConfigurationLocked();
2218 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002219 }
2220 }
2221
2222 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002223 sp<Camera3OutputStreamInterface> outputStream =
2224 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002225 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002226 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002227 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002228 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002229 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002230 cancelStreamsConfigurationLocked();
2231 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002232 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002233 }
2234 }
2235
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002236 // Request thread needs to know to avoid using repeat-last-settings protocol
2237 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002238 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239
Zhijun He90f7c372016-08-16 16:19:43 -07002240 char value[PROPERTY_VALUE_MAX];
2241 property_get("camera.fifo.disable", value, "0");
2242 int32_t disableFifo = atoi(value);
2243 if (disableFifo != 1) {
2244 // Boost priority of request thread to SCHED_FIFO.
2245 pid_t requestThreadTid = mRequestThread->getTid();
2246 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002247 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002248 if (res != OK) {
2249 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2250 strerror(-res), res);
2251 } else {
2252 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2253 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002254 }
2255
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002256 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002257
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002258 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259
Ruben Brunk183f0562015-08-12 12:55:02 -07002260 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2261 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002262
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002263 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002264
Zhijun He0a210512014-07-24 13:45:15 -07002265 // tear down the deleted streams after configure streams.
2266 mDeletedStreams.clear();
2267
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002269}
2270
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002271status_t Camera3Device::addDummyStreamLocked() {
2272 ATRACE_CALL();
2273 status_t res;
2274
2275 if (mDummyStreamId != NO_STREAM) {
2276 // Should never be adding a second dummy stream when one is already
2277 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002278 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2279 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002280 return INVALID_OPERATION;
2281 }
2282
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002283 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002284
2285 sp<Camera3OutputStreamInterface> dummyStream =
2286 new Camera3DummyStream(mNextStreamId);
2287
2288 res = mOutputStreams.add(mNextStreamId, dummyStream);
2289 if (res < 0) {
2290 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2291 return res;
2292 }
2293
2294 mDummyStreamId = mNextStreamId;
2295 mNextStreamId++;
2296
2297 return OK;
2298}
2299
2300status_t Camera3Device::tryRemoveDummyStreamLocked() {
2301 ATRACE_CALL();
2302 status_t res;
2303
2304 if (mDummyStreamId == NO_STREAM) return OK;
2305 if (mOutputStreams.size() == 1) return OK;
2306
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002307 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002308
2309 // Ok, have a dummy stream and there's at least one other output stream,
2310 // so remove the dummy
2311
2312 sp<Camera3StreamInterface> deletedStream;
2313 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2314 if (outputStreamIdx == NAME_NOT_FOUND) {
2315 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2316 return INVALID_OPERATION;
2317 }
2318
2319 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2320 mOutputStreams.removeItemsAt(outputStreamIdx);
2321
2322 // Free up the stream endpoint so that it can be used by some other stream
2323 res = deletedStream->disconnect();
2324 if (res != OK) {
2325 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2326 // fall through since we want to still list the stream as deleted.
2327 }
2328 mDeletedStreams.add(deletedStream);
2329 mDummyStreamId = NO_STREAM;
2330
2331 return res;
2332}
2333
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002334void Camera3Device::setErrorState(const char *fmt, ...) {
2335 Mutex::Autolock l(mLock);
2336 va_list args;
2337 va_start(args, fmt);
2338
2339 setErrorStateLockedV(fmt, args);
2340
2341 va_end(args);
2342}
2343
2344void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2345 Mutex::Autolock l(mLock);
2346 setErrorStateLockedV(fmt, args);
2347}
2348
2349void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2350 va_list args;
2351 va_start(args, fmt);
2352
2353 setErrorStateLockedV(fmt, args);
2354
2355 va_end(args);
2356}
2357
2358void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002359 // Print out all error messages to log
2360 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002361 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002362
2363 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002364 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002365
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002366 mErrorCause = errorCause;
2367
2368 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002369 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002370
2371 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002372 sp<NotificationListener> listener = mListener.promote();
2373 if (listener != NULL) {
2374 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002375 CaptureResultExtras());
2376 }
2377
2378 // Save stack trace. View by dumping it later.
2379 CameraTraces::saveTrace();
2380 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002381}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382
2383/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002384 * In-flight request management
2385 */
2386
Jianing Weicb0652e2014-03-12 18:29:36 -07002387status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002388 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002389 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002390 ATRACE_CALL();
2391 Mutex::Autolock l(mInFlightLock);
2392
2393 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002394 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002395 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002396 if (res < 0) return res;
2397
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002398 if (mInFlightMap.size() == 1) {
2399 mStatusTracker->markComponentActive(mInFlightStatusId);
2400 }
2401
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002402 return OK;
2403}
2404
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002405void Camera3Device::returnOutputBuffers(
2406 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2407 nsecs_t timestamp) {
2408 for (size_t i = 0; i < numBuffers; i++)
2409 {
2410 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2411 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2412 // Note: stream may be deallocated at this point, if this buffer was
2413 // the last reference to it.
2414 if (res != OK) {
2415 ALOGE("Can't return buffer to its stream: %s (%d)",
2416 strerror(-res), res);
2417 }
2418 }
2419}
2420
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002421void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2422 mInFlightMap.removeItemsAt(idx, 1);
2423
2424 // Indicate idle inFlightMap to the status tracker
2425 if (mInFlightMap.size() == 0) {
2426 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2427 }
2428}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002429
2430void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2431
2432 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2433 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2434
2435 nsecs_t sensorTimestamp = request.sensorTimestamp;
2436 nsecs_t shutterTimestamp = request.shutterTimestamp;
2437
2438 // Check if it's okay to remove the request from InFlightMap:
2439 // In the case of a successful request:
2440 // all input and output buffers, all result metadata, shutter callback
2441 // arrived.
2442 // In the case of a unsuccessful request:
2443 // all input and output buffers arrived.
2444 if (request.numBuffersLeft == 0 &&
2445 (request.requestStatus != OK ||
2446 (request.haveResultMetadata && shutterTimestamp != 0))) {
2447 ATRACE_ASYNC_END("frame capture", frameNumber);
2448
Shuzhen Wang403044a2017-02-26 23:29:04 -08002449 // Sanity check - if sensor timestamp matches shutter timestamp in the
2450 // case of request having callback.
2451 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002452 sensorTimestamp != shutterTimestamp) {
2453 SET_ERR("sensor timestamp (%" PRId64
2454 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2455 sensorTimestamp, frameNumber, shutterTimestamp);
2456 }
2457
2458 // for an unsuccessful request, it may have pending output buffers to
2459 // return.
2460 assert(request.requestStatus != OK ||
2461 request.pendingOutputBuffers.size() == 0);
2462 returnOutputBuffers(request.pendingOutputBuffers.array(),
2463 request.pendingOutputBuffers.size(), 0);
2464
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002465 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002466 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2467 }
2468
2469 // Sanity check - if we have too many in-flight frames, something has
2470 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002471 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002472 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002473 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2474 kInFlightWarnLimitHighSpeed) {
2475 CLOGE("In-flight list too large for high speed configuration: %zu",
2476 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002477 }
2478}
2479
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002480void Camera3Device::insertResultLocked(CaptureResult *result,
2481 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002482 if (result == nullptr) return;
2483
Emilian Peev71c73a22017-03-21 16:35:51 +00002484 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2485 result->mMetadata.getAndLock());
2486 set_camera_metadata_vendor_id(meta, mVendorTagId);
2487 result->mMetadata.unlock(meta);
2488
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002489 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2490 (int32_t*)&frameNumber, 1) != OK) {
2491 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2492 return;
2493 }
2494
2495 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2496 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2497 return;
2498 }
2499
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002500 // Valid result, insert into queue
2501 List<CaptureResult>::iterator queuedResult =
2502 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2503 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2504 ", burstId = %" PRId32, __FUNCTION__,
2505 queuedResult->mResultExtras.requestId,
2506 queuedResult->mResultExtras.frameNumber,
2507 queuedResult->mResultExtras.burstId);
2508
2509 mResultSignal.signal();
2510}
2511
2512
2513void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002514 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002515 Mutex::Autolock l(mOutputLock);
2516
2517 CaptureResult captureResult;
2518 captureResult.mResultExtras = resultExtras;
2519 captureResult.mMetadata = partialResult;
2520
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002521 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002522}
2523
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002524
2525void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2526 CaptureResultExtras &resultExtras,
2527 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002528 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002529 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002530 if (pendingMetadata.isEmpty())
2531 return;
2532
2533 Mutex::Autolock l(mOutputLock);
2534
2535 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002536 if (reprocess) {
2537 if (frameNumber < mNextReprocessResultFrameNumber) {
2538 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002539 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002540 frameNumber, mNextReprocessResultFrameNumber);
2541 return;
2542 }
2543 mNextReprocessResultFrameNumber = frameNumber + 1;
2544 } else {
2545 if (frameNumber < mNextResultFrameNumber) {
2546 SET_ERR("Out-of-order capture result metadata submitted! "
2547 "(got frame number %d, expecting %d)",
2548 frameNumber, mNextResultFrameNumber);
2549 return;
2550 }
2551 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002552 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002553
2554 CaptureResult captureResult;
2555 captureResult.mResultExtras = resultExtras;
2556 captureResult.mMetadata = pendingMetadata;
2557
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002558 // Append any previous partials to form a complete result
2559 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2560 captureResult.mMetadata.append(collectedPartialResult);
2561 }
2562
2563 captureResult.mMetadata.sort();
2564
2565 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002566 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2567 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002568 SET_ERR("No timestamp provided by HAL for frame %d!",
2569 frameNumber);
2570 return;
2571 }
2572
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002573 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2574 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2575
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002576 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002577}
2578
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002579/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002580 * Camera HAL device callback methods
2581 */
2582
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002583void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002584 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002585
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002586 status_t res;
2587
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002588 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002589 if (result->result == NULL && result->num_output_buffers == 0 &&
2590 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002591 SET_ERR("No result data provided by HAL for frame %d",
2592 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002593 return;
2594 }
Zhijun He204e3292014-07-14 17:09:23 -07002595
Zhijun He204e3292014-07-14 17:09:23 -07002596 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002597 result->result != NULL &&
2598 result->partial_result != 1) {
2599 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2600 " if partial result is not supported",
2601 frameNumber, result->partial_result);
2602 return;
2603 }
2604
2605 bool isPartialResult = false;
2606 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002607 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002608 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002609
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002610 // Get shutter timestamp and resultExtras from list of in-flight requests,
2611 // where it was added by the shutter notification for this frame. If the
2612 // shutter timestamp isn't received yet, append the output buffers to the
2613 // in-flight request and they will be returned when the shutter timestamp
2614 // arrives. Update the in-flight status and remove the in-flight entry if
2615 // all result data and shutter timestamp have been received.
2616 nsecs_t shutterTimestamp = 0;
2617
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002618 {
2619 Mutex::Autolock l(mInFlightLock);
2620 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2621 if (idx == NAME_NOT_FOUND) {
2622 SET_ERR("Unknown frame number for capture result: %d",
2623 frameNumber);
2624 return;
2625 }
2626 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002627 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2628 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002629 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002630 __FUNCTION__, request.resultExtras.requestId,
2631 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002632 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002633 // Always update the partial count to the latest one if it's not 0
2634 // (buffers only). When framework aggregates adjacent partial results
2635 // into one, the latest partial count will be used.
2636 if (result->partial_result != 0)
2637 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002638
2639 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002640 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002641 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2642 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2643 " the range of [1, %d] when metadata is included in the result",
2644 frameNumber, result->partial_result, mNumPartialResults);
2645 return;
2646 }
2647 isPartialResult = (result->partial_result < mNumPartialResults);
2648 if (isPartialResult) {
2649 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002650 }
2651
Shuzhen Wang4a472662017-02-26 23:29:04 -08002652 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002653 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002654 sendPartialCaptureResult(result->result, request.resultExtras,
2655 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002656 }
2657 }
2658
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002659 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002660 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002661
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002662 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002663 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002664 if (request.haveResultMetadata) {
2665 SET_ERR("Called multiple times with metadata for frame %d",
2666 frameNumber);
2667 return;
2668 }
Zhijun He204e3292014-07-14 17:09:23 -07002669 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002670 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002671 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002672 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002673 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002674 request.haveResultMetadata = true;
2675 }
2676
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002677 uint32_t numBuffersReturned = result->num_output_buffers;
2678 if (result->input_buffer != NULL) {
2679 if (hasInputBufferInRequest) {
2680 numBuffersReturned += 1;
2681 } else {
2682 ALOGW("%s: Input buffer should be NULL if there is no input"
2683 " buffer sent in the request",
2684 __FUNCTION__);
2685 }
2686 }
2687 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002688 if (request.numBuffersLeft < 0) {
2689 SET_ERR("Too many buffers returned for frame %d",
2690 frameNumber);
2691 return;
2692 }
2693
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002694 camera_metadata_ro_entry_t entry;
2695 res = find_camera_metadata_ro_entry(result->result,
2696 ANDROID_SENSOR_TIMESTAMP, &entry);
2697 if (res == OK && entry.count == 1) {
2698 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002699 }
2700
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002701 // If shutter event isn't received yet, append the output buffers to
2702 // the in-flight request. Otherwise, return the output buffers to
2703 // streams.
2704 if (shutterTimestamp == 0) {
2705 request.pendingOutputBuffers.appendArray(result->output_buffers,
2706 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002707 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002708 returnOutputBuffers(result->output_buffers,
2709 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002710 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002711
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002712 if (result->result != NULL && !isPartialResult) {
2713 if (shutterTimestamp == 0) {
2714 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002715 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002716 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002717 CameraMetadata metadata;
2718 metadata = result->result;
2719 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002720 collectedPartialResult, frameNumber,
2721 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002722 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002723 }
2724
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002725 removeInFlightRequestIfReadyLocked(idx);
2726 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002727
Zhijun Hef0d962a2014-06-30 10:24:11 -07002728 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002729 if (hasInputBufferInRequest) {
2730 Camera3Stream *stream =
2731 Camera3Stream::cast(result->input_buffer->stream);
2732 res = stream->returnInputBuffer(*(result->input_buffer));
2733 // Note: stream may be deallocated at this point, if this buffer was the
2734 // last reference to it.
2735 if (res != OK) {
2736 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2737 " its stream:%s (%d)", __FUNCTION__,
2738 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002739 }
2740 } else {
2741 ALOGW("%s: Input buffer should be NULL if there is no input"
2742 " buffer sent in the request, skipping input buffer return.",
2743 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002744 }
2745 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002746}
2747
2748void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002749 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002750 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002751 {
2752 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002753 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002754 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002755
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002756 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002757 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002758 return;
2759 }
2760
2761 switch (msg->type) {
2762 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002763 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002764 break;
2765 }
2766 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002767 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002768 break;
2769 }
2770 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002771 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002772 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002773 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002774}
2775
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002776void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002777 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002778
2779 // Map camera HAL error codes to ICameraDeviceCallback error codes
2780 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002781 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002782 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002783 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002784 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002785 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002786 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002787 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002788 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002789 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002790 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002791 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002792 };
2793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002794 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002795 ((msg.error_code >= 0) &&
2796 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2797 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002798 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002799
2800 int streamId = 0;
2801 if (msg.error_stream != NULL) {
2802 Camera3Stream *stream =
2803 Camera3Stream::cast(msg.error_stream);
2804 streamId = stream->getId();
2805 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002806 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2807 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002808 streamId, msg.error_code);
2809
2810 CaptureResultExtras resultExtras;
2811 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002812 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002813 // SET_ERR calls notifyError
2814 SET_ERR("Camera HAL reported serious device error");
2815 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002816 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2817 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2818 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002819 {
2820 Mutex::Autolock l(mInFlightLock);
2821 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2822 if (idx >= 0) {
2823 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2824 r.requestStatus = msg.error_code;
2825 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002826 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2827 errorCode) {
2828 // In case of missing result check whether the buffers
2829 // returned. If they returned, then remove inflight
2830 // request.
2831 removeInFlightRequestIfReadyLocked(idx);
2832 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002833 } else {
2834 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002835 ALOGE("Camera %s: %s: cannot find in-flight request on "
2836 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002837 resultExtras.frameNumber);
2838 }
2839 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002840 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002841 if (listener != NULL) {
2842 listener->notifyError(errorCode, resultExtras);
2843 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002844 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002845 }
2846 break;
2847 default:
2848 // SET_ERR calls notifyError
2849 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2850 break;
2851 }
2852}
2853
2854void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002855 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002856 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858 // Set timestamp for the request in the in-flight tracking
2859 // and get the request ID to send upstream
2860 {
2861 Mutex::Autolock l(mInFlightLock);
2862 idx = mInFlightMap.indexOfKey(msg.frame_number);
2863 if (idx >= 0) {
2864 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002865
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002866 // Verify ordering of shutter notifications
2867 {
2868 Mutex::Autolock l(mOutputLock);
2869 // TODO: need to track errors for tighter bounds on expected frame number.
2870 if (r.hasInputBuffer) {
2871 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2872 SET_ERR("Shutter notification out-of-order. Expected "
2873 "notification for frame %d, got frame %d",
2874 mNextReprocessShutterFrameNumber, msg.frame_number);
2875 return;
2876 }
2877 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2878 } else {
2879 if (msg.frame_number < mNextShutterFrameNumber) {
2880 SET_ERR("Shutter notification out-of-order. Expected "
2881 "notification for frame %d, got frame %d",
2882 mNextShutterFrameNumber, msg.frame_number);
2883 return;
2884 }
2885 mNextShutterFrameNumber = msg.frame_number + 1;
2886 }
2887 }
2888
Shuzhen Wang4a472662017-02-26 23:29:04 -08002889 r.shutterTimestamp = msg.timestamp;
2890 if (r.hasCallback) {
2891 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002892 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002893 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002894 // Call listener, if any
2895 if (listener != NULL) {
2896 listener->notifyShutter(r.resultExtras, msg.timestamp);
2897 }
2898 // send pending result and buffers
2899 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2900 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002901 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002902 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002903 returnOutputBuffers(r.pendingOutputBuffers.array(),
2904 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2905 r.pendingOutputBuffers.clear();
2906
2907 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002908 }
2909 }
2910 if (idx < 0) {
2911 SET_ERR("Shutter notification for non-existent frame number %d",
2912 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002913 }
2914}
2915
2916
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002917CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002918 ALOGV("%s", __FUNCTION__);
2919
Igor Murashkin1e479c02013-09-06 16:55:14 -07002920 CameraMetadata retVal;
2921
2922 if (mRequestThread != NULL) {
2923 retVal = mRequestThread->getLatestRequest();
2924 }
2925
Igor Murashkin1e479c02013-09-06 16:55:14 -07002926 return retVal;
2927}
2928
Jianing Weicb0652e2014-03-12 18:29:36 -07002929
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002930void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2931 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2932 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2933}
2934
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002935/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002936 * HalInterface inner class methods
2937 */
2938
2939Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
2940 mHal3Device(device) {}
2941
Yifan Hongf79b5542017-04-11 14:44:25 -07002942Camera3Device::HalInterface::HalInterface(
2943 sp<ICameraDeviceSession> &session,
2944 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002945 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002946 mHidlSession(session),
2947 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948
2949Camera3Device::HalInterface::HalInterface() :
2950 mHal3Device(nullptr) {}
2951
2952Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002953 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002954 mHidlSession(other.mHidlSession),
2955 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002956
2957bool Camera3Device::HalInterface::valid() {
2958 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2959}
2960
2961void Camera3Device::HalInterface::clear() {
2962 mHal3Device = nullptr;
2963 mHidlSession.clear();
2964}
2965
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002966bool Camera3Device::HalInterface::supportBatchRequest() {
2967 return mHidlSession != nullptr;
2968}
2969
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002970status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2971 camera3_request_template_t templateId,
2972 /*out*/ camera_metadata_t **requestTemplate) {
2973 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2974 if (!valid()) return INVALID_OPERATION;
2975 status_t res = OK;
2976
2977 if (mHal3Device != nullptr) {
2978 const camera_metadata *r;
2979 r = mHal3Device->ops->construct_default_request_settings(
2980 mHal3Device, templateId);
2981 if (r == nullptr) return BAD_VALUE;
2982 *requestTemplate = clone_camera_metadata(r);
2983 if (requestTemplate == nullptr) {
2984 ALOGE("%s: Unable to clone camera metadata received from HAL",
2985 __FUNCTION__);
2986 return INVALID_OPERATION;
2987 }
2988 } else {
2989 common::V1_0::Status status;
2990 RequestTemplate id;
2991 switch (templateId) {
2992 case CAMERA3_TEMPLATE_PREVIEW:
2993 id = RequestTemplate::PREVIEW;
2994 break;
2995 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2996 id = RequestTemplate::STILL_CAPTURE;
2997 break;
2998 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2999 id = RequestTemplate::VIDEO_RECORD;
3000 break;
3001 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3002 id = RequestTemplate::VIDEO_SNAPSHOT;
3003 break;
3004 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3005 id = RequestTemplate::ZERO_SHUTTER_LAG;
3006 break;
3007 case CAMERA3_TEMPLATE_MANUAL:
3008 id = RequestTemplate::MANUAL;
3009 break;
3010 default:
3011 // Unknown template ID
3012 return BAD_VALUE;
3013 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003014 auto err = mHidlSession->constructDefaultRequestSettings(id,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003015 [&status, &requestTemplate]
3016 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3017 status = s;
3018 if (status == common::V1_0::Status::OK) {
3019 const camera_metadata *r =
3020 reinterpret_cast<const camera_metadata_t*>(request.data());
3021 size_t expectedSize = request.size();
3022 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003023 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003024 *requestTemplate = clone_camera_metadata(r);
3025 if (*requestTemplate == nullptr) {
3026 ALOGE("%s: Unable to clone camera metadata received from HAL",
3027 __FUNCTION__);
3028 status = common::V1_0::Status::INTERNAL_ERROR;
3029 }
3030 } else {
3031 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3032 status = common::V1_0::Status::INTERNAL_ERROR;
3033 }
3034 }
3035 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003036 if (!err.isOk()) {
3037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3038 res = DEAD_OBJECT;
3039 } else {
3040 res = CameraProviderManager::mapToStatusT(status);
3041 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003042 }
3043 return res;
3044}
3045
3046status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3047 ATRACE_NAME("CameraHal::configureStreams");
3048 if (!valid()) return INVALID_OPERATION;
3049 status_t res = OK;
3050
3051 if (mHal3Device != nullptr) {
3052 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3053 } else {
3054 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003055 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003056 StreamConfiguration requestedConfiguration;
3057 requestedConfiguration.streams.resize(config->num_streams);
3058 for (size_t i = 0; i < config->num_streams; i++) {
3059 Stream &dst = requestedConfiguration.streams[i];
3060 camera3_stream_t *src = config->streams[i];
3061
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003062 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3063 cam3stream->setBufferFreedListener(this);
3064 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003065 StreamType streamType;
3066 switch (src->stream_type) {
3067 case CAMERA3_STREAM_OUTPUT:
3068 streamType = StreamType::OUTPUT;
3069 break;
3070 case CAMERA3_STREAM_INPUT:
3071 streamType = StreamType::INPUT;
3072 break;
3073 default:
3074 ALOGE("%s: Stream %d: Unsupported stream type %d",
3075 __FUNCTION__, streamId, config->streams[i]->stream_type);
3076 return BAD_VALUE;
3077 }
3078 dst.id = streamId;
3079 dst.streamType = streamType;
3080 dst.width = src->width;
3081 dst.height = src->height;
3082 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003083 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003084 dst.dataSpace = mapToHidlDataspace(src->data_space);
3085 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003086
3087 activeStreams.insert(streamId);
3088 // Create Buffer ID map if necessary
3089 if (mBufferIdMaps.count(streamId) == 0) {
3090 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3091 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003093 // remove BufferIdMap for deleted streams
3094 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3095 int streamId = it->first;
3096 bool active = activeStreams.count(streamId) > 0;
3097 if (!active) {
3098 it = mBufferIdMaps.erase(it);
3099 } else {
3100 ++it;
3101 }
3102 }
3103
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003104 res = mapToStreamConfigurationMode(
3105 (camera3_stream_configuration_mode_t) config->operation_mode,
3106 /*out*/ &requestedConfiguration.operationMode);
3107 if (res != OK) {
3108 return res;
3109 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003110
3111 // Invoke configureStreams
3112
3113 HalStreamConfiguration finalConfiguration;
3114 common::V1_0::Status status;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003115 auto err = mHidlSession->configureStreams(requestedConfiguration,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116 [&status, &finalConfiguration]
3117 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3118 finalConfiguration = halConfiguration;
3119 status = s;
3120 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003121 if (!err.isOk()) {
3122 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3123 return DEAD_OBJECT;
3124 }
3125
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003126 if (status != common::V1_0::Status::OK ) {
3127 return CameraProviderManager::mapToStatusT(status);
3128 }
3129
3130 // And convert output stream configuration from HIDL
3131
3132 for (size_t i = 0; i < config->num_streams; i++) {
3133 camera3_stream_t *dst = config->streams[i];
3134 int streamId = Camera3Stream::cast(dst)->getId();
3135
3136 // Start scan at i, with the assumption that the stream order matches
3137 size_t realIdx = i;
3138 bool found = false;
3139 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3140 if (finalConfiguration.streams[realIdx].id == streamId) {
3141 found = true;
3142 break;
3143 }
3144 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3145 }
3146 if (!found) {
3147 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3148 __FUNCTION__, streamId);
3149 return INVALID_OPERATION;
3150 }
3151 HalStream &src = finalConfiguration.streams[realIdx];
3152
3153 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3154 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3155 if (dst->format != overrideFormat) {
3156 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3157 streamId, dst->format);
3158 }
3159 } else {
3160 // Override allowed with IMPLEMENTATION_DEFINED
3161 dst->format = overrideFormat;
3162 }
3163
3164 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3165 if (src.producerUsage != 0) {
3166 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3167 __FUNCTION__, streamId);
3168 return INVALID_OPERATION;
3169 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003170 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003171 } else {
3172 // OUTPUT
3173 if (src.consumerUsage != 0) {
3174 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3175 __FUNCTION__, streamId);
3176 return INVALID_OPERATION;
3177 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003178 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003179 }
3180 dst->max_buffers = src.maxBuffers;
3181 }
3182 }
3183 return res;
3184}
3185
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003186void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3187 /*out*/device::V3_2::CaptureRequest* captureRequest,
3188 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3189
3190 if (captureRequest == nullptr || handlesCreated == nullptr) {
3191 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3192 __FUNCTION__, captureRequest, handlesCreated);
3193 return;
3194 }
3195
3196 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003197
3198 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003199
3200 {
3201 std::lock_guard<std::mutex> lock(mInflightLock);
3202 if (request->input_buffer != nullptr) {
3203 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3204 buffer_handle_t buf = *(request->input_buffer->buffer);
3205 auto pair = getBufferId(buf, streamId);
3206 bool isNewBuffer = pair.first;
3207 uint64_t bufferId = pair.second;
3208 captureRequest->inputBuffer.streamId = streamId;
3209 captureRequest->inputBuffer.bufferId = bufferId;
3210 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3211 captureRequest->inputBuffer.status = BufferStatus::OK;
3212 native_handle_t *acquireFence = nullptr;
3213 if (request->input_buffer->acquire_fence != -1) {
3214 acquireFence = native_handle_create(1,0);
3215 acquireFence->data[0] = request->input_buffer->acquire_fence;
3216 handlesCreated->push_back(acquireFence);
3217 }
3218 captureRequest->inputBuffer.acquireFence = acquireFence;
3219 captureRequest->inputBuffer.releaseFence = nullptr;
3220
3221 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3222 request->input_buffer->buffer,
3223 request->input_buffer->acquire_fence);
3224 } else {
3225 captureRequest->inputBuffer.streamId = -1;
3226 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3227 }
3228
3229 captureRequest->outputBuffers.resize(request->num_output_buffers);
3230 for (size_t i = 0; i < request->num_output_buffers; i++) {
3231 const camera3_stream_buffer_t *src = request->output_buffers + i;
3232 StreamBuffer &dst = captureRequest->outputBuffers[i];
3233 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3234 buffer_handle_t buf = *(src->buffer);
3235 auto pair = getBufferId(buf, streamId);
3236 bool isNewBuffer = pair.first;
3237 dst.streamId = streamId;
3238 dst.bufferId = pair.second;
3239 dst.buffer = isNewBuffer ? buf : nullptr;
3240 dst.status = BufferStatus::OK;
3241 native_handle_t *acquireFence = nullptr;
3242 if (src->acquire_fence != -1) {
3243 acquireFence = native_handle_create(1,0);
3244 acquireFence->data[0] = src->acquire_fence;
3245 handlesCreated->push_back(acquireFence);
3246 }
3247 dst.acquireFence = acquireFence;
3248 dst.releaseFence = nullptr;
3249
3250 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3251 src->buffer, src->acquire_fence);
3252 }
3253 }
3254}
3255
3256status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3257 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3258 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3259 if (!valid()) return INVALID_OPERATION;
3260
3261 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3262 size_t batchSize = requests.size();
3263 captureRequests.resize(batchSize);
3264 std::vector<native_handle_t*> handlesCreated;
3265
3266 for (size_t i = 0; i < batchSize; i++) {
3267 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3268 }
3269
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003270 std::vector<device::V3_2::BufferCache> cachesToRemove;
3271 {
3272 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3273 for (auto& pair : mFreedBuffers) {
3274 // The stream might have been removed since onBufferFreed
3275 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3276 cachesToRemove.push_back({pair.first, pair.second});
3277 }
3278 }
3279 mFreedBuffers.clear();
3280 }
3281
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003282 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3283 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003284
3285 // Write metadata to FMQ.
3286 for (size_t i = 0; i < batchSize; i++) {
3287 camera3_capture_request_t* request = requests[i];
3288 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3289
3290 if (request->settings != nullptr) {
3291 size_t settingsSize = get_camera_metadata_size(request->settings);
3292 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3293 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3294 captureRequest->settings.resize(0);
3295 captureRequest->fmqSettingsSize = settingsSize;
3296 } else {
3297 if (mRequestMetadataQueue != nullptr) {
3298 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3299 }
3300 captureRequest->settings.setToExternal(
3301 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3302 get_camera_metadata_size(request->settings));
3303 captureRequest->fmqSettingsSize = 0u;
3304 }
3305 } else {
3306 // A null request settings maps to a size-0 CameraMetadata
3307 captureRequest->settings.resize(0);
3308 captureRequest->fmqSettingsSize = 0u;
3309 }
3310 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003311 auto err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003312 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3313 status = s;
3314 *numRequestProcessed = n;
3315 });
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003316 if (!err.isOk()) {
3317 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3318 return DEAD_OBJECT;
3319 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003320 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3321 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3322 __FUNCTION__, *numRequestProcessed, batchSize);
3323 status = common::V1_0::Status::INTERNAL_ERROR;
3324 }
3325
3326 for (auto& handle : handlesCreated) {
3327 native_handle_delete(handle);
3328 }
3329 return CameraProviderManager::mapToStatusT(status);
3330}
3331
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003332status_t Camera3Device::HalInterface::processCaptureRequest(
3333 camera3_capture_request_t *request) {
3334 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003335 if (!valid()) return INVALID_OPERATION;
3336 status_t res = OK;
3337
3338 if (mHal3Device != nullptr) {
3339 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3340 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003341 uint32_t numRequestProcessed = 0;
3342 std::vector<camera3_capture_request_t*> requests(1);
3343 requests[0] = request;
3344 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003345 }
3346 return res;
3347}
3348
3349status_t Camera3Device::HalInterface::flush() {
3350 ATRACE_NAME("CameraHal::flush");
3351 if (!valid()) return INVALID_OPERATION;
3352 status_t res = OK;
3353
3354 if (mHal3Device != nullptr) {
3355 res = mHal3Device->ops->flush(mHal3Device);
3356 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003357 auto err = mHidlSession->flush();
3358 if (!err.isOk()) {
3359 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3360 res = DEAD_OBJECT;
3361 } else {
3362 res = CameraProviderManager::mapToStatusT(err);
3363 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003364 }
3365 return res;
3366}
3367
3368status_t Camera3Device::HalInterface::dump(int fd) {
3369 ATRACE_NAME("CameraHal::dump");
3370 if (!valid()) return INVALID_OPERATION;
3371 status_t res = OK;
3372
3373 if (mHal3Device != nullptr) {
3374 mHal3Device->ops->dump(mHal3Device, fd);
3375 } else {
3376 // Handled by CameraProviderManager::dump
3377 }
3378 return res;
3379}
3380
3381status_t Camera3Device::HalInterface::close() {
3382 ATRACE_NAME("CameraHal::close()");
3383 if (!valid()) return INVALID_OPERATION;
3384 status_t res = OK;
3385
3386 if (mHal3Device != nullptr) {
3387 mHal3Device->common.close(&mHal3Device->common);
3388 } else {
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003389 auto err = mHidlSession->close();
3390 // Interface will be dead shortly anyway, so don't log errors
3391 if (!err.isOk()) {
3392 res = DEAD_OBJECT;
3393 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003394 }
3395 return res;
3396}
3397
3398status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003399 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003400 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003401 auto pair = std::make_pair(buffer, acquireFence);
3402 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003403 return OK;
3404}
3405
3406status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003407 int32_t frameNumber, int32_t streamId,
3408 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003409 std::lock_guard<std::mutex> lock(mInflightLock);
3410
3411 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3412 auto it = mInflightBufferMap.find(key);
3413 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003414 auto pair = it->second;
3415 *buffer = pair.first;
3416 int acquireFence = pair.second;
3417 if (acquireFence > 0) {
3418 ::close(acquireFence);
3419 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003420 mInflightBufferMap.erase(it);
3421 return OK;
3422}
3423
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003424std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3425 const buffer_handle_t& buf, int streamId) {
3426 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3427
3428 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3429 auto it = bIdMap.find(buf);
3430 if (it == bIdMap.end()) {
3431 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003432 ALOGV("stream %d now have %zu buffer caches, buf %p",
3433 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003434 return std::make_pair(true, mNextBufferId - 1);
3435 } else {
3436 return std::make_pair(false, it->second);
3437 }
3438}
3439
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003440void Camera3Device::HalInterface::onBufferFreed(
3441 int streamId, const native_handle_t* handle) {
3442 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3443 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3444 auto mapIt = mBufferIdMaps.find(streamId);
3445 if (mapIt == mBufferIdMaps.end()) {
3446 // streamId might be from a deleted stream here
3447 ALOGI("%s: stream %d has been removed",
3448 __FUNCTION__, streamId);
3449 return;
3450 }
3451 BufferIdMap& bIdMap = mapIt->second;
3452 auto it = bIdMap.find(handle);
3453 if (it == bIdMap.end()) {
3454 ALOGW("%s: cannot find buffer %p in stream %d",
3455 __FUNCTION__, handle, streamId);
3456 return;
3457 } else {
3458 bufferId = it->second;
3459 bIdMap.erase(it);
3460 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3461 __FUNCTION__, streamId, bIdMap.size(), handle);
3462 }
3463 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3464}
3465
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003466/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003467 * RequestThread inner class methods
3468 */
3469
3470Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003471 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003472 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003473 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003474 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003475 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003476 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003477 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003478 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003479 mReconfigured(false),
3480 mDoPause(false),
3481 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003482 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003483 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003484 mCurrentAfTriggerId(0),
3485 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003486 mRepeatingLastFrameNumber(
3487 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003488 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003489 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003490}
3491
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492Camera3Device::RequestThread::~RequestThread() {}
3493
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003494void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003495 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003496 Mutex::Autolock l(mRequestLock);
3497 mListener = listener;
3498}
3499
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003500void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003501 Mutex::Autolock l(mRequestLock);
3502 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003503 // Prepare video stream for high speed recording.
3504 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003505}
3506
Jianing Wei90e59c92014-03-12 18:29:36 -07003507status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003508 List<sp<CaptureRequest> > &requests,
3509 /*out*/
3510 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003511 Mutex::Autolock l(mRequestLock);
3512 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3513 ++it) {
3514 mRequestQueue.push_back(*it);
3515 }
3516
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003517 if (lastFrameNumber != NULL) {
3518 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3519 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3520 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3521 *lastFrameNumber);
3522 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003523
Jianing Wei90e59c92014-03-12 18:29:36 -07003524 unpauseForNewRequests();
3525
3526 return OK;
3527}
3528
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003529
3530status_t Camera3Device::RequestThread::queueTrigger(
3531 RequestTrigger trigger[],
3532 size_t count) {
3533
3534 Mutex::Autolock l(mTriggerMutex);
3535 status_t ret;
3536
3537 for (size_t i = 0; i < count; ++i) {
3538 ret = queueTriggerLocked(trigger[i]);
3539
3540 if (ret != OK) {
3541 return ret;
3542 }
3543 }
3544
3545 return OK;
3546}
3547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003548const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3549 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003550 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003551 if (d != nullptr) return d->mId;
3552 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003553}
3554
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003555status_t Camera3Device::RequestThread::queueTriggerLocked(
3556 RequestTrigger trigger) {
3557
3558 uint32_t tag = trigger.metadataTag;
3559 ssize_t index = mTriggerMap.indexOfKey(tag);
3560
3561 switch (trigger.getTagType()) {
3562 case TYPE_BYTE:
3563 // fall-through
3564 case TYPE_INT32:
3565 break;
3566 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003567 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3568 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003569 return INVALID_OPERATION;
3570 }
3571
3572 /**
3573 * Collect only the latest trigger, since we only have 1 field
3574 * in the request settings per trigger tag, and can't send more than 1
3575 * trigger per request.
3576 */
3577 if (index != NAME_NOT_FOUND) {
3578 mTriggerMap.editValueAt(index) = trigger;
3579 } else {
3580 mTriggerMap.add(tag, trigger);
3581 }
3582
3583 return OK;
3584}
3585
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003586status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003587 const RequestList &requests,
3588 /*out*/
3589 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003590 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003591 if (lastFrameNumber != NULL) {
3592 *lastFrameNumber = mRepeatingLastFrameNumber;
3593 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003594 mRepeatingRequests.clear();
3595 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3596 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003597
3598 unpauseForNewRequests();
3599
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003600 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003601 return OK;
3602}
3603
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003604bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003605 if (mRepeatingRequests.empty()) {
3606 return false;
3607 }
3608 int32_t requestId = requestIn->mResultExtras.requestId;
3609 const RequestList &repeatRequests = mRepeatingRequests;
3610 // All repeating requests are guaranteed to have same id so only check first quest
3611 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3612 return (firstRequest->mResultExtras.requestId == requestId);
3613}
3614
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003615status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003616 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003617 return clearRepeatingRequestsLocked(lastFrameNumber);
3618
3619}
3620
3621status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003622 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003623 if (lastFrameNumber != NULL) {
3624 *lastFrameNumber = mRepeatingLastFrameNumber;
3625 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003626 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003627 return OK;
3628}
3629
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003630status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003631 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003632 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003633 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003634
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003635 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003636
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 // Send errors for all requests pending in the request queue, including
3638 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003639 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003640 if (listener != NULL) {
3641 for (RequestList::iterator it = mRequestQueue.begin();
3642 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003643 // Abort the input buffers for reprocess requests.
3644 if ((*it)->mInputStream != NULL) {
3645 camera3_stream_buffer_t inputBuffer;
3646 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3647 if (res != OK) {
3648 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3649 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3650 } else {
3651 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3652 if (res != OK) {
3653 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3654 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3655 }
3656 }
3657 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003658 // Set the frame number this request would have had, if it
3659 // had been submitted; this frame number will not be reused.
3660 // The requestId and burstId fields were set when the request was
3661 // submitted originally (in convertMetadataListToRequestListLocked)
3662 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003663 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003664 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003665 }
3666 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003667 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003668
3669 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003670 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003671 if (lastFrameNumber != NULL) {
3672 *lastFrameNumber = mRepeatingLastFrameNumber;
3673 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003674 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003675 return OK;
3676}
3677
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003678status_t Camera3Device::RequestThread::flush() {
3679 ATRACE_CALL();
3680 Mutex::Autolock l(mFlushLock);
3681
Emilian Peev08dd2452017-04-06 16:55:14 +01003682 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003683}
3684
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003685void Camera3Device::RequestThread::setPaused(bool paused) {
3686 Mutex::Autolock l(mPauseLock);
3687 mDoPause = paused;
3688 mDoPauseSignal.signal();
3689}
3690
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003691status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3692 int32_t requestId, nsecs_t timeout) {
3693 Mutex::Autolock l(mLatestRequestMutex);
3694 status_t res;
3695 while (mLatestRequestId != requestId) {
3696 nsecs_t startTime = systemTime();
3697
3698 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3699 if (res != OK) return res;
3700
3701 timeout -= (systemTime() - startTime);
3702 }
3703
3704 return OK;
3705}
3706
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003707void Camera3Device::RequestThread::requestExit() {
3708 // Call parent to set up shutdown
3709 Thread::requestExit();
3710 // The exit from any possible waits
3711 mDoPauseSignal.signal();
3712 mRequestSignal.signal();
3713}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003714
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003715void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003716 bool surfaceAbandoned = false;
3717 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003718 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003719 {
3720 Mutex::Autolock l(mRequestLock);
3721 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3722 // repeating requests.
3723 for (const auto& request : mRepeatingRequests) {
3724 for (const auto& s : request->mOutputStreams) {
3725 if (s->isAbandoned()) {
3726 surfaceAbandoned = true;
3727 clearRepeatingRequestsLocked(&lastFrameNumber);
3728 break;
3729 }
3730 }
3731 if (surfaceAbandoned) {
3732 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003733 }
3734 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003735 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003736 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003737
3738 if (listener != NULL && surfaceAbandoned) {
3739 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003740 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003741}
3742
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003743bool Camera3Device::RequestThread::sendRequestsBatch() {
3744 status_t res;
3745 size_t batchSize = mNextRequests.size();
3746 std::vector<camera3_capture_request_t*> requests(batchSize);
3747 uint32_t numRequestProcessed = 0;
3748 for (size_t i = 0; i < batchSize; i++) {
3749 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3750 }
3751
3752 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3753 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3754
3755 bool triggerRemoveFailed = false;
3756 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3757 for (size_t i = 0; i < numRequestProcessed; i++) {
3758 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3759 nextRequest.submitted = true;
3760
3761
3762 // Update the latest request sent to HAL
3763 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3764 Mutex::Autolock al(mLatestRequestMutex);
3765
3766 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3767 mLatestRequest.acquire(cloned);
3768
3769 sp<Camera3Device> parent = mParent.promote();
3770 if (parent != NULL) {
3771 parent->monitorMetadata(TagMonitor::REQUEST,
3772 nextRequest.halRequest.frame_number,
3773 0, mLatestRequest);
3774 }
3775 }
3776
3777 if (nextRequest.halRequest.settings != NULL) {
3778 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3779 }
3780
3781 if (!triggerRemoveFailed) {
3782 // Remove any previously queued triggers (after unlock)
3783 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3784 if (removeTriggerRes != OK) {
3785 triggerRemoveFailed = true;
3786 triggerFailedRequest = nextRequest;
3787 }
3788 }
3789 }
3790
3791 if (triggerRemoveFailed) {
3792 SET_ERR("RequestThread: Unable to remove triggers "
3793 "(capture request %d, HAL device: %s (%d)",
3794 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3795 cleanUpFailedRequests(/*sendRequestError*/ false);
3796 return false;
3797 }
3798
3799 if (res != OK) {
3800 // Should only get a failure here for malformed requests or device-level
3801 // errors, so consider all errors fatal. Bad metadata failures should
3802 // come through notify.
3803 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3804 mNextRequests[numRequestProcessed].halRequest.frame_number,
3805 strerror(-res), res);
3806 cleanUpFailedRequests(/*sendRequestError*/ false);
3807 return false;
3808 }
3809 return true;
3810}
3811
3812bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3813 status_t res;
3814
3815 for (auto& nextRequest : mNextRequests) {
3816 // Submit request and block until ready for next one
3817 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3818 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3819
3820 if (res != OK) {
3821 // Should only get a failure here for malformed requests or device-level
3822 // errors, so consider all errors fatal. Bad metadata failures should
3823 // come through notify.
3824 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3825 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3826 res);
3827 cleanUpFailedRequests(/*sendRequestError*/ false);
3828 return false;
3829 }
3830
3831 // Mark that the request has be submitted successfully.
3832 nextRequest.submitted = true;
3833
3834 // Update the latest request sent to HAL
3835 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3836 Mutex::Autolock al(mLatestRequestMutex);
3837
3838 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3839 mLatestRequest.acquire(cloned);
3840
3841 sp<Camera3Device> parent = mParent.promote();
3842 if (parent != NULL) {
3843 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3844 0, mLatestRequest);
3845 }
3846 }
3847
3848 if (nextRequest.halRequest.settings != NULL) {
3849 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3850 }
3851
3852 // Remove any previously queued triggers (after unlock)
3853 res = removeTriggers(mPrevRequest);
3854 if (res != OK) {
3855 SET_ERR("RequestThread: Unable to remove triggers "
3856 "(capture request %d, HAL device: %s (%d)",
3857 nextRequest.halRequest.frame_number, strerror(-res), res);
3858 cleanUpFailedRequests(/*sendRequestError*/ false);
3859 return false;
3860 }
3861 }
3862 return true;
3863}
3864
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003865bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003866 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003867 status_t res;
3868
3869 // Handle paused state.
3870 if (waitIfPaused()) {
3871 return true;
3872 }
3873
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003874 // Wait for the next batch of requests.
3875 waitForNextRequestBatch();
3876 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003877 return true;
3878 }
3879
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003880 // Get the latest request ID, if any
3881 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003882 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003883 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003884 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003885 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003886 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003887 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3888 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003889 }
3890
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003892 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003893 if (res == TIMED_OUT) {
3894 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003895 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003896 // Check if any stream is abandoned.
3897 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003898 return true;
3899 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003900 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003901 return false;
3902 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003903
Zhijun Hecc27e112013-10-03 16:12:43 -07003904 // Inform waitUntilRequestProcessed thread of a new request ID
3905 {
3906 Mutex::Autolock al(mLatestRequestMutex);
3907
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003908 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003909 mLatestRequestSignal.signal();
3910 }
3911
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003912 // Submit a batch of requests to HAL.
3913 // Use flush lock only when submitting multilple requests in a batch.
3914 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3915 // which may take a long time to finish so synchronizing flush() and
3916 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3917 // For now, only synchronize for high speed recording and we should figure something out for
3918 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003919 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003920
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003921 if (useFlushLock) {
3922 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003923 }
3924
Zhijun Hef0645c12016-08-02 00:58:11 -07003925 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003926 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003927
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003928 bool submitRequestSuccess = false;
3929 if (mInterface->supportBatchRequest()) {
3930 submitRequestSuccess = sendRequestsBatch();
3931 } else {
3932 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003933 }
3934
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003935 if (useFlushLock) {
3936 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003937 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003938
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003939 // Unset as current request
3940 {
3941 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003942 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003943 }
3944
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003945 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003946}
3947
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003948status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003949 ATRACE_CALL();
3950
Shuzhen Wang4a472662017-02-26 23:29:04 -08003951 for (size_t i = 0; i < mNextRequests.size(); i++) {
3952 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003953 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3954 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3955 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3956
3957 // Prepare a request to HAL
3958 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3959
3960 // Insert any queued triggers (before metadata is locked)
3961 status_t res = insertTriggers(captureRequest);
3962
3963 if (res < 0) {
3964 SET_ERR("RequestThread: Unable to insert triggers "
3965 "(capture request %d, HAL device: %s (%d)",
3966 halRequest->frame_number, strerror(-res), res);
3967 return INVALID_OPERATION;
3968 }
3969 int triggerCount = res;
3970 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3971 mPrevTriggers = triggerCount;
3972
3973 // If the request is the same as last, or we had triggers last time
3974 if (mPrevRequest != captureRequest || triggersMixedIn) {
3975 /**
3976 * HAL workaround:
3977 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3978 */
3979 res = addDummyTriggerIds(captureRequest);
3980 if (res != OK) {
3981 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3982 "(capture request %d, HAL device: %s (%d)",
3983 halRequest->frame_number, strerror(-res), res);
3984 return INVALID_OPERATION;
3985 }
3986
3987 /**
3988 * The request should be presorted so accesses in HAL
3989 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3990 */
3991 captureRequest->mSettings.sort();
3992 halRequest->settings = captureRequest->mSettings.getAndLock();
3993 mPrevRequest = captureRequest;
3994 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3995
3996 IF_ALOGV() {
3997 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3998 find_camera_metadata_ro_entry(
3999 halRequest->settings,
4000 ANDROID_CONTROL_AF_TRIGGER,
4001 &e
4002 );
4003 if (e.count > 0) {
4004 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4005 __FUNCTION__,
4006 halRequest->frame_number,
4007 e.data.u8[0]);
4008 }
4009 }
4010 } else {
4011 // leave request.settings NULL to indicate 'reuse latest given'
4012 ALOGVV("%s: Request settings are REUSED",
4013 __FUNCTION__);
4014 }
4015
4016 uint32_t totalNumBuffers = 0;
4017
4018 // Fill in buffers
4019 if (captureRequest->mInputStream != NULL) {
4020 halRequest->input_buffer = &captureRequest->mInputBuffer;
4021 totalNumBuffers += 1;
4022 } else {
4023 halRequest->input_buffer = NULL;
4024 }
4025
4026 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4027 captureRequest->mOutputStreams.size());
4028 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004029 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4030 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004031
4032 // Prepare video buffers for high speed recording on the first video request.
4033 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4034 // Only try to prepare video stream on the first video request.
4035 mPrepareVideoStream = false;
4036
4037 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4038 while (res == NOT_ENOUGH_DATA) {
4039 res = outputStream->prepareNextBuffer();
4040 }
4041 if (res != OK) {
4042 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4043 __FUNCTION__, strerror(-res), res);
4044 outputStream->cancelPrepare();
4045 }
4046 }
4047
Shuzhen Wang4a472662017-02-26 23:29:04 -08004048 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4049 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004050 if (res != OK) {
4051 // Can't get output buffer from gralloc queue - this could be due to
4052 // abandoned queue or other consumer misbehavior, so not a fatal
4053 // error
4054 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4055 " %s (%d)", strerror(-res), res);
4056
4057 return TIMED_OUT;
4058 }
4059 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004060
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004061 }
4062 totalNumBuffers += halRequest->num_output_buffers;
4063
4064 // Log request in the in-flight queue
4065 sp<Camera3Device> parent = mParent.promote();
4066 if (parent == NULL) {
4067 // Should not happen, and nowhere to send errors to, so just log it
4068 CLOGE("RequestThread: Parent is gone");
4069 return INVALID_OPERATION;
4070 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004071
4072 // If this request list is for constrained high speed recording (not
4073 // preview), and the current request is not the last one in the batch,
4074 // do not send callback to the app.
4075 bool hasCallback = true;
4076 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4077 hasCallback = false;
4078 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004079 res = parent->registerInFlight(halRequest->frame_number,
4080 totalNumBuffers, captureRequest->mResultExtras,
4081 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004082 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4084 ", burstId = %" PRId32 ".",
4085 __FUNCTION__,
4086 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4087 captureRequest->mResultExtras.burstId);
4088 if (res != OK) {
4089 SET_ERR("RequestThread: Unable to register new in-flight request:"
4090 " %s (%d)", strerror(-res), res);
4091 return INVALID_OPERATION;
4092 }
4093 }
4094
4095 return OK;
4096}
4097
Igor Murashkin1e479c02013-09-06 16:55:14 -07004098CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4099 Mutex::Autolock al(mLatestRequestMutex);
4100
4101 ALOGV("RequestThread::%s", __FUNCTION__);
4102
4103 return mLatestRequest;
4104}
4105
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004106bool Camera3Device::RequestThread::isStreamPending(
4107 sp<Camera3StreamInterface>& stream) {
4108 Mutex::Autolock l(mRequestLock);
4109
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004110 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004111 if (!nextRequest.submitted) {
4112 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4113 if (stream == s) return true;
4114 }
4115 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004116 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004117 }
4118
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004119 for (const auto& request : mRequestQueue) {
4120 for (const auto& s : request->mOutputStreams) {
4121 if (stream == s) return true;
4122 }
4123 if (stream == request->mInputStream) return true;
4124 }
4125
4126 for (const auto& request : mRepeatingRequests) {
4127 for (const auto& s : request->mOutputStreams) {
4128 if (stream == s) return true;
4129 }
4130 if (stream == request->mInputStream) return true;
4131 }
4132
4133 return false;
4134}
Jianing Weicb0652e2014-03-12 18:29:36 -07004135
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004136void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4137 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004138 return;
4139 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004140
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004141 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004142 // Skip the ones that have been submitted successfully.
4143 if (nextRequest.submitted) {
4144 continue;
4145 }
4146
4147 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4148 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4149 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4150
4151 if (halRequest->settings != NULL) {
4152 captureRequest->mSettings.unlock(halRequest->settings);
4153 }
4154
4155 if (captureRequest->mInputStream != NULL) {
4156 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4157 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4158 }
4159
4160 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4161 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4162 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4163 }
4164
4165 if (sendRequestError) {
4166 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004167 sp<NotificationListener> listener = mListener.promote();
4168 if (listener != NULL) {
4169 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004170 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004171 captureRequest->mResultExtras);
4172 }
4173 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004174
4175 // Remove yet-to-be submitted inflight request from inflightMap
4176 {
4177 sp<Camera3Device> parent = mParent.promote();
4178 if (parent != NULL) {
4179 Mutex::Autolock l(parent->mInFlightLock);
4180 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4181 if (idx >= 0) {
4182 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4183 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4184 parent->removeInFlightMapEntryLocked(idx);
4185 }
4186 }
4187 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004188 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004189
4190 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004191 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004192}
4193
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004194void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004195 // Optimized a bit for the simple steady-state case (single repeating
4196 // request), to avoid putting that request in the queue temporarily.
4197 Mutex::Autolock l(mRequestLock);
4198
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004199 assert(mNextRequests.empty());
4200
4201 NextRequest nextRequest;
4202 nextRequest.captureRequest = waitForNextRequestLocked();
4203 if (nextRequest.captureRequest == nullptr) {
4204 return;
4205 }
4206
4207 nextRequest.halRequest = camera3_capture_request_t();
4208 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004209 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004210
4211 // Wait for additional requests
4212 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4213
4214 for (size_t i = 1; i < batchSize; i++) {
4215 NextRequest additionalRequest;
4216 additionalRequest.captureRequest = waitForNextRequestLocked();
4217 if (additionalRequest.captureRequest == nullptr) {
4218 break;
4219 }
4220
4221 additionalRequest.halRequest = camera3_capture_request_t();
4222 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004223 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004224 }
4225
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004226 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004227 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004228 mNextRequests.size(), batchSize);
4229 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004230 }
4231
4232 return;
4233}
4234
4235sp<Camera3Device::CaptureRequest>
4236 Camera3Device::RequestThread::waitForNextRequestLocked() {
4237 status_t res;
4238 sp<CaptureRequest> nextRequest;
4239
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004240 while (mRequestQueue.empty()) {
4241 if (!mRepeatingRequests.empty()) {
4242 // Always atomically enqueue all requests in a repeating request
4243 // list. Guarantees a complete in-sequence set of captures to
4244 // application.
4245 const RequestList &requests = mRepeatingRequests;
4246 RequestList::const_iterator firstRequest =
4247 requests.begin();
4248 nextRequest = *firstRequest;
4249 mRequestQueue.insert(mRequestQueue.end(),
4250 ++firstRequest,
4251 requests.end());
4252 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004253
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004254 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 break;
4257 }
4258
4259 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004261 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4262 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004263 Mutex::Autolock pl(mPauseLock);
4264 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004265 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004266 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004267 // Let the tracker know
4268 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4269 if (statusTracker != 0) {
4270 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 }
4273 // Stop waiting for now and let thread management happen
4274 return NULL;
4275 }
4276 }
4277
4278 if (nextRequest == NULL) {
4279 // Don't have a repeating request already in hand, so queue
4280 // must have an entry now.
4281 RequestList::iterator firstRequest =
4282 mRequestQueue.begin();
4283 nextRequest = *firstRequest;
4284 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004285 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4286 sp<NotificationListener> listener = mListener.promote();
4287 if (listener != NULL) {
4288 listener->notifyRequestQueueEmpty();
4289 }
4290 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004291 }
4292
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004293 // In case we've been unpaused by setPaused clearing mDoPause, need to
4294 // update internal pause state (capture/setRepeatingRequest unpause
4295 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004296 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297 if (mPaused) {
4298 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4299 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4300 if (statusTracker != 0) {
4301 statusTracker->markComponentActive(mStatusId);
4302 }
4303 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004304 mPaused = false;
4305
4306 // Check if we've reconfigured since last time, and reset the preview
4307 // request if so. Can't use 'NULL request == repeat' across configure calls.
4308 if (mReconfigured) {
4309 mPrevRequest.clear();
4310 mReconfigured = false;
4311 }
4312
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004313 if (nextRequest != NULL) {
4314 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004315 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4316 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004317
4318 // Since RequestThread::clear() removes buffers from the input stream,
4319 // get the right buffer here before unlocking mRequestLock
4320 if (nextRequest->mInputStream != NULL) {
4321 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4322 if (res != OK) {
4323 // Can't get input buffer from gralloc queue - this could be due to
4324 // disconnected queue or other producer misbehavior, so not a fatal
4325 // error
4326 ALOGE("%s: Can't get input buffer, skipping request:"
4327 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004328
4329 sp<NotificationListener> listener = mListener.promote();
4330 if (listener != NULL) {
4331 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004332 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004333 nextRequest->mResultExtras);
4334 }
4335 return NULL;
4336 }
4337 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004338 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004339
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004340 return nextRequest;
4341}
4342
4343bool Camera3Device::RequestThread::waitIfPaused() {
4344 status_t res;
4345 Mutex::Autolock l(mPauseLock);
4346 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 if (mPaused == false) {
4348 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004349 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4350 // Let the tracker know
4351 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4352 if (statusTracker != 0) {
4353 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4354 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004355 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004358 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004359 return true;
4360 }
4361 }
4362 // We don't set mPaused to false here, because waitForNextRequest needs
4363 // to further manage the paused state in case of starvation.
4364 return false;
4365}
4366
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004367void Camera3Device::RequestThread::unpauseForNewRequests() {
4368 // With work to do, mark thread as unpaused.
4369 // If paused by request (setPaused), don't resume, to avoid
4370 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004371 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004372 Mutex::Autolock p(mPauseLock);
4373 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004374 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4375 if (mPaused) {
4376 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4377 if (statusTracker != 0) {
4378 statusTracker->markComponentActive(mStatusId);
4379 }
4380 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004381 mPaused = false;
4382 }
4383}
4384
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004385void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4386 sp<Camera3Device> parent = mParent.promote();
4387 if (parent != NULL) {
4388 va_list args;
4389 va_start(args, fmt);
4390
4391 parent->setErrorStateV(fmt, args);
4392
4393 va_end(args);
4394 }
4395}
4396
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004397status_t Camera3Device::RequestThread::insertTriggers(
4398 const sp<CaptureRequest> &request) {
4399
4400 Mutex::Autolock al(mTriggerMutex);
4401
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004402 sp<Camera3Device> parent = mParent.promote();
4403 if (parent == NULL) {
4404 CLOGE("RequestThread: Parent is gone");
4405 return DEAD_OBJECT;
4406 }
4407
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004408 CameraMetadata &metadata = request->mSettings;
4409 size_t count = mTriggerMap.size();
4410
4411 for (size_t i = 0; i < count; ++i) {
4412 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004413 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004414
4415 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4416 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4417 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004418 if (isAeTrigger) {
4419 request->mResultExtras.precaptureTriggerId = triggerId;
4420 mCurrentPreCaptureTriggerId = triggerId;
4421 } else {
4422 request->mResultExtras.afTriggerId = triggerId;
4423 mCurrentAfTriggerId = triggerId;
4424 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004425 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004426 }
4427
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004428 camera_metadata_entry entry = metadata.find(tag);
4429
4430 if (entry.count > 0) {
4431 /**
4432 * Already has an entry for this trigger in the request.
4433 * Rewrite it with our requested trigger value.
4434 */
4435 RequestTrigger oldTrigger = trigger;
4436
4437 oldTrigger.entryValue = entry.data.u8[0];
4438
4439 mTriggerReplacedMap.add(tag, oldTrigger);
4440 } else {
4441 /**
4442 * More typical, no trigger entry, so we just add it
4443 */
4444 mTriggerRemovedMap.add(tag, trigger);
4445 }
4446
4447 status_t res;
4448
4449 switch (trigger.getTagType()) {
4450 case TYPE_BYTE: {
4451 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4452 res = metadata.update(tag,
4453 &entryValue,
4454 /*count*/1);
4455 break;
4456 }
4457 case TYPE_INT32:
4458 res = metadata.update(tag,
4459 &trigger.entryValue,
4460 /*count*/1);
4461 break;
4462 default:
4463 ALOGE("%s: Type not supported: 0x%x",
4464 __FUNCTION__,
4465 trigger.getTagType());
4466 return INVALID_OPERATION;
4467 }
4468
4469 if (res != OK) {
4470 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4471 ", value %d", __FUNCTION__, trigger.getTagName(),
4472 trigger.entryValue);
4473 return res;
4474 }
4475
4476 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4477 trigger.getTagName(),
4478 trigger.entryValue);
4479 }
4480
4481 mTriggerMap.clear();
4482
4483 return count;
4484}
4485
4486status_t Camera3Device::RequestThread::removeTriggers(
4487 const sp<CaptureRequest> &request) {
4488 Mutex::Autolock al(mTriggerMutex);
4489
4490 CameraMetadata &metadata = request->mSettings;
4491
4492 /**
4493 * Replace all old entries with their old values.
4494 */
4495 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4496 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4497
4498 status_t res;
4499
4500 uint32_t tag = trigger.metadataTag;
4501 switch (trigger.getTagType()) {
4502 case TYPE_BYTE: {
4503 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4504 res = metadata.update(tag,
4505 &entryValue,
4506 /*count*/1);
4507 break;
4508 }
4509 case TYPE_INT32:
4510 res = metadata.update(tag,
4511 &trigger.entryValue,
4512 /*count*/1);
4513 break;
4514 default:
4515 ALOGE("%s: Type not supported: 0x%x",
4516 __FUNCTION__,
4517 trigger.getTagType());
4518 return INVALID_OPERATION;
4519 }
4520
4521 if (res != OK) {
4522 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4523 ", trigger value %d", __FUNCTION__,
4524 trigger.getTagName(), trigger.entryValue);
4525 return res;
4526 }
4527 }
4528 mTriggerReplacedMap.clear();
4529
4530 /**
4531 * Remove all new entries.
4532 */
4533 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4534 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4535 status_t res = metadata.erase(trigger.metadataTag);
4536
4537 if (res != OK) {
4538 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4539 ", trigger value %d", __FUNCTION__,
4540 trigger.getTagName(), trigger.entryValue);
4541 return res;
4542 }
4543 }
4544 mTriggerRemovedMap.clear();
4545
4546 return OK;
4547}
4548
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004549status_t Camera3Device::RequestThread::addDummyTriggerIds(
4550 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004551 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004552 static const int32_t dummyTriggerId = 1;
4553 status_t res;
4554
4555 CameraMetadata &metadata = request->mSettings;
4556
4557 // If AF trigger is active, insert a dummy AF trigger ID if none already
4558 // exists
4559 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4560 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4561 if (afTrigger.count > 0 &&
4562 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4563 afId.count == 0) {
4564 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4565 if (res != OK) return res;
4566 }
4567
4568 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4569 // if none already exists
4570 camera_metadata_entry pcTrigger =
4571 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4572 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4573 if (pcTrigger.count > 0 &&
4574 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4575 pcId.count == 0) {
4576 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4577 &dummyTriggerId, 1);
4578 if (res != OK) return res;
4579 }
4580
4581 return OK;
4582}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004583
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004584/**
4585 * PreparerThread inner class methods
4586 */
4587
4588Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004589 Thread(/*canCallJava*/false), mListener(nullptr),
4590 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004591}
4592
4593Camera3Device::PreparerThread::~PreparerThread() {
4594 Thread::requestExitAndWait();
4595 if (mCurrentStream != nullptr) {
4596 mCurrentStream->cancelPrepare();
4597 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4598 mCurrentStream.clear();
4599 }
4600 clear();
4601}
4602
Ruben Brunkc78ac262015-08-13 17:58:46 -07004603status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004604 status_t res;
4605
4606 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004607 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004608
Ruben Brunkc78ac262015-08-13 17:58:46 -07004609 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004610 if (res == OK) {
4611 // No preparation needed, fire listener right off
4612 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004613 if (listener != NULL) {
4614 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004615 }
4616 return OK;
4617 } else if (res != NOT_ENOUGH_DATA) {
4618 return res;
4619 }
4620
4621 // Need to prepare, start up thread if necessary
4622 if (!mActive) {
4623 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4624 // isn't running
4625 Thread::requestExitAndWait();
4626 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4627 if (res != OK) {
4628 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004629 if (listener != NULL) {
4630 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004631 }
4632 return res;
4633 }
4634 mCancelNow = false;
4635 mActive = true;
4636 ALOGV("%s: Preparer stream started", __FUNCTION__);
4637 }
4638
4639 // queue up the work
4640 mPendingStreams.push_back(stream);
4641 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4642
4643 return OK;
4644}
4645
4646status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004647 Mutex::Autolock l(mLock);
4648
4649 for (const auto& stream : mPendingStreams) {
4650 stream->cancelPrepare();
4651 }
4652 mPendingStreams.clear();
4653 mCancelNow = true;
4654
4655 return OK;
4656}
4657
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004658void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004659 Mutex::Autolock l(mLock);
4660 mListener = listener;
4661}
4662
4663bool Camera3Device::PreparerThread::threadLoop() {
4664 status_t res;
4665 {
4666 Mutex::Autolock l(mLock);
4667 if (mCurrentStream == nullptr) {
4668 // End thread if done with work
4669 if (mPendingStreams.empty()) {
4670 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4671 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4672 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4673 mActive = false;
4674 return false;
4675 }
4676
4677 // Get next stream to prepare
4678 auto it = mPendingStreams.begin();
4679 mCurrentStream = *it;
4680 mPendingStreams.erase(it);
4681 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4682 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4683 } else if (mCancelNow) {
4684 mCurrentStream->cancelPrepare();
4685 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4686 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4687 mCurrentStream.clear();
4688 mCancelNow = false;
4689 return true;
4690 }
4691 }
4692
4693 res = mCurrentStream->prepareNextBuffer();
4694 if (res == NOT_ENOUGH_DATA) return true;
4695 if (res != OK) {
4696 // Something bad happened; try to recover by cancelling prepare and
4697 // signalling listener anyway
4698 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4699 mCurrentStream->getId(), res, strerror(-res));
4700 mCurrentStream->cancelPrepare();
4701 }
4702
4703 // This stream has finished, notify listener
4704 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004705 sp<NotificationListener> listener = mListener.promote();
4706 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004707 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4708 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004709 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004710 }
4711
4712 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4713 mCurrentStream.clear();
4714
4715 return true;
4716}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004717
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004718/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004719 * Static callback forwarding methods from HAL to instance
4720 */
4721
4722void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4723 const camera3_capture_result *result) {
4724 Camera3Device *d =
4725 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004726
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004727 d->processCaptureResult(result);
4728}
4729
4730void Camera3Device::sNotify(const camera3_callback_ops *cb,
4731 const camera3_notify_msg *msg) {
4732 Camera3Device *d =
4733 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4734 d->notify(msg);
4735}
4736
4737}; // namespace android