blob: fb303bff14f549fc97f06d92d751062d27bb5f20 [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());
Yifan Hongf79b5542017-04-11 14:44:25 -0700214 queue = nullptr;
215 // Don't use the queue onwards.
216 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700217 auto resultQueueRet = session->getCaptureResultMetadataQueue(
218 [&queue = mResultMetadataQueue](const auto& descriptor) {
219 queue = std::make_unique<ResultMetadataQueue>(descriptor);
220 if (!queue->isValid() || queue->availableToWrite() <= 0) {
221 ALOGE("HAL returns empty result metadata fmq, not use it");
222 queue = nullptr;
223 // Don't use the queue onwards.
224 }
225 });
226 if (!resultQueueRet.isOk()) {
227 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
228 resultQueueRet.description().c_str());
229 mResultMetadataQueue = nullptr;
230 // Don't use the queue onwards.
231 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700232
Yifan Hongf79b5542017-04-11 14:44:25 -0700233 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000234 std::string providerType;
235 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800236
237 return initializeCommonLocked();
238}
239
240status_t Camera3Device::initializeCommonLocked() {
241
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700242 /** Start up status tracker thread */
243 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800244 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700245 if (res != OK) {
246 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
247 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700249 mStatusTracker.clear();
250 return res;
251 }
252
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700253 /** Register in-flight map to the status tracker */
254 mInFlightStatusId = mStatusTracker->addComponent();
255
Zhijun He125684a2015-12-26 15:07:30 -0800256 /** Create buffer manager */
257 mBufferManager = new Camera3BufferManager();
258
Emilian Peev71c73a22017-03-21 16:35:51 +0000259 mTagMonitor.initialize(mVendorTagId);
260
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700261 /** Start up request queue thread */
Emilian Peev7e25e5e2017-04-07 15:48:49 +0100262 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800263 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800264 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700265 SET_ERR_L("Unable to start request queue thread: %s (%d)",
266 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800267 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800268 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800269 return res;
270 }
271
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700272 mPreparerThread = new PreparerThread();
273
Ruben Brunk183f0562015-08-12 12:55:02 -0700274 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800275 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700276 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700277 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800279
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800280 // Measure the clock domain offset between camera and video/hw_composer
281 camera_metadata_entry timestampSource =
282 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
283 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
284 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
285 mTimestampOffset = getMonoToBoottimeOffset();
286 }
287
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700288 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100289 camera_metadata_entry partialResultsCount =
290 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
291 if (partialResultsCount.count > 0) {
292 mNumPartialResults = partialResultsCount.data.i32[0];
293 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700294 }
295
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700296 camera_metadata_entry configs =
297 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
298 for (uint32_t i = 0; i < configs.count; i += 4) {
299 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
300 configs.data.i32[i + 3] ==
301 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
302 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
303 configs.data.i32[i + 2]));
304 }
305 }
306
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800307 return OK;
308}
309
310status_t Camera3Device::disconnect() {
311 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800313
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700314 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700316 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 {
319 Mutex::Autolock l(mLock);
320 if (mStatus == STATUS_UNINITIALIZED) return res;
321
322 if (mStatus == STATUS_ACTIVE ||
323 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
324 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700325 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700327 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 } else {
329 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
330 if (res != OK) {
331 SET_ERR_L("Timeout waiting for HAL to drain");
332 // Continue to close device even in case of error
333 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700334 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800335 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800336
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700337 if (mStatus == STATUS_ERROR) {
338 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700339 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700340
341 if (mStatusTracker != NULL) {
342 mStatusTracker->requestExit();
343 }
344
345 if (mRequestThread != NULL) {
346 mRequestThread->requestExit();
347 }
348
349 mOutputStreams.clear();
350 mInputStream.clear();
351 }
352
353 // Joining done without holding mLock, otherwise deadlocks may ensue
354 // as the threads try to access parent state
355 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
356 // HAL may be in a bad state, so waiting for request thread
357 // (which may be stuck in the HAL processCaptureRequest call)
358 // could be dangerous.
359 mRequestThread->join();
360 }
361
362 if (mStatusTracker != NULL) {
363 mStatusTracker->join();
364 }
365
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800366 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367 {
368 Mutex::Autolock l(mLock);
369
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800370 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700371 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800372 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800373
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800374 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700375 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800376
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700377 // Call close without internal mutex held, as the HAL close may need to
378 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800379 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700380
381 {
382 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800383 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700384 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800386
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700387 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700388 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800389}
390
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391// For dumping/debugging only -
392// try to acquire a lock a few times, eventually give up to proceed with
393// debug/dump operations
394bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
395 bool gotLock = false;
396 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
397 if (lock.tryLock() == NO_ERROR) {
398 gotLock = true;
399 break;
400 } else {
401 usleep(kDumpSleepDuration);
402 }
403 }
404 return gotLock;
405}
406
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700407Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
408 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100409 const int STREAM_CONFIGURATION_SIZE = 4;
410 const int STREAM_FORMAT_OFFSET = 0;
411 const int STREAM_WIDTH_OFFSET = 1;
412 const int STREAM_HEIGHT_OFFSET = 2;
413 const int STREAM_IS_INPUT_OFFSET = 3;
414 camera_metadata_ro_entry_t availableStreamConfigs =
415 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
416 if (availableStreamConfigs.count == 0 ||
417 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
418 return Size(0, 0);
419 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420
Emilian Peev08dd2452017-04-06 16:55:14 +0100421 // Get max jpeg size (area-wise).
422 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
423 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
424 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
425 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
426 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
427 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
428 && format == HAL_PIXEL_FORMAT_BLOB &&
429 (width * height > maxJpegWidth * maxJpegHeight)) {
430 maxJpegWidth = width;
431 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 }
433 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100434
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700435 return Size(maxJpegWidth, maxJpegHeight);
436}
437
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800438nsecs_t Camera3Device::getMonoToBoottimeOffset() {
439 // try three times to get the clock offset, choose the one
440 // with the minimum gap in measurements.
441 const int tries = 3;
442 nsecs_t bestGap, measured;
443 for (int i = 0; i < tries; ++i) {
444 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
445 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
446 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
447 const nsecs_t gap = tmono2 - tmono;
448 if (i == 0 || gap < bestGap) {
449 bestGap = gap;
450 measured = tbase - ((tmono + tmono2) >> 1);
451 }
452 }
453 return measured;
454}
455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800456hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
457 int frameworkFormat) {
458 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
459}
460
461DataspaceFlags Camera3Device::mapToHidlDataspace(
462 android_dataspace dataSpace) {
463 return dataSpace;
464}
465
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700466BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700467 uint32_t usage) {
468 return usage;
469}
470
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800471StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
472 switch (rotation) {
473 case CAMERA3_STREAM_ROTATION_0:
474 return StreamRotation::ROTATION_0;
475 case CAMERA3_STREAM_ROTATION_90:
476 return StreamRotation::ROTATION_90;
477 case CAMERA3_STREAM_ROTATION_180:
478 return StreamRotation::ROTATION_180;
479 case CAMERA3_STREAM_ROTATION_270:
480 return StreamRotation::ROTATION_270;
481 }
482 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
483 return StreamRotation::ROTATION_0;
484}
485
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800486status_t Camera3Device::mapToStreamConfigurationMode(
487 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
488 if (mode == nullptr) return BAD_VALUE;
489 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
490 switch(operationMode) {
491 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
492 *mode = StreamConfigurationMode::NORMAL_MODE;
493 break;
494 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
495 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
496 break;
497 default:
498 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
499 return BAD_VALUE;
500 }
501 } else {
502 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800503 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800504 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800505}
506
507camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
508 switch (status) {
509 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
510 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
511 }
512 return CAMERA3_BUFFER_STATUS_ERROR;
513}
514
515int Camera3Device::mapToFrameworkFormat(
516 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
517 return static_cast<uint32_t>(pixelFormat);
518}
519
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700520uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700521 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700522 return usage;
523}
524
525uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700526 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700527 return usage;
528}
529
Zhijun Hef7da0962014-04-24 13:27:56 -0700530ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700531 // Get max jpeg size (area-wise).
532 Size maxJpegResolution = getMaxJpegResolution();
533 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
535 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700536 return BAD_VALUE;
537 }
538
Zhijun Hef7da0962014-04-24 13:27:56 -0700539 // Get max jpeg buffer size
540 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700541 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
542 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800543 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
544 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700545 return BAD_VALUE;
546 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700547 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800548 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700549
550 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700551 float scaleFactor = ((float) (width * height)) /
552 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800553 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
554 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700555 if (jpegBufferSize > maxJpegBufferSize) {
556 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700557 }
558
559 return jpegBufferSize;
560}
561
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700562ssize_t Camera3Device::getPointCloudBufferSize() const {
563 const int FLOATS_PER_POINT=4;
564 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
565 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800566 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
567 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700568 return BAD_VALUE;
569 }
570 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
571 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
572 return maxBytesForPointCloud;
573}
574
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800576 const int PER_CONFIGURATION_SIZE = 3;
577 const int WIDTH_OFFSET = 0;
578 const int HEIGHT_OFFSET = 1;
579 const int SIZE_OFFSET = 2;
580 camera_metadata_ro_entry rawOpaqueSizes =
581 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800582 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800583 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
585 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800586 return BAD_VALUE;
587 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700588
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800589 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
590 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
591 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
592 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
593 }
594 }
595
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800596 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
597 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800598 return BAD_VALUE;
599}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700600
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800601status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
602 ATRACE_CALL();
603 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700604
605 // Try to lock, but continue in case of failure (to avoid blocking in
606 // deadlocks)
607 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
608 bool gotLock = tryLockSpinRightRound(mLock);
609
610 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800611 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
612 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700613 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800614 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
615 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700616
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800617 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700618
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800619 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700620 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800621 int n = args.size();
622 for (int i = 0; i < n; i++) {
623 if (args[i] == templatesOption) {
624 dumpTemplates = true;
625 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700626 if (args[i] == monitorOption) {
627 if (i + 1 < n) {
628 String8 monitorTags = String8(args[i + 1]);
629 if (monitorTags == "off") {
630 mTagMonitor.disableMonitoring();
631 } else {
632 mTagMonitor.parseTagsToMonitor(monitorTags);
633 }
634 } else {
635 mTagMonitor.disableMonitoring();
636 }
637 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 }
639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800641
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800642 const char *status =
643 mStatus == STATUS_ERROR ? "ERROR" :
644 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
646 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 mStatus == STATUS_ACTIVE ? "ACTIVE" :
648 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700649
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800650 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700651 if (mStatus == STATUS_ERROR) {
652 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
653 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800655 const char *mode =
656 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
657 mOperatingMode == static_cast<int>(
658 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
659 "CUSTOM";
660 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800661
662 if (mInputStream != NULL) {
663 write(fd, lines.string(), lines.size());
664 mInputStream->dump(fd, args);
665 } else {
666 lines.appendFormat(" No input stream.\n");
667 write(fd, lines.string(), lines.size());
668 }
669 for (size_t i = 0; i < mOutputStreams.size(); i++) {
670 mOutputStreams[i]->dump(fd,args);
671 }
672
Zhijun He431503c2016-03-07 17:30:16 -0800673 if (mBufferManager != NULL) {
674 lines = String8(" Camera3 Buffer Manager:\n");
675 write(fd, lines.string(), lines.size());
676 mBufferManager->dump(fd, args);
677 }
Zhijun He125684a2015-12-26 15:07:30 -0800678
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700679 lines = String8(" In-flight requests:\n");
680 if (mInFlightMap.size() == 0) {
681 lines.append(" None\n");
682 } else {
683 for (size_t i = 0; i < mInFlightMap.size(); i++) {
684 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700685 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700686 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800687 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700688 r.numBuffersLeft);
689 }
690 }
691 write(fd, lines.string(), lines.size());
692
Igor Murashkin1e479c02013-09-06 16:55:14 -0700693 {
694 lines = String8(" Last request sent:\n");
695 write(fd, lines.string(), lines.size());
696
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700697 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700698 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
699 }
700
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800701 if (dumpTemplates) {
702 const char *templateNames[] = {
703 "TEMPLATE_PREVIEW",
704 "TEMPLATE_STILL_CAPTURE",
705 "TEMPLATE_VIDEO_RECORD",
706 "TEMPLATE_VIDEO_SNAPSHOT",
707 "TEMPLATE_ZERO_SHUTTER_LAG",
708 "TEMPLATE_MANUAL"
709 };
710
711 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800712 camera_metadata_t *templateRequest = nullptr;
713 mInterface->constructDefaultRequestSettings(
714 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800715 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800716 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800717 lines.append(" Not supported\n");
718 write(fd, lines.string(), lines.size());
719 } else {
720 write(fd, lines.string(), lines.size());
721 dump_indented_camera_metadata(templateRequest,
722 fd, /*verbosity*/2, /*indentation*/8);
723 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800724 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800725 }
726 }
727
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700728 mTagMonitor.dumpMonitoredMetadata(fd);
729
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800730 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800731 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800732 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800733 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800735
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700736 if (gotLock) mLock.unlock();
737 if (gotInterfaceLock) mInterfaceLock.unlock();
738
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800739 return OK;
740}
741
742const CameraMetadata& Camera3Device::info() const {
743 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800744 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
745 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700746 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800747 mStatus == STATUS_ERROR ?
748 "when in error state" : "before init");
749 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800750 return mDeviceInfo;
751}
752
Jianing Wei90e59c92014-03-12 18:29:36 -0700753status_t Camera3Device::checkStatusOkToCaptureLocked() {
754 switch (mStatus) {
755 case STATUS_ERROR:
756 CLOGE("Device has encountered a serious error");
757 return INVALID_OPERATION;
758 case STATUS_UNINITIALIZED:
759 CLOGE("Device not initialized");
760 return INVALID_OPERATION;
761 case STATUS_UNCONFIGURED:
762 case STATUS_CONFIGURED:
763 case STATUS_ACTIVE:
764 // OK
765 break;
766 default:
767 SET_ERR_L("Unexpected status: %d", mStatus);
768 return INVALID_OPERATION;
769 }
770 return OK;
771}
772
773status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 const List<const CameraMetadata> &metadataList,
775 const std::list<const SurfaceMap> &surfaceMaps,
776 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700777 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 if (requestList == NULL) {
779 CLOGE("requestList cannot be NULL.");
780 return BAD_VALUE;
781 }
782
Jianing Weicb0652e2014-03-12 18:29:36 -0700783 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
785 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
786 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
787 ++metadataIt, ++surfaceMapIt) {
788 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700789 if (newRequest == 0) {
790 CLOGE("Can't create capture request");
791 return BAD_VALUE;
792 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700793
Shuzhen Wang9d066012016-09-30 11:30:20 -0700794 newRequest->mRepeating = repeating;
795
Jianing Weicb0652e2014-03-12 18:29:36 -0700796 // Setup burst Id and request Id
797 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
799 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700800 CLOGE("RequestID entry exists; but must not be empty in metadata");
801 return BAD_VALUE;
802 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700803 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700804 } else {
805 CLOGE("RequestID does not exist in metadata");
806 return BAD_VALUE;
807 }
808
Jianing Wei90e59c92014-03-12 18:29:36 -0700809 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700810
811 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700812 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700813 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
814 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
815 return BAD_VALUE;
816 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700817
818 // Setup batch size if this is a high speed video recording request.
819 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
820 auto firstRequest = requestList->begin();
821 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
822 if (outputStream->isVideoStream()) {
823 (*firstRequest)->mBatchSize = requestList->size();
824 break;
825 }
826 }
827 }
828
Jianing Wei90e59c92014-03-12 18:29:36 -0700829 return OK;
830}
831
Jianing Weicb0652e2014-03-12 18:29:36 -0700832status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800833 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800834
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700835 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836 std::list<const SurfaceMap> surfaceMaps;
837 convertToRequestList(requests, surfaceMaps, request);
838
839 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
840}
841
842void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
843 std::list<const SurfaceMap>& surfaceMaps,
844 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700845 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846
847 SurfaceMap surfaceMap;
848 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
849 // With no surface list passed in, stream and surface will have 1-to-1
850 // mapping. So the surface index is 0 for each stream in the surfaceMap.
851 for (size_t i = 0; i < streams.count; i++) {
852 surfaceMap[streams.data.i32[i]].push_back(0);
853 }
854 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855}
856
Jianing Wei90e59c92014-03-12 18:29:36 -0700857status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 const List<const CameraMetadata> &requests,
859 const std::list<const SurfaceMap> &surfaceMaps,
860 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700861 /*out*/
862 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700863 ATRACE_CALL();
864 Mutex::Autolock il(mInterfaceLock);
865 Mutex::Autolock l(mLock);
866
867 status_t res = checkStatusOkToCaptureLocked();
868 if (res != OK) {
869 // error logged by previous call
870 return res;
871 }
872
873 RequestList requestList;
874
Shuzhen Wang0129d522016-10-30 22:43:41 -0700875 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
876 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700877 if (res != OK) {
878 // error logged by previous call
879 return res;
880 }
881
882 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700883 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700885 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700886 }
887
888 if (res == OK) {
889 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
890 if (res != OK) {
891 SET_ERR_L("Can't transition to active in %f seconds!",
892 kActiveTimeout/1e9);
893 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700895 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700896 } else {
897 CLOGE("Cannot queue request. Impossible.");
898 return BAD_VALUE;
899 }
900
901 return res;
902}
903
Yifan Honga640c5a2017-04-12 16:30:31 -0700904// Only one processCaptureResult should be called at a time, so
905// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800906hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800907 const hardware::hidl_vec<
908 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700909
910 if (mProcessCaptureResultLock.tryLock() != OK) {
911 // This should never happen; it indicates a wrong client implementation
912 // that doesn't follow the contract. But, we can be tolerant here.
913 ALOGE("%s: callback overlapped! waiting 1s...",
914 __FUNCTION__);
915 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
916 ALOGE("%s: cannot acquire lock in 1s, dropping results",
917 __FUNCTION__);
918 // really don't know what to do, so bail out.
919 return hardware::Void();
920 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800921 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700922 for (const auto& result : results) {
923 processOneCaptureResultLocked(result);
924 }
925 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800926 return hardware::Void();
927}
928
Yifan Honga640c5a2017-04-12 16:30:31 -0700929void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800930 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 camera3_capture_result r;
932 status_t res;
933 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700934
935 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
936 if (result.fmqResultSize > 0) {
937 resultMetadata.resize(result.fmqResultSize);
938 if (mResultMetadataQueue == nullptr) {
939 return; // logged in initialize()
940 }
941 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
942 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
943 __FUNCTION__, result.frameNumber, result.fmqResultSize);
944 return;
945 }
946 } else {
947 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
948 result.result.size());
949 }
950
951 if (resultMetadata.size() != 0) {
952 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
953 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800954 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
955 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
956 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800957 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800958 }
959 } else {
960 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800961 }
962
963 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
964 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
965 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
966 auto& bDst = outputBuffers[i];
967 const StreamBuffer &bSrc = result.outputBuffers[i];
968
969 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100970 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
972 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800973 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800974 }
975 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
976
977 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800978 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800979 if (res != OK) {
980 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
981 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800982 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800983 }
984 bDst.buffer = buffer;
985 bDst.status = mapHidlBufferStatus(bSrc.status);
986 bDst.acquire_fence = -1;
987 if (bSrc.releaseFence == nullptr) {
988 bDst.release_fence = -1;
989 } else if (bSrc.releaseFence->numFds == 1) {
990 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
991 } else {
992 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
993 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800994 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 }
996 }
997 r.num_output_buffers = outputBuffers.size();
998 r.output_buffers = outputBuffers.data();
999
1000 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001001 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001002 r.input_buffer = nullptr;
1003 } else {
1004 if (mInputStream->getId() != result.inputBuffer.streamId) {
1005 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1006 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001007 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001008 }
1009 inputBuffer.stream = mInputStream->asHalStream();
1010 buffer_handle_t *buffer;
1011 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1012 &buffer);
1013 if (res != OK) {
1014 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1015 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001016 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001017 }
1018 inputBuffer.buffer = buffer;
1019 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1020 inputBuffer.acquire_fence = -1;
1021 if (result.inputBuffer.releaseFence == nullptr) {
1022 inputBuffer.release_fence = -1;
1023 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1024 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1025 } else {
1026 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1027 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001028 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001029 }
1030 r.input_buffer = &inputBuffer;
1031 }
1032
1033 r.partial_result = result.partialResult;
1034
1035 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001036}
1037
1038hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001039 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1040 for (const auto& msg : msgs) {
1041 notify(msg);
1042 }
1043 return hardware::Void();
1044}
1045
1046void Camera3Device::notify(
1047 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1048
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001049 camera3_notify_msg m;
1050 switch (msg.type) {
1051 case MsgType::ERROR:
1052 m.type = CAMERA3_MSG_ERROR;
1053 m.message.error.frame_number = msg.msg.error.frameNumber;
1054 if (msg.msg.error.errorStreamId >= 0) {
1055 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001056 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001057 ALOGE("%s: Frame %d: Invalid error stream id %d",
1058 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001059 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001060 }
1061 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1062 } else {
1063 m.message.error.error_stream = nullptr;
1064 }
1065 switch (msg.msg.error.errorCode) {
1066 case ErrorCode::ERROR_DEVICE:
1067 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1068 break;
1069 case ErrorCode::ERROR_REQUEST:
1070 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1071 break;
1072 case ErrorCode::ERROR_RESULT:
1073 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1074 break;
1075 case ErrorCode::ERROR_BUFFER:
1076 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1077 break;
1078 }
1079 break;
1080 case MsgType::SHUTTER:
1081 m.type = CAMERA3_MSG_SHUTTER;
1082 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1083 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1084 break;
1085 }
1086 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001087}
1088
Jianing Weicb0652e2014-03-12 18:29:36 -07001089status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001090 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001091 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001092 ATRACE_CALL();
1093
Shuzhen Wang0129d522016-10-30 22:43:41 -07001094 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001095}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001096
Jianing Weicb0652e2014-03-12 18:29:36 -07001097status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1098 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001099 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001100
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001101 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001102 std::list<const SurfaceMap> surfaceMaps;
1103 convertToRequestList(requests, surfaceMaps, request);
1104
1105 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1106 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107}
1108
Jianing Weicb0652e2014-03-12 18:29:36 -07001109status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001110 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001111 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001112 ATRACE_CALL();
1113
Shuzhen Wang0129d522016-10-30 22:43:41 -07001114 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001115}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001116
1117sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001118 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001119 status_t res;
1120
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001121 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001122 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1123 // so unilaterally select normal operating mode.
1124 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001125 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001127 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001129 } else if (mStatus == STATUS_UNCONFIGURED) {
1130 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001131 CLOGE("No streams configured");
1132 return NULL;
1133 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001134 }
1135
Shuzhen Wang0129d522016-10-30 22:43:41 -07001136 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001138}
1139
Jianing Weicb0652e2014-03-12 18:29:36 -07001140status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001141 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001142 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001144
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001145 switch (mStatus) {
1146 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001147 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148 return INVALID_OPERATION;
1149 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001150 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001151 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001152 case STATUS_UNCONFIGURED:
1153 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001154 case STATUS_ACTIVE:
1155 // OK
1156 break;
1157 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001158 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001159 return INVALID_OPERATION;
1160 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001161 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001162
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001163 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001164}
1165
1166status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1167 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001168 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001170 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001171}
1172
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001173status_t Camera3Device::createInputStream(
1174 uint32_t width, uint32_t height, int format, int *id) {
1175 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001176 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001177 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001178 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1179 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180
1181 status_t res;
1182 bool wasActive = false;
1183
1184 switch (mStatus) {
1185 case STATUS_ERROR:
1186 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1187 return INVALID_OPERATION;
1188 case STATUS_UNINITIALIZED:
1189 ALOGE("%s: Device not initialized", __FUNCTION__);
1190 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 case STATUS_UNCONFIGURED:
1192 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001193 // OK
1194 break;
1195 case STATUS_ACTIVE:
1196 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001197 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001198 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001200 return res;
1201 }
1202 wasActive = true;
1203 break;
1204 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001205 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001206 return INVALID_OPERATION;
1207 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001208 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001209
1210 if (mInputStream != 0) {
1211 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1212 return INVALID_OPERATION;
1213 }
1214
1215 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1216 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001218
1219 mInputStream = newStream;
1220
1221 *id = mNextStreamId++;
1222
1223 // Continue captures if active at start
1224 if (wasActive) {
1225 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001226 // Reuse current operating mode for new stream config
1227 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001228 if (res != OK) {
1229 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1230 __FUNCTION__, mNextStreamId, strerror(-res), res);
1231 return res;
1232 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001233 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001234 }
1235
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001236 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001237 return OK;
1238}
1239
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001240status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001241 uint32_t width, uint32_t height, int format,
1242 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001243 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001244 ATRACE_CALL();
1245
1246 if (consumer == nullptr) {
1247 ALOGE("%s: consumer must not be null", __FUNCTION__);
1248 return BAD_VALUE;
1249 }
1250
1251 std::vector<sp<Surface>> consumers;
1252 consumers.push_back(consumer);
1253
1254 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001255 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001256}
1257
1258status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1259 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1260 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001261 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001262 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001265 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001266 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1267 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 status_t res;
1270 bool wasActive = false;
1271
1272 switch (mStatus) {
1273 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001274 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return INVALID_OPERATION;
1276 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001277 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 case STATUS_UNCONFIGURED:
1280 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 // OK
1282 break;
1283 case STATUS_ACTIVE:
1284 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001285 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 return res;
1289 }
1290 wasActive = true;
1291 break;
1292 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001293 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 return INVALID_OPERATION;
1295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001296 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297
1298 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001299
Shuzhen Wang0129d522016-10-30 22:43:41 -07001300 if (consumers.size() == 0 && !hasDeferredConsumer) {
1301 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1302 return BAD_VALUE;
1303 }
Zhijun He5d677d12016-05-29 16:52:39 -07001304
Shuzhen Wang0129d522016-10-30 22:43:41 -07001305 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001306 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1307 return BAD_VALUE;
1308 }
1309
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001311 ssize_t blobBufferSize;
1312 if (dataSpace != HAL_DATASPACE_DEPTH) {
1313 blobBufferSize = getJpegBufferSize(width, height);
1314 if (blobBufferSize <= 0) {
1315 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1316 return BAD_VALUE;
1317 }
1318 } else {
1319 blobBufferSize = getPointCloudBufferSize();
1320 if (blobBufferSize <= 0) {
1321 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1322 return BAD_VALUE;
1323 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001324 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001326 width, height, blobBufferSize, format, dataSpace, rotation,
1327 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001328 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1329 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1330 if (rawOpaqueBufferSize <= 0) {
1331 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1332 return BAD_VALUE;
1333 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001334 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001335 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1336 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001337 } else if (isShared) {
1338 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1339 width, height, format, consumerUsage, dataSpace, rotation,
1340 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001342 newStream = new Camera3OutputStream(mNextStreamId,
1343 width, height, format, consumerUsage, dataSpace, rotation,
1344 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001346 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001347 width, height, format, dataSpace, rotation,
1348 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001349 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351
Emilian Peev08dd2452017-04-06 16:55:14 +01001352 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001353
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354 res = mOutputStreams.add(mNextStreamId, newStream);
1355 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001356 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 return res;
1358 }
1359
1360 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001361 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362
1363 // Continue captures if active at start
1364 if (wasActive) {
1365 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001366 // Reuse current operating mode for new stream config
1367 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001369 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1370 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371 return res;
1372 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001373 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001374 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377}
1378
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001379status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001380 uint32_t *width, uint32_t *height,
1381 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001382 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001383 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 switch (mStatus) {
1387 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001388 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return INVALID_OPERATION;
1390 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 case STATUS_UNCONFIGURED:
1394 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 case STATUS_ACTIVE:
1396 // OK
1397 break;
1398 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return INVALID_OPERATION;
1401 }
1402
1403 ssize_t idx = mOutputStreams.indexOfKey(id);
1404 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001405 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return idx;
1407 }
1408
1409 if (width) *width = mOutputStreams[idx]->getWidth();
1410 if (height) *height = mOutputStreams[idx]->getHeight();
1411 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001412 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001414}
1415
1416status_t Camera3Device::setStreamTransform(int id,
1417 int transform) {
1418 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001419 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422 switch (mStatus) {
1423 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001424 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 return INVALID_OPERATION;
1426 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001427 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001429 case STATUS_UNCONFIGURED:
1430 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 case STATUS_ACTIVE:
1432 // OK
1433 break;
1434 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001435 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001436 return INVALID_OPERATION;
1437 }
1438
1439 ssize_t idx = mOutputStreams.indexOfKey(id);
1440 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001441 CLOGE("Stream %d does not exist",
1442 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 return BAD_VALUE;
1444 }
1445
1446 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001447}
1448
1449status_t Camera3Device::deleteStream(int id) {
1450 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001451 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 Mutex::Autolock l(mLock);
1453 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001455 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 // CameraDevice semantics require device to already be idle before
1458 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001459 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001460 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001461 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 }
1463
Igor Murashkin2fba5842013-04-22 14:03:54 -07001464 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001465 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 if (mInputStream != NULL && id == mInputStream->getId()) {
1467 deletedStream = mInputStream;
1468 mInputStream.clear();
1469 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001470 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001471 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 return BAD_VALUE;
1473 }
Zhijun He5f446352014-01-22 09:49:33 -08001474 }
1475
1476 // Delete output stream or the output part of a bi-directional stream.
1477 if (outputStreamIdx != NAME_NOT_FOUND) {
1478 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 mOutputStreams.removeItem(id);
1480 }
1481
1482 // Free up the stream endpoint so that it can be used by some other stream
1483 res = deletedStream->disconnect();
1484 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001485 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 // fall through since we want to still list the stream as deleted.
1487 }
1488 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001489 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490
1491 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001492}
1493
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001494status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001495 ATRACE_CALL();
1496 ALOGV("%s: E", __FUNCTION__);
1497
1498 Mutex::Autolock il(mInterfaceLock);
1499 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001500
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001501 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001502}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001503
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001504status_t Camera3Device::getInputBufferProducer(
1505 sp<IGraphicBufferProducer> *producer) {
1506 Mutex::Autolock il(mInterfaceLock);
1507 Mutex::Autolock l(mLock);
1508
1509 if (producer == NULL) {
1510 return BAD_VALUE;
1511 } else if (mInputStream == NULL) {
1512 return INVALID_OPERATION;
1513 }
1514
1515 return mInputStream->getInputBufferProducer(producer);
1516}
1517
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001518status_t Camera3Device::createDefaultRequest(int templateId,
1519 CameraMetadata *request) {
1520 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001521 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001522
1523 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1524 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1525 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1526 return BAD_VALUE;
1527 }
1528
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001529 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 Mutex::Autolock l(mLock);
1531
1532 switch (mStatus) {
1533 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001534 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 return INVALID_OPERATION;
1536 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 case STATUS_UNCONFIGURED:
1540 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 case STATUS_ACTIVE:
1542 // OK
1543 break;
1544 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001545 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 return INVALID_OPERATION;
1547 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548
Zhijun Hea1530f12014-09-14 12:44:20 -07001549 if (!mRequestTemplateCache[templateId].isEmpty()) {
1550 *request = mRequestTemplateCache[templateId];
1551 return OK;
1552 }
1553
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001554 camera_metadata_t *rawRequest;
1555 status_t res = mInterface->constructDefaultRequestSettings(
1556 (camera3_request_template_t) templateId, &rawRequest);
1557 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001558 ALOGI("%s: template %d is not supported on this camera device",
1559 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001560 return res;
1561 } else if (res != OK) {
1562 CLOGE("Unable to construct request template %d: %s (%d)",
1563 templateId, strerror(-res), res);
1564 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001565 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001566
Emilian Peev71c73a22017-03-21 16:35:51 +00001567 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001568 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001569
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001570 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571 return OK;
1572}
1573
1574status_t Camera3Device::waitUntilDrained() {
1575 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001578
Zhijun He69a37482014-03-23 18:44:49 -07001579 return waitUntilDrainedLocked();
1580}
1581
1582status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 switch (mStatus) {
1584 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 ALOGV("%s: Already idle", __FUNCTION__);
1587 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 case STATUS_CONFIGURED:
1589 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590 case STATUS_ERROR:
1591 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 break;
1594 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001595 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 return INVALID_OPERATION;
1597 }
1598
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001599 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001601 if (res != OK) {
1602 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1603 res);
1604 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605 return res;
1606}
1607
Ruben Brunk183f0562015-08-12 12:55:02 -07001608
1609void Camera3Device::internalUpdateStatusLocked(Status status) {
1610 mStatus = status;
1611 mRecentStatusUpdates.add(mStatus);
1612 mStatusChanged.broadcast();
1613}
1614
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001615// Pause to reconfigure
1616status_t Camera3Device::internalPauseAndWaitLocked() {
1617 mRequestThread->setPaused(true);
1618 mPauseStateNotify = true;
1619
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001620 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1622 if (res != OK) {
1623 SET_ERR_L("Can't idle device in %f seconds!",
1624 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 }
1626
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 return res;
1628}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630// Resume after internalPauseAndWaitLocked
1631status_t Camera3Device::internalResumeLocked() {
1632 status_t res;
1633
1634 mRequestThread->setPaused(false);
1635
1636 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1637 if (res != OK) {
1638 SET_ERR_L("Can't transition to active in %f seconds!",
1639 kActiveTimeout/1e9);
1640 }
1641 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001642 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643}
1644
Ruben Brunk183f0562015-08-12 12:55:02 -07001645status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001646 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001647
1648 size_t startIndex = 0;
1649 if (mStatusWaiters == 0) {
1650 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1651 // this status list
1652 mRecentStatusUpdates.clear();
1653 } else {
1654 // If other threads are waiting on updates to this status list, set the position of the
1655 // first element that this list will check rather than clearing the list.
1656 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001657 }
1658
Ruben Brunk183f0562015-08-12 12:55:02 -07001659 mStatusWaiters++;
1660
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 bool stateSeen = false;
1662 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001663 if (active == (mStatus == STATUS_ACTIVE)) {
1664 // Desired state is current
1665 break;
1666 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667
1668 res = mStatusChanged.waitRelative(mLock, timeout);
1669 if (res != OK) break;
1670
Ruben Brunk183f0562015-08-12 12:55:02 -07001671 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1672 // transitions.
1673 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1674 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1675 __FUNCTION__);
1676
1677 // Encountered desired state since we began waiting
1678 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1680 stateSeen = true;
1681 break;
1682 }
1683 }
1684 } while (!stateSeen);
1685
Ruben Brunk183f0562015-08-12 12:55:02 -07001686 mStatusWaiters--;
1687
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001688 return res;
1689}
1690
1691
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001692status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001694 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001695
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001696 if (listener != NULL && mListener != NULL) {
1697 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1698 }
1699 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001700 mRequestThread->setNotificationListener(listener);
1701 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001702
1703 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001704}
1705
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001706bool Camera3Device::willNotify3A() {
1707 return false;
1708}
1709
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001711 status_t res;
1712 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001714 while (mResultQueue.empty()) {
1715 res = mResultSignal.waitRelative(mOutputLock, timeout);
1716 if (res == TIMED_OUT) {
1717 return res;
1718 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001719 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1720 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001721 return res;
1722 }
1723 }
1724 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001725}
1726
Jianing Weicb0652e2014-03-12 18:29:36 -07001727status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001729 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001730
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001731 if (mResultQueue.empty()) {
1732 return NOT_ENOUGH_DATA;
1733 }
1734
Jianing Weicb0652e2014-03-12 18:29:36 -07001735 if (frame == NULL) {
1736 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1737 return BAD_VALUE;
1738 }
1739
1740 CaptureResult &result = *(mResultQueue.begin());
1741 frame->mResultExtras = result.mResultExtras;
1742 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001743 mResultQueue.erase(mResultQueue.begin());
1744
1745 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746}
1747
1748status_t Camera3Device::triggerAutofocus(uint32_t id) {
1749 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001752 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1753 // Mix-in this trigger into the next request and only the next request.
1754 RequestTrigger trigger[] = {
1755 {
1756 ANDROID_CONTROL_AF_TRIGGER,
1757 ANDROID_CONTROL_AF_TRIGGER_START
1758 },
1759 {
1760 ANDROID_CONTROL_AF_TRIGGER_ID,
1761 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001762 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001763 };
1764
1765 return mRequestThread->queueTrigger(trigger,
1766 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767}
1768
1769status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1770 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001772
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001773 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1774 // Mix-in this trigger into the next request and only the next request.
1775 RequestTrigger trigger[] = {
1776 {
1777 ANDROID_CONTROL_AF_TRIGGER,
1778 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1779 },
1780 {
1781 ANDROID_CONTROL_AF_TRIGGER_ID,
1782 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001783 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001784 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001786 return mRequestThread->queueTrigger(trigger,
1787 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001788}
1789
1790status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1791 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001792 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001793
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001794 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1795 // Mix-in this trigger into the next request and only the next request.
1796 RequestTrigger trigger[] = {
1797 {
1798 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1799 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1800 },
1801 {
1802 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1803 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001804 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001805 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001807 return mRequestThread->queueTrigger(trigger,
1808 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809}
1810
Jianing Weicb0652e2014-03-12 18:29:36 -07001811status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001812 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001813 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001815
Zhijun He7ef20392014-04-21 16:04:17 -07001816 {
1817 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001818 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001819 }
1820
Emilian Peev08dd2452017-04-06 16:55:14 +01001821 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001822}
1823
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001824status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001825 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1826}
1827
1828status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001829 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001830 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001831 Mutex::Autolock il(mInterfaceLock);
1832 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001833
1834 sp<Camera3StreamInterface> stream;
1835 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1836 if (outputStreamIdx == NAME_NOT_FOUND) {
1837 CLOGE("Stream %d does not exist", streamId);
1838 return BAD_VALUE;
1839 }
1840
1841 stream = mOutputStreams.editValueAt(outputStreamIdx);
1842
1843 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001844 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001845 return BAD_VALUE;
1846 }
1847
1848 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001849 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001850 return BAD_VALUE;
1851 }
1852
Ruben Brunkc78ac262015-08-13 17:58:46 -07001853 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001854}
1855
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001856status_t Camera3Device::tearDown(int streamId) {
1857 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001858 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001859 Mutex::Autolock il(mInterfaceLock);
1860 Mutex::Autolock l(mLock);
1861
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001862 sp<Camera3StreamInterface> stream;
1863 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1864 if (outputStreamIdx == NAME_NOT_FOUND) {
1865 CLOGE("Stream %d does not exist", streamId);
1866 return BAD_VALUE;
1867 }
1868
1869 stream = mOutputStreams.editValueAt(outputStreamIdx);
1870
1871 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1872 CLOGE("Stream %d is a target of a in-progress request", streamId);
1873 return BAD_VALUE;
1874 }
1875
1876 return stream->tearDown();
1877}
1878
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001879status_t Camera3Device::addBufferListenerForStream(int streamId,
1880 wp<Camera3StreamBufferListener> listener) {
1881 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001882 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001883 Mutex::Autolock il(mInterfaceLock);
1884 Mutex::Autolock l(mLock);
1885
1886 sp<Camera3StreamInterface> stream;
1887 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1888 if (outputStreamIdx == NAME_NOT_FOUND) {
1889 CLOGE("Stream %d does not exist", streamId);
1890 return BAD_VALUE;
1891 }
1892
1893 stream = mOutputStreams.editValueAt(outputStreamIdx);
1894 stream->addBufferListener(listener);
1895
1896 return OK;
1897}
1898
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001900 * Methods called by subclasses
1901 */
1902
1903void Camera3Device::notifyStatus(bool idle) {
1904 {
1905 // Need mLock to safely update state and synchronize to current
1906 // state of methods in flight.
1907 Mutex::Autolock l(mLock);
1908 // We can get various system-idle notices from the status tracker
1909 // while starting up. Only care about them if we've actually sent
1910 // in some requests recently.
1911 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1912 return;
1913 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001914 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001916 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001917
1918 // Skip notifying listener if we're doing some user-transparent
1919 // state changes
1920 if (mPauseStateNotify) return;
1921 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001922
1923 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001924 {
1925 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001926 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001927 }
1928 if (idle && listener != NULL) {
1929 listener->notifyIdle();
1930 }
1931}
1932
Shuzhen Wang758c2152017-01-10 18:26:18 -08001933status_t Camera3Device::setConsumerSurfaces(int streamId,
1934 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001935 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001936 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1937 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001938 Mutex::Autolock il(mInterfaceLock);
1939 Mutex::Autolock l(mLock);
1940
Shuzhen Wang758c2152017-01-10 18:26:18 -08001941 if (consumers.size() == 0) {
1942 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001943 return BAD_VALUE;
1944 }
1945
1946 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1947 if (idx == NAME_NOT_FOUND) {
1948 CLOGE("Stream %d is unknown", streamId);
1949 return idx;
1950 }
1951 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001952 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001953 if (res != OK) {
1954 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1955 return res;
1956 }
1957
Shuzhen Wang0129d522016-10-30 22:43:41 -07001958 if (stream->isConsumerConfigurationDeferred()) {
1959 if (!stream->isConfiguring()) {
1960 CLOGE("Stream %d was already fully configured.", streamId);
1961 return INVALID_OPERATION;
1962 }
Zhijun He5d677d12016-05-29 16:52:39 -07001963
Shuzhen Wang0129d522016-10-30 22:43:41 -07001964 res = stream->finishConfiguration();
1965 if (res != OK) {
1966 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1967 stream->getId(), strerror(-res), res);
1968 return res;
1969 }
Zhijun He5d677d12016-05-29 16:52:39 -07001970 }
1971
1972 return OK;
1973}
1974
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001975/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976 * Camera3Device private methods
1977 */
1978
1979sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001980 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001981 ATRACE_CALL();
1982 status_t res;
1983
1984 sp<CaptureRequest> newRequest = new CaptureRequest;
1985 newRequest->mSettings = request;
1986
1987 camera_metadata_entry_t inputStreams =
1988 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1989 if (inputStreams.count > 0) {
1990 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001991 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001992 CLOGE("Request references unknown input stream %d",
1993 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001994 return NULL;
1995 }
1996 // Lazy completion of stream configuration (allocation/registration)
1997 // on first use
1998 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001999 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002000 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002001 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002002 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002003 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002004 return NULL;
2005 }
2006 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002007 // Check if stream is being prepared
2008 if (mInputStream->isPreparing()) {
2009 CLOGE("Request references an input stream that's being prepared!");
2010 return NULL;
2011 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002012
2013 newRequest->mInputStream = mInputStream;
2014 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2015 }
2016
2017 camera_metadata_entry_t streams =
2018 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2019 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002020 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002021 return NULL;
2022 }
2023
2024 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002025 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002026 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002027 CLOGE("Request references unknown stream %d",
2028 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002029 return NULL;
2030 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002031 sp<Camera3OutputStreamInterface> stream =
2032 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002033
Zhijun He5d677d12016-05-29 16:52:39 -07002034 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002035 auto iter = surfaceMap.find(streams.data.i32[i]);
2036 if (iter != surfaceMap.end()) {
2037 const std::vector<size_t>& surfaces = iter->second;
2038 for (const auto& surface : surfaces) {
2039 if (stream->isConsumerConfigurationDeferred(surface)) {
2040 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2041 "due to deferred consumer", stream->getId(), surface);
2042 return NULL;
2043 }
2044 }
2045 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002046 }
2047
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 // Lazy completion of stream configuration (allocation/registration)
2049 // on first use
2050 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002051 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002053 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2054 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002055 return NULL;
2056 }
2057 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002058 // Check if stream is being prepared
2059 if (stream->isPreparing()) {
2060 CLOGE("Request references an output stream that's being prepared!");
2061 return NULL;
2062 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063
2064 newRequest->mOutputStreams.push(stream);
2065 }
2066 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002067 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002068
2069 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002070}
2071
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002072bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2073 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2074 Size size = mSupportedOpaqueInputSizes[i];
2075 if (size.width == width && size.height == height) {
2076 return true;
2077 }
2078 }
2079
2080 return false;
2081}
2082
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002083void Camera3Device::cancelStreamsConfigurationLocked() {
2084 int res = OK;
2085 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2086 res = mInputStream->cancelConfiguration();
2087 if (res != OK) {
2088 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2089 mInputStream->getId(), strerror(-res), res);
2090 }
2091 }
2092
2093 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2094 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2095 if (outputStream->isConfiguring()) {
2096 res = outputStream->cancelConfiguration();
2097 if (res != OK) {
2098 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2099 outputStream->getId(), strerror(-res), res);
2100 }
2101 }
2102 }
2103
2104 // Return state to that at start of call, so that future configures
2105 // properly clean things up
2106 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2107 mNeedConfig = true;
2108}
2109
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002110status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002111 ATRACE_CALL();
2112 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002113
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002114 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002115 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 return INVALID_OPERATION;
2117 }
2118
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002119 if (operatingMode < 0) {
2120 CLOGE("Invalid operating mode: %d", operatingMode);
2121 return BAD_VALUE;
2122 }
2123
2124 bool isConstrainedHighSpeed =
2125 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2126 operatingMode;
2127
2128 if (mOperatingMode != operatingMode) {
2129 mNeedConfig = true;
2130 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2131 mOperatingMode = operatingMode;
2132 }
2133
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002134 if (!mNeedConfig) {
2135 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2136 return OK;
2137 }
2138
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002139 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2140 // adding a dummy stream instead.
2141 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2142 if (mOutputStreams.size() == 0) {
2143 addDummyStreamLocked();
2144 } else {
2145 tryRemoveDummyStreamLocked();
2146 }
2147
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002149 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150
2151 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002152 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002153 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2154
2155 Vector<camera3_stream_t*> streams;
2156 streams.setCapacity(config.num_streams);
2157
2158 if (mInputStream != NULL) {
2159 camera3_stream_t *inputStream;
2160 inputStream = mInputStream->startConfiguration();
2161 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002162 CLOGE("Can't start input stream configuration");
2163 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164 return INVALID_OPERATION;
2165 }
2166 streams.add(inputStream);
2167 }
2168
2169 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002170
2171 // Don't configure bidi streams twice, nor add them twice to the list
2172 if (mOutputStreams[i].get() ==
2173 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2174
2175 config.num_streams--;
2176 continue;
2177 }
2178
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002179 camera3_stream_t *outputStream;
2180 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2181 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002182 CLOGE("Can't start output stream configuration");
2183 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002184 return INVALID_OPERATION;
2185 }
2186 streams.add(outputStream);
2187 }
2188
2189 config.streams = streams.editArray();
2190
2191 // Do the HAL configuration; will potentially touch stream
2192 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002193
2194 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002196 if (res == BAD_VALUE) {
2197 // HAL rejected this set of streams as unsupported, clean up config
2198 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002199 CLOGE("Set of requested inputs/outputs not supported by HAL");
2200 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002201 return BAD_VALUE;
2202 } else if (res != OK) {
2203 // Some other kind of error from configure_streams - this is not
2204 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002205 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2206 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002207 return res;
2208 }
2209
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002210 // Finish all stream configuration immediately.
2211 // TODO: Try to relax this later back to lazy completion, which should be
2212 // faster
2213
Igor Murashkin073f8572013-05-02 14:59:28 -07002214 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002215 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002216 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002217 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002218 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002219 cancelStreamsConfigurationLocked();
2220 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002221 }
2222 }
2223
2224 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002225 sp<Camera3OutputStreamInterface> outputStream =
2226 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002227 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002228 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002229 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002230 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002231 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002232 cancelStreamsConfigurationLocked();
2233 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002234 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002235 }
2236 }
2237
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238 // Request thread needs to know to avoid using repeat-last-settings protocol
2239 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002240 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241
Zhijun He90f7c372016-08-16 16:19:43 -07002242 char value[PROPERTY_VALUE_MAX];
2243 property_get("camera.fifo.disable", value, "0");
2244 int32_t disableFifo = atoi(value);
2245 if (disableFifo != 1) {
2246 // Boost priority of request thread to SCHED_FIFO.
2247 pid_t requestThreadTid = mRequestThread->getTid();
2248 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002249 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002250 if (res != OK) {
2251 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2252 strerror(-res), res);
2253 } else {
2254 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2255 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002256 }
2257
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002258 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002260 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002261
Ruben Brunk183f0562015-08-12 12:55:02 -07002262 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2263 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002264
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002265 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002266
Zhijun He0a210512014-07-24 13:45:15 -07002267 // tear down the deleted streams after configure streams.
2268 mDeletedStreams.clear();
2269
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002271}
2272
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002273status_t Camera3Device::addDummyStreamLocked() {
2274 ATRACE_CALL();
2275 status_t res;
2276
2277 if (mDummyStreamId != NO_STREAM) {
2278 // Should never be adding a second dummy stream when one is already
2279 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002280 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2281 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002282 return INVALID_OPERATION;
2283 }
2284
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002285 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002286
2287 sp<Camera3OutputStreamInterface> dummyStream =
2288 new Camera3DummyStream(mNextStreamId);
2289
2290 res = mOutputStreams.add(mNextStreamId, dummyStream);
2291 if (res < 0) {
2292 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2293 return res;
2294 }
2295
2296 mDummyStreamId = mNextStreamId;
2297 mNextStreamId++;
2298
2299 return OK;
2300}
2301
2302status_t Camera3Device::tryRemoveDummyStreamLocked() {
2303 ATRACE_CALL();
2304 status_t res;
2305
2306 if (mDummyStreamId == NO_STREAM) return OK;
2307 if (mOutputStreams.size() == 1) return OK;
2308
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002309 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002310
2311 // Ok, have a dummy stream and there's at least one other output stream,
2312 // so remove the dummy
2313
2314 sp<Camera3StreamInterface> deletedStream;
2315 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2316 if (outputStreamIdx == NAME_NOT_FOUND) {
2317 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2318 return INVALID_OPERATION;
2319 }
2320
2321 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2322 mOutputStreams.removeItemsAt(outputStreamIdx);
2323
2324 // Free up the stream endpoint so that it can be used by some other stream
2325 res = deletedStream->disconnect();
2326 if (res != OK) {
2327 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2328 // fall through since we want to still list the stream as deleted.
2329 }
2330 mDeletedStreams.add(deletedStream);
2331 mDummyStreamId = NO_STREAM;
2332
2333 return res;
2334}
2335
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002336void Camera3Device::setErrorState(const char *fmt, ...) {
2337 Mutex::Autolock l(mLock);
2338 va_list args;
2339 va_start(args, fmt);
2340
2341 setErrorStateLockedV(fmt, args);
2342
2343 va_end(args);
2344}
2345
2346void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2347 Mutex::Autolock l(mLock);
2348 setErrorStateLockedV(fmt, args);
2349}
2350
2351void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2352 va_list args;
2353 va_start(args, fmt);
2354
2355 setErrorStateLockedV(fmt, args);
2356
2357 va_end(args);
2358}
2359
2360void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002361 // Print out all error messages to log
2362 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002363 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002364
2365 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002366 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002367
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002368 mErrorCause = errorCause;
2369
2370 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002371 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002372
2373 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002374 sp<NotificationListener> listener = mListener.promote();
2375 if (listener != NULL) {
2376 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002377 CaptureResultExtras());
2378 }
2379
2380 // Save stack trace. View by dumping it later.
2381 CameraTraces::saveTrace();
2382 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002383}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384
2385/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002386 * In-flight request management
2387 */
2388
Jianing Weicb0652e2014-03-12 18:29:36 -07002389status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002390 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002391 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002392 ATRACE_CALL();
2393 Mutex::Autolock l(mInFlightLock);
2394
2395 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002396 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002397 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002398 if (res < 0) return res;
2399
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002400 if (mInFlightMap.size() == 1) {
2401 mStatusTracker->markComponentActive(mInFlightStatusId);
2402 }
2403
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002404 return OK;
2405}
2406
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002407void Camera3Device::returnOutputBuffers(
2408 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2409 nsecs_t timestamp) {
2410 for (size_t i = 0; i < numBuffers; i++)
2411 {
2412 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2413 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2414 // Note: stream may be deallocated at this point, if this buffer was
2415 // the last reference to it.
2416 if (res != OK) {
2417 ALOGE("Can't return buffer to its stream: %s (%d)",
2418 strerror(-res), res);
2419 }
2420 }
2421}
2422
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002423void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2424 mInFlightMap.removeItemsAt(idx, 1);
2425
2426 // Indicate idle inFlightMap to the status tracker
2427 if (mInFlightMap.size() == 0) {
2428 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2429 }
2430}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002431
2432void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2433
2434 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2435 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2436
2437 nsecs_t sensorTimestamp = request.sensorTimestamp;
2438 nsecs_t shutterTimestamp = request.shutterTimestamp;
2439
2440 // Check if it's okay to remove the request from InFlightMap:
2441 // In the case of a successful request:
2442 // all input and output buffers, all result metadata, shutter callback
2443 // arrived.
2444 // In the case of a unsuccessful request:
2445 // all input and output buffers arrived.
2446 if (request.numBuffersLeft == 0 &&
2447 (request.requestStatus != OK ||
2448 (request.haveResultMetadata && shutterTimestamp != 0))) {
2449 ATRACE_ASYNC_END("frame capture", frameNumber);
2450
Shuzhen Wang403044a2017-02-26 23:29:04 -08002451 // Sanity check - if sensor timestamp matches shutter timestamp in the
2452 // case of request having callback.
2453 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002454 sensorTimestamp != shutterTimestamp) {
2455 SET_ERR("sensor timestamp (%" PRId64
2456 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2457 sensorTimestamp, frameNumber, shutterTimestamp);
2458 }
2459
2460 // for an unsuccessful request, it may have pending output buffers to
2461 // return.
2462 assert(request.requestStatus != OK ||
2463 request.pendingOutputBuffers.size() == 0);
2464 returnOutputBuffers(request.pendingOutputBuffers.array(),
2465 request.pendingOutputBuffers.size(), 0);
2466
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002467 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002468 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2469 }
2470
2471 // Sanity check - if we have too many in-flight frames, something has
2472 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002473 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002474 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002475 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2476 kInFlightWarnLimitHighSpeed) {
2477 CLOGE("In-flight list too large for high speed configuration: %zu",
2478 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002479 }
2480}
2481
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002482void Camera3Device::insertResultLocked(CaptureResult *result,
2483 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002484 if (result == nullptr) return;
2485
Emilian Peev71c73a22017-03-21 16:35:51 +00002486 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2487 result->mMetadata.getAndLock());
2488 set_camera_metadata_vendor_id(meta, mVendorTagId);
2489 result->mMetadata.unlock(meta);
2490
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002491 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2492 (int32_t*)&frameNumber, 1) != OK) {
2493 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2494 return;
2495 }
2496
2497 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2498 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2499 return;
2500 }
2501
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002502 // Valid result, insert into queue
2503 List<CaptureResult>::iterator queuedResult =
2504 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2505 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2506 ", burstId = %" PRId32, __FUNCTION__,
2507 queuedResult->mResultExtras.requestId,
2508 queuedResult->mResultExtras.frameNumber,
2509 queuedResult->mResultExtras.burstId);
2510
2511 mResultSignal.signal();
2512}
2513
2514
2515void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002516 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002517 Mutex::Autolock l(mOutputLock);
2518
2519 CaptureResult captureResult;
2520 captureResult.mResultExtras = resultExtras;
2521 captureResult.mMetadata = partialResult;
2522
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002523 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002524}
2525
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002526
2527void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2528 CaptureResultExtras &resultExtras,
2529 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002530 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002531 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002532 if (pendingMetadata.isEmpty())
2533 return;
2534
2535 Mutex::Autolock l(mOutputLock);
2536
2537 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002538 if (reprocess) {
2539 if (frameNumber < mNextReprocessResultFrameNumber) {
2540 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002541 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002542 frameNumber, mNextReprocessResultFrameNumber);
2543 return;
2544 }
2545 mNextReprocessResultFrameNumber = frameNumber + 1;
2546 } else {
2547 if (frameNumber < mNextResultFrameNumber) {
2548 SET_ERR("Out-of-order capture result metadata submitted! "
2549 "(got frame number %d, expecting %d)",
2550 frameNumber, mNextResultFrameNumber);
2551 return;
2552 }
2553 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002554 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002555
2556 CaptureResult captureResult;
2557 captureResult.mResultExtras = resultExtras;
2558 captureResult.mMetadata = pendingMetadata;
2559
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002560 // Append any previous partials to form a complete result
2561 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2562 captureResult.mMetadata.append(collectedPartialResult);
2563 }
2564
2565 captureResult.mMetadata.sort();
2566
2567 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002568 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2569 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002570 SET_ERR("No timestamp provided by HAL for frame %d!",
2571 frameNumber);
2572 return;
2573 }
2574
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002575 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2576 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2577
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002578 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002579}
2580
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002581/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002582 * Camera HAL device callback methods
2583 */
2584
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002585void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002586 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002587
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002588 status_t res;
2589
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002590 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002591 if (result->result == NULL && result->num_output_buffers == 0 &&
2592 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002593 SET_ERR("No result data provided by HAL for frame %d",
2594 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002595 return;
2596 }
Zhijun He204e3292014-07-14 17:09:23 -07002597
Zhijun He204e3292014-07-14 17:09:23 -07002598 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002599 result->result != NULL &&
2600 result->partial_result != 1) {
2601 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2602 " if partial result is not supported",
2603 frameNumber, result->partial_result);
2604 return;
2605 }
2606
2607 bool isPartialResult = false;
2608 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002609 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002610 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002611
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002612 // Get shutter timestamp and resultExtras from list of in-flight requests,
2613 // where it was added by the shutter notification for this frame. If the
2614 // shutter timestamp isn't received yet, append the output buffers to the
2615 // in-flight request and they will be returned when the shutter timestamp
2616 // arrives. Update the in-flight status and remove the in-flight entry if
2617 // all result data and shutter timestamp have been received.
2618 nsecs_t shutterTimestamp = 0;
2619
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002620 {
2621 Mutex::Autolock l(mInFlightLock);
2622 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2623 if (idx == NAME_NOT_FOUND) {
2624 SET_ERR("Unknown frame number for capture result: %d",
2625 frameNumber);
2626 return;
2627 }
2628 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002629 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2630 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002631 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002632 __FUNCTION__, request.resultExtras.requestId,
2633 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002634 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002635 // Always update the partial count to the latest one if it's not 0
2636 // (buffers only). When framework aggregates adjacent partial results
2637 // into one, the latest partial count will be used.
2638 if (result->partial_result != 0)
2639 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002640
2641 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002642 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002643 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2644 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2645 " the range of [1, %d] when metadata is included in the result",
2646 frameNumber, result->partial_result, mNumPartialResults);
2647 return;
2648 }
2649 isPartialResult = (result->partial_result < mNumPartialResults);
2650 if (isPartialResult) {
2651 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002652 }
2653
Shuzhen Wang4a472662017-02-26 23:29:04 -08002654 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002655 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002656 sendPartialCaptureResult(result->result, request.resultExtras,
2657 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002658 }
2659 }
2660
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002661 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002662 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002663
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002664 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002665 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002666 if (request.haveResultMetadata) {
2667 SET_ERR("Called multiple times with metadata for frame %d",
2668 frameNumber);
2669 return;
2670 }
Zhijun He204e3292014-07-14 17:09:23 -07002671 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002672 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002673 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002674 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002675 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002676 request.haveResultMetadata = true;
2677 }
2678
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002679 uint32_t numBuffersReturned = result->num_output_buffers;
2680 if (result->input_buffer != NULL) {
2681 if (hasInputBufferInRequest) {
2682 numBuffersReturned += 1;
2683 } else {
2684 ALOGW("%s: Input buffer should be NULL if there is no input"
2685 " buffer sent in the request",
2686 __FUNCTION__);
2687 }
2688 }
2689 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002690 if (request.numBuffersLeft < 0) {
2691 SET_ERR("Too many buffers returned for frame %d",
2692 frameNumber);
2693 return;
2694 }
2695
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002696 camera_metadata_ro_entry_t entry;
2697 res = find_camera_metadata_ro_entry(result->result,
2698 ANDROID_SENSOR_TIMESTAMP, &entry);
2699 if (res == OK && entry.count == 1) {
2700 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002701 }
2702
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002703 // If shutter event isn't received yet, append the output buffers to
2704 // the in-flight request. Otherwise, return the output buffers to
2705 // streams.
2706 if (shutterTimestamp == 0) {
2707 request.pendingOutputBuffers.appendArray(result->output_buffers,
2708 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002709 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002710 returnOutputBuffers(result->output_buffers,
2711 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002712 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002713
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002714 if (result->result != NULL && !isPartialResult) {
2715 if (shutterTimestamp == 0) {
2716 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002717 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002718 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002719 CameraMetadata metadata;
2720 metadata = result->result;
2721 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002722 collectedPartialResult, frameNumber,
2723 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002724 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002725 }
2726
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002727 removeInFlightRequestIfReadyLocked(idx);
2728 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002729
Zhijun Hef0d962a2014-06-30 10:24:11 -07002730 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002731 if (hasInputBufferInRequest) {
2732 Camera3Stream *stream =
2733 Camera3Stream::cast(result->input_buffer->stream);
2734 res = stream->returnInputBuffer(*(result->input_buffer));
2735 // Note: stream may be deallocated at this point, if this buffer was the
2736 // last reference to it.
2737 if (res != OK) {
2738 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2739 " its stream:%s (%d)", __FUNCTION__,
2740 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002741 }
2742 } else {
2743 ALOGW("%s: Input buffer should be NULL if there is no input"
2744 " buffer sent in the request, skipping input buffer return.",
2745 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002746 }
2747 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002748}
2749
2750void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002751 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002752 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002753 {
2754 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002755 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002756 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002757
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002758 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002759 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002760 return;
2761 }
2762
2763 switch (msg->type) {
2764 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002765 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002766 break;
2767 }
2768 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002769 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002770 break;
2771 }
2772 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002773 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002774 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002775 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002776}
2777
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002778void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002779 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002780
2781 // Map camera HAL error codes to ICameraDeviceCallback error codes
2782 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002783 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002784 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002785 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002786 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002787 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002788 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002789 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002790 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002791 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002792 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002793 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002794 };
2795
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002796 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002797 ((msg.error_code >= 0) &&
2798 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2799 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002800 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002801
2802 int streamId = 0;
2803 if (msg.error_stream != NULL) {
2804 Camera3Stream *stream =
2805 Camera3Stream::cast(msg.error_stream);
2806 streamId = stream->getId();
2807 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002808 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2809 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002810 streamId, msg.error_code);
2811
2812 CaptureResultExtras resultExtras;
2813 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002814 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002815 // SET_ERR calls notifyError
2816 SET_ERR("Camera HAL reported serious device error");
2817 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002818 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2819 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2820 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002821 {
2822 Mutex::Autolock l(mInFlightLock);
2823 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2824 if (idx >= 0) {
2825 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2826 r.requestStatus = msg.error_code;
2827 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002828 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2829 errorCode) {
2830 // In case of missing result check whether the buffers
2831 // returned. If they returned, then remove inflight
2832 // request.
2833 removeInFlightRequestIfReadyLocked(idx);
2834 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 } else {
2836 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002837 ALOGE("Camera %s: %s: cannot find in-flight request on "
2838 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002839 resultExtras.frameNumber);
2840 }
2841 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002842 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002843 if (listener != NULL) {
2844 listener->notifyError(errorCode, resultExtras);
2845 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002846 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002847 }
2848 break;
2849 default:
2850 // SET_ERR calls notifyError
2851 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2852 break;
2853 }
2854}
2855
2856void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002857 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002860 // Set timestamp for the request in the in-flight tracking
2861 // and get the request ID to send upstream
2862 {
2863 Mutex::Autolock l(mInFlightLock);
2864 idx = mInFlightMap.indexOfKey(msg.frame_number);
2865 if (idx >= 0) {
2866 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002867
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002868 // Verify ordering of shutter notifications
2869 {
2870 Mutex::Autolock l(mOutputLock);
2871 // TODO: need to track errors for tighter bounds on expected frame number.
2872 if (r.hasInputBuffer) {
2873 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2874 SET_ERR("Shutter notification out-of-order. Expected "
2875 "notification for frame %d, got frame %d",
2876 mNextReprocessShutterFrameNumber, msg.frame_number);
2877 return;
2878 }
2879 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2880 } else {
2881 if (msg.frame_number < mNextShutterFrameNumber) {
2882 SET_ERR("Shutter notification out-of-order. Expected "
2883 "notification for frame %d, got frame %d",
2884 mNextShutterFrameNumber, msg.frame_number);
2885 return;
2886 }
2887 mNextShutterFrameNumber = msg.frame_number + 1;
2888 }
2889 }
2890
Shuzhen Wang4a472662017-02-26 23:29:04 -08002891 r.shutterTimestamp = msg.timestamp;
2892 if (r.hasCallback) {
2893 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002894 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002895 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002896 // Call listener, if any
2897 if (listener != NULL) {
2898 listener->notifyShutter(r.resultExtras, msg.timestamp);
2899 }
2900 // send pending result and buffers
2901 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2902 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002903 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002904 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002905 returnOutputBuffers(r.pendingOutputBuffers.array(),
2906 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2907 r.pendingOutputBuffers.clear();
2908
2909 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002910 }
2911 }
2912 if (idx < 0) {
2913 SET_ERR("Shutter notification for non-existent frame number %d",
2914 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002915 }
2916}
2917
2918
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002919CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002920 ALOGV("%s", __FUNCTION__);
2921
Igor Murashkin1e479c02013-09-06 16:55:14 -07002922 CameraMetadata retVal;
2923
2924 if (mRequestThread != NULL) {
2925 retVal = mRequestThread->getLatestRequest();
2926 }
2927
Igor Murashkin1e479c02013-09-06 16:55:14 -07002928 return retVal;
2929}
2930
Jianing Weicb0652e2014-03-12 18:29:36 -07002931
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002932void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2933 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2934 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2935}
2936
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002937/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002938 * HalInterface inner class methods
2939 */
2940
2941Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
2942 mHal3Device(device) {}
2943
Yifan Hongf79b5542017-04-11 14:44:25 -07002944Camera3Device::HalInterface::HalInterface(
2945 sp<ICameraDeviceSession> &session,
2946 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002947 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002948 mHidlSession(session),
2949 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002950
2951Camera3Device::HalInterface::HalInterface() :
2952 mHal3Device(nullptr) {}
2953
2954Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002955 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002956 mHidlSession(other.mHidlSession),
2957 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002958
2959bool Camera3Device::HalInterface::valid() {
2960 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2961}
2962
2963void Camera3Device::HalInterface::clear() {
2964 mHal3Device = nullptr;
2965 mHidlSession.clear();
2966}
2967
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002968bool Camera3Device::HalInterface::supportBatchRequest() {
2969 return mHidlSession != nullptr;
2970}
2971
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002972status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2973 camera3_request_template_t templateId,
2974 /*out*/ camera_metadata_t **requestTemplate) {
2975 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2976 if (!valid()) return INVALID_OPERATION;
2977 status_t res = OK;
2978
2979 if (mHal3Device != nullptr) {
2980 const camera_metadata *r;
2981 r = mHal3Device->ops->construct_default_request_settings(
2982 mHal3Device, templateId);
2983 if (r == nullptr) return BAD_VALUE;
2984 *requestTemplate = clone_camera_metadata(r);
2985 if (requestTemplate == nullptr) {
2986 ALOGE("%s: Unable to clone camera metadata received from HAL",
2987 __FUNCTION__);
2988 return INVALID_OPERATION;
2989 }
2990 } else {
2991 common::V1_0::Status status;
2992 RequestTemplate id;
2993 switch (templateId) {
2994 case CAMERA3_TEMPLATE_PREVIEW:
2995 id = RequestTemplate::PREVIEW;
2996 break;
2997 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2998 id = RequestTemplate::STILL_CAPTURE;
2999 break;
3000 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3001 id = RequestTemplate::VIDEO_RECORD;
3002 break;
3003 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3004 id = RequestTemplate::VIDEO_SNAPSHOT;
3005 break;
3006 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3007 id = RequestTemplate::ZERO_SHUTTER_LAG;
3008 break;
3009 case CAMERA3_TEMPLATE_MANUAL:
3010 id = RequestTemplate::MANUAL;
3011 break;
3012 default:
3013 // Unknown template ID
3014 return BAD_VALUE;
3015 }
3016 mHidlSession->constructDefaultRequestSettings(id,
3017 [&status, &requestTemplate]
3018 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3019 status = s;
3020 if (status == common::V1_0::Status::OK) {
3021 const camera_metadata *r =
3022 reinterpret_cast<const camera_metadata_t*>(request.data());
3023 size_t expectedSize = request.size();
3024 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003025 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003026 *requestTemplate = clone_camera_metadata(r);
3027 if (*requestTemplate == nullptr) {
3028 ALOGE("%s: Unable to clone camera metadata received from HAL",
3029 __FUNCTION__);
3030 status = common::V1_0::Status::INTERNAL_ERROR;
3031 }
3032 } else {
3033 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3034 status = common::V1_0::Status::INTERNAL_ERROR;
3035 }
3036 }
3037 });
3038 res = CameraProviderManager::mapToStatusT(status);
3039 }
3040 return res;
3041}
3042
3043status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3044 ATRACE_NAME("CameraHal::configureStreams");
3045 if (!valid()) return INVALID_OPERATION;
3046 status_t res = OK;
3047
3048 if (mHal3Device != nullptr) {
3049 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3050 } else {
3051 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003052 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003053 StreamConfiguration requestedConfiguration;
3054 requestedConfiguration.streams.resize(config->num_streams);
3055 for (size_t i = 0; i < config->num_streams; i++) {
3056 Stream &dst = requestedConfiguration.streams[i];
3057 camera3_stream_t *src = config->streams[i];
3058
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003059 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3060 cam3stream->setBufferFreedListener(this);
3061 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003062 StreamType streamType;
3063 switch (src->stream_type) {
3064 case CAMERA3_STREAM_OUTPUT:
3065 streamType = StreamType::OUTPUT;
3066 break;
3067 case CAMERA3_STREAM_INPUT:
3068 streamType = StreamType::INPUT;
3069 break;
3070 default:
3071 ALOGE("%s: Stream %d: Unsupported stream type %d",
3072 __FUNCTION__, streamId, config->streams[i]->stream_type);
3073 return BAD_VALUE;
3074 }
3075 dst.id = streamId;
3076 dst.streamType = streamType;
3077 dst.width = src->width;
3078 dst.height = src->height;
3079 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003080 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003081 dst.dataSpace = mapToHidlDataspace(src->data_space);
3082 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003083
3084 activeStreams.insert(streamId);
3085 // Create Buffer ID map if necessary
3086 if (mBufferIdMaps.count(streamId) == 0) {
3087 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3088 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003089 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003090 // remove BufferIdMap for deleted streams
3091 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3092 int streamId = it->first;
3093 bool active = activeStreams.count(streamId) > 0;
3094 if (!active) {
3095 it = mBufferIdMaps.erase(it);
3096 } else {
3097 ++it;
3098 }
3099 }
3100
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003101 res = mapToStreamConfigurationMode(
3102 (camera3_stream_configuration_mode_t) config->operation_mode,
3103 /*out*/ &requestedConfiguration.operationMode);
3104 if (res != OK) {
3105 return res;
3106 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003107
3108 // Invoke configureStreams
3109
3110 HalStreamConfiguration finalConfiguration;
3111 common::V1_0::Status status;
3112 mHidlSession->configureStreams(requestedConfiguration,
3113 [&status, &finalConfiguration]
3114 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3115 finalConfiguration = halConfiguration;
3116 status = s;
3117 });
3118 if (status != common::V1_0::Status::OK ) {
3119 return CameraProviderManager::mapToStatusT(status);
3120 }
3121
3122 // And convert output stream configuration from HIDL
3123
3124 for (size_t i = 0; i < config->num_streams; i++) {
3125 camera3_stream_t *dst = config->streams[i];
3126 int streamId = Camera3Stream::cast(dst)->getId();
3127
3128 // Start scan at i, with the assumption that the stream order matches
3129 size_t realIdx = i;
3130 bool found = false;
3131 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3132 if (finalConfiguration.streams[realIdx].id == streamId) {
3133 found = true;
3134 break;
3135 }
3136 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3137 }
3138 if (!found) {
3139 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3140 __FUNCTION__, streamId);
3141 return INVALID_OPERATION;
3142 }
3143 HalStream &src = finalConfiguration.streams[realIdx];
3144
3145 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3146 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3147 if (dst->format != overrideFormat) {
3148 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3149 streamId, dst->format);
3150 }
3151 } else {
3152 // Override allowed with IMPLEMENTATION_DEFINED
3153 dst->format = overrideFormat;
3154 }
3155
3156 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3157 if (src.producerUsage != 0) {
3158 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3159 __FUNCTION__, streamId);
3160 return INVALID_OPERATION;
3161 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003162 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003163 } else {
3164 // OUTPUT
3165 if (src.consumerUsage != 0) {
3166 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3167 __FUNCTION__, streamId);
3168 return INVALID_OPERATION;
3169 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003170 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003171 }
3172 dst->max_buffers = src.maxBuffers;
3173 }
3174 }
3175 return res;
3176}
3177
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003178void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3179 /*out*/device::V3_2::CaptureRequest* captureRequest,
3180 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3181
3182 if (captureRequest == nullptr || handlesCreated == nullptr) {
3183 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3184 __FUNCTION__, captureRequest, handlesCreated);
3185 return;
3186 }
3187
3188 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003189
3190 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003191
3192 {
3193 std::lock_guard<std::mutex> lock(mInflightLock);
3194 if (request->input_buffer != nullptr) {
3195 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3196 buffer_handle_t buf = *(request->input_buffer->buffer);
3197 auto pair = getBufferId(buf, streamId);
3198 bool isNewBuffer = pair.first;
3199 uint64_t bufferId = pair.second;
3200 captureRequest->inputBuffer.streamId = streamId;
3201 captureRequest->inputBuffer.bufferId = bufferId;
3202 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3203 captureRequest->inputBuffer.status = BufferStatus::OK;
3204 native_handle_t *acquireFence = nullptr;
3205 if (request->input_buffer->acquire_fence != -1) {
3206 acquireFence = native_handle_create(1,0);
3207 acquireFence->data[0] = request->input_buffer->acquire_fence;
3208 handlesCreated->push_back(acquireFence);
3209 }
3210 captureRequest->inputBuffer.acquireFence = acquireFence;
3211 captureRequest->inputBuffer.releaseFence = nullptr;
3212
3213 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3214 request->input_buffer->buffer,
3215 request->input_buffer->acquire_fence);
3216 } else {
3217 captureRequest->inputBuffer.streamId = -1;
3218 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3219 }
3220
3221 captureRequest->outputBuffers.resize(request->num_output_buffers);
3222 for (size_t i = 0; i < request->num_output_buffers; i++) {
3223 const camera3_stream_buffer_t *src = request->output_buffers + i;
3224 StreamBuffer &dst = captureRequest->outputBuffers[i];
3225 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3226 buffer_handle_t buf = *(src->buffer);
3227 auto pair = getBufferId(buf, streamId);
3228 bool isNewBuffer = pair.first;
3229 dst.streamId = streamId;
3230 dst.bufferId = pair.second;
3231 dst.buffer = isNewBuffer ? buf : nullptr;
3232 dst.status = BufferStatus::OK;
3233 native_handle_t *acquireFence = nullptr;
3234 if (src->acquire_fence != -1) {
3235 acquireFence = native_handle_create(1,0);
3236 acquireFence->data[0] = src->acquire_fence;
3237 handlesCreated->push_back(acquireFence);
3238 }
3239 dst.acquireFence = acquireFence;
3240 dst.releaseFence = nullptr;
3241
3242 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3243 src->buffer, src->acquire_fence);
3244 }
3245 }
3246}
3247
3248status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3249 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3250 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3251 if (!valid()) return INVALID_OPERATION;
3252
3253 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3254 size_t batchSize = requests.size();
3255 captureRequests.resize(batchSize);
3256 std::vector<native_handle_t*> handlesCreated;
3257
3258 for (size_t i = 0; i < batchSize; i++) {
3259 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3260 }
3261
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003262 std::vector<device::V3_2::BufferCache> cachesToRemove;
3263 {
3264 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3265 for (auto& pair : mFreedBuffers) {
3266 // The stream might have been removed since onBufferFreed
3267 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3268 cachesToRemove.push_back({pair.first, pair.second});
3269 }
3270 }
3271 mFreedBuffers.clear();
3272 }
3273
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003274 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3275 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003276
3277 // Write metadata to FMQ.
3278 for (size_t i = 0; i < batchSize; i++) {
3279 camera3_capture_request_t* request = requests[i];
3280 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3281
3282 if (request->settings != nullptr) {
3283 size_t settingsSize = get_camera_metadata_size(request->settings);
3284 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3285 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3286 captureRequest->settings.resize(0);
3287 captureRequest->fmqSettingsSize = settingsSize;
3288 } else {
3289 if (mRequestMetadataQueue != nullptr) {
3290 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3291 }
3292 captureRequest->settings.setToExternal(
3293 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3294 get_camera_metadata_size(request->settings));
3295 captureRequest->fmqSettingsSize = 0u;
3296 }
3297 } else {
3298 // A null request settings maps to a size-0 CameraMetadata
3299 captureRequest->settings.resize(0);
3300 captureRequest->fmqSettingsSize = 0u;
3301 }
3302 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003303 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003304 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3305 status = s;
3306 *numRequestProcessed = n;
3307 });
3308
3309 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3310 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3311 __FUNCTION__, *numRequestProcessed, batchSize);
3312 status = common::V1_0::Status::INTERNAL_ERROR;
3313 }
3314
3315 for (auto& handle : handlesCreated) {
3316 native_handle_delete(handle);
3317 }
3318 return CameraProviderManager::mapToStatusT(status);
3319}
3320
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003321status_t Camera3Device::HalInterface::processCaptureRequest(
3322 camera3_capture_request_t *request) {
3323 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003324 if (!valid()) return INVALID_OPERATION;
3325 status_t res = OK;
3326
3327 if (mHal3Device != nullptr) {
3328 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3329 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003330 uint32_t numRequestProcessed = 0;
3331 std::vector<camera3_capture_request_t*> requests(1);
3332 requests[0] = request;
3333 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003334 }
3335 return res;
3336}
3337
3338status_t Camera3Device::HalInterface::flush() {
3339 ATRACE_NAME("CameraHal::flush");
3340 if (!valid()) return INVALID_OPERATION;
3341 status_t res = OK;
3342
3343 if (mHal3Device != nullptr) {
3344 res = mHal3Device->ops->flush(mHal3Device);
3345 } else {
3346 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3347 }
3348 return res;
3349}
3350
3351status_t Camera3Device::HalInterface::dump(int fd) {
3352 ATRACE_NAME("CameraHal::dump");
3353 if (!valid()) return INVALID_OPERATION;
3354 status_t res = OK;
3355
3356 if (mHal3Device != nullptr) {
3357 mHal3Device->ops->dump(mHal3Device, fd);
3358 } else {
3359 // Handled by CameraProviderManager::dump
3360 }
3361 return res;
3362}
3363
3364status_t Camera3Device::HalInterface::close() {
3365 ATRACE_NAME("CameraHal::close()");
3366 if (!valid()) return INVALID_OPERATION;
3367 status_t res = OK;
3368
3369 if (mHal3Device != nullptr) {
3370 mHal3Device->common.close(&mHal3Device->common);
3371 } else {
3372 mHidlSession->close();
3373 }
3374 return res;
3375}
3376
3377status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003378 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003379 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003380 auto pair = std::make_pair(buffer, acquireFence);
3381 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003382 return OK;
3383}
3384
3385status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003386 int32_t frameNumber, int32_t streamId,
3387 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003388 std::lock_guard<std::mutex> lock(mInflightLock);
3389
3390 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3391 auto it = mInflightBufferMap.find(key);
3392 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003393 auto pair = it->second;
3394 *buffer = pair.first;
3395 int acquireFence = pair.second;
3396 if (acquireFence > 0) {
3397 ::close(acquireFence);
3398 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003399 mInflightBufferMap.erase(it);
3400 return OK;
3401}
3402
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003403std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3404 const buffer_handle_t& buf, int streamId) {
3405 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3406
3407 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3408 auto it = bIdMap.find(buf);
3409 if (it == bIdMap.end()) {
3410 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003411 ALOGV("stream %d now have %zu buffer caches, buf %p",
3412 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003413 return std::make_pair(true, mNextBufferId - 1);
3414 } else {
3415 return std::make_pair(false, it->second);
3416 }
3417}
3418
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003419void Camera3Device::HalInterface::onBufferFreed(
3420 int streamId, const native_handle_t* handle) {
3421 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3422 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3423 auto mapIt = mBufferIdMaps.find(streamId);
3424 if (mapIt == mBufferIdMaps.end()) {
3425 // streamId might be from a deleted stream here
3426 ALOGI("%s: stream %d has been removed",
3427 __FUNCTION__, streamId);
3428 return;
3429 }
3430 BufferIdMap& bIdMap = mapIt->second;
3431 auto it = bIdMap.find(handle);
3432 if (it == bIdMap.end()) {
3433 ALOGW("%s: cannot find buffer %p in stream %d",
3434 __FUNCTION__, handle, streamId);
3435 return;
3436 } else {
3437 bufferId = it->second;
3438 bIdMap.erase(it);
3439 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3440 __FUNCTION__, streamId, bIdMap.size(), handle);
3441 }
3442 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3443}
3444
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003445/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446 * RequestThread inner class methods
3447 */
3448
3449Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003450 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003451 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003452 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003453 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003454 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003455 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003456 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003457 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003458 mReconfigured(false),
3459 mDoPause(false),
3460 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003461 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003462 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003463 mCurrentAfTriggerId(0),
3464 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003465 mRepeatingLastFrameNumber(
3466 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003467 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003468 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003469}
3470
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003471Camera3Device::RequestThread::~RequestThread() {}
3472
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003473void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003474 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003475 Mutex::Autolock l(mRequestLock);
3476 mListener = listener;
3477}
3478
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003479void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003480 Mutex::Autolock l(mRequestLock);
3481 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003482 // Prepare video stream for high speed recording.
3483 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003484}
3485
Jianing Wei90e59c92014-03-12 18:29:36 -07003486status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003487 List<sp<CaptureRequest> > &requests,
3488 /*out*/
3489 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003490 Mutex::Autolock l(mRequestLock);
3491 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3492 ++it) {
3493 mRequestQueue.push_back(*it);
3494 }
3495
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003496 if (lastFrameNumber != NULL) {
3497 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3498 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3499 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3500 *lastFrameNumber);
3501 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003502
Jianing Wei90e59c92014-03-12 18:29:36 -07003503 unpauseForNewRequests();
3504
3505 return OK;
3506}
3507
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003508
3509status_t Camera3Device::RequestThread::queueTrigger(
3510 RequestTrigger trigger[],
3511 size_t count) {
3512
3513 Mutex::Autolock l(mTriggerMutex);
3514 status_t ret;
3515
3516 for (size_t i = 0; i < count; ++i) {
3517 ret = queueTriggerLocked(trigger[i]);
3518
3519 if (ret != OK) {
3520 return ret;
3521 }
3522 }
3523
3524 return OK;
3525}
3526
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003527const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3528 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003529 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003530 if (d != nullptr) return d->mId;
3531 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003532}
3533
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003534status_t Camera3Device::RequestThread::queueTriggerLocked(
3535 RequestTrigger trigger) {
3536
3537 uint32_t tag = trigger.metadataTag;
3538 ssize_t index = mTriggerMap.indexOfKey(tag);
3539
3540 switch (trigger.getTagType()) {
3541 case TYPE_BYTE:
3542 // fall-through
3543 case TYPE_INT32:
3544 break;
3545 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003546 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3547 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003548 return INVALID_OPERATION;
3549 }
3550
3551 /**
3552 * Collect only the latest trigger, since we only have 1 field
3553 * in the request settings per trigger tag, and can't send more than 1
3554 * trigger per request.
3555 */
3556 if (index != NAME_NOT_FOUND) {
3557 mTriggerMap.editValueAt(index) = trigger;
3558 } else {
3559 mTriggerMap.add(tag, trigger);
3560 }
3561
3562 return OK;
3563}
3564
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003565status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003566 const RequestList &requests,
3567 /*out*/
3568 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003569 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003570 if (lastFrameNumber != NULL) {
3571 *lastFrameNumber = mRepeatingLastFrameNumber;
3572 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003573 mRepeatingRequests.clear();
3574 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3575 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003576
3577 unpauseForNewRequests();
3578
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003579 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003580 return OK;
3581}
3582
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003583bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003584 if (mRepeatingRequests.empty()) {
3585 return false;
3586 }
3587 int32_t requestId = requestIn->mResultExtras.requestId;
3588 const RequestList &repeatRequests = mRepeatingRequests;
3589 // All repeating requests are guaranteed to have same id so only check first quest
3590 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3591 return (firstRequest->mResultExtras.requestId == requestId);
3592}
3593
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003594status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003595 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003596 return clearRepeatingRequestsLocked(lastFrameNumber);
3597
3598}
3599
3600status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003601 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003602 if (lastFrameNumber != NULL) {
3603 *lastFrameNumber = mRepeatingLastFrameNumber;
3604 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003605 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003606 return OK;
3607}
3608
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003609status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003610 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003611 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003612 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003613
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003614 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003615
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003616 // Send errors for all requests pending in the request queue, including
3617 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003618 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003619 if (listener != NULL) {
3620 for (RequestList::iterator it = mRequestQueue.begin();
3621 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003622 // Abort the input buffers for reprocess requests.
3623 if ((*it)->mInputStream != NULL) {
3624 camera3_stream_buffer_t inputBuffer;
3625 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3626 if (res != OK) {
3627 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3628 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3629 } else {
3630 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3631 if (res != OK) {
3632 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3633 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3634 }
3635 }
3636 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 // Set the frame number this request would have had, if it
3638 // had been submitted; this frame number will not be reused.
3639 // The requestId and burstId fields were set when the request was
3640 // submitted originally (in convertMetadataListToRequestListLocked)
3641 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003642 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003643 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003644 }
3645 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003646 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003647
3648 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003649 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003650 if (lastFrameNumber != NULL) {
3651 *lastFrameNumber = mRepeatingLastFrameNumber;
3652 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003653 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003654 return OK;
3655}
3656
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003657status_t Camera3Device::RequestThread::flush() {
3658 ATRACE_CALL();
3659 Mutex::Autolock l(mFlushLock);
3660
Emilian Peev08dd2452017-04-06 16:55:14 +01003661 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003662}
3663
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003664void Camera3Device::RequestThread::setPaused(bool paused) {
3665 Mutex::Autolock l(mPauseLock);
3666 mDoPause = paused;
3667 mDoPauseSignal.signal();
3668}
3669
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003670status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3671 int32_t requestId, nsecs_t timeout) {
3672 Mutex::Autolock l(mLatestRequestMutex);
3673 status_t res;
3674 while (mLatestRequestId != requestId) {
3675 nsecs_t startTime = systemTime();
3676
3677 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3678 if (res != OK) return res;
3679
3680 timeout -= (systemTime() - startTime);
3681 }
3682
3683 return OK;
3684}
3685
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003686void Camera3Device::RequestThread::requestExit() {
3687 // Call parent to set up shutdown
3688 Thread::requestExit();
3689 // The exit from any possible waits
3690 mDoPauseSignal.signal();
3691 mRequestSignal.signal();
3692}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003693
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003694void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003695 bool surfaceAbandoned = false;
3696 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003697 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003698 {
3699 Mutex::Autolock l(mRequestLock);
3700 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3701 // repeating requests.
3702 for (const auto& request : mRepeatingRequests) {
3703 for (const auto& s : request->mOutputStreams) {
3704 if (s->isAbandoned()) {
3705 surfaceAbandoned = true;
3706 clearRepeatingRequestsLocked(&lastFrameNumber);
3707 break;
3708 }
3709 }
3710 if (surfaceAbandoned) {
3711 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003712 }
3713 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003714 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003715 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003716
3717 if (listener != NULL && surfaceAbandoned) {
3718 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003719 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003720}
3721
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003722bool Camera3Device::RequestThread::sendRequestsBatch() {
3723 status_t res;
3724 size_t batchSize = mNextRequests.size();
3725 std::vector<camera3_capture_request_t*> requests(batchSize);
3726 uint32_t numRequestProcessed = 0;
3727 for (size_t i = 0; i < batchSize; i++) {
3728 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3729 }
3730
3731 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3732 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3733
3734 bool triggerRemoveFailed = false;
3735 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3736 for (size_t i = 0; i < numRequestProcessed; i++) {
3737 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3738 nextRequest.submitted = true;
3739
3740
3741 // Update the latest request sent to HAL
3742 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3743 Mutex::Autolock al(mLatestRequestMutex);
3744
3745 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3746 mLatestRequest.acquire(cloned);
3747
3748 sp<Camera3Device> parent = mParent.promote();
3749 if (parent != NULL) {
3750 parent->monitorMetadata(TagMonitor::REQUEST,
3751 nextRequest.halRequest.frame_number,
3752 0, mLatestRequest);
3753 }
3754 }
3755
3756 if (nextRequest.halRequest.settings != NULL) {
3757 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3758 }
3759
3760 if (!triggerRemoveFailed) {
3761 // Remove any previously queued triggers (after unlock)
3762 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3763 if (removeTriggerRes != OK) {
3764 triggerRemoveFailed = true;
3765 triggerFailedRequest = nextRequest;
3766 }
3767 }
3768 }
3769
3770 if (triggerRemoveFailed) {
3771 SET_ERR("RequestThread: Unable to remove triggers "
3772 "(capture request %d, HAL device: %s (%d)",
3773 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3774 cleanUpFailedRequests(/*sendRequestError*/ false);
3775 return false;
3776 }
3777
3778 if (res != OK) {
3779 // Should only get a failure here for malformed requests or device-level
3780 // errors, so consider all errors fatal. Bad metadata failures should
3781 // come through notify.
3782 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3783 mNextRequests[numRequestProcessed].halRequest.frame_number,
3784 strerror(-res), res);
3785 cleanUpFailedRequests(/*sendRequestError*/ false);
3786 return false;
3787 }
3788 return true;
3789}
3790
3791bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3792 status_t res;
3793
3794 for (auto& nextRequest : mNextRequests) {
3795 // Submit request and block until ready for next one
3796 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3797 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
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"
3804 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3805 res);
3806 cleanUpFailedRequests(/*sendRequestError*/ false);
3807 return false;
3808 }
3809
3810 // Mark that the request has be submitted successfully.
3811 nextRequest.submitted = true;
3812
3813 // Update the latest request sent to HAL
3814 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3815 Mutex::Autolock al(mLatestRequestMutex);
3816
3817 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3818 mLatestRequest.acquire(cloned);
3819
3820 sp<Camera3Device> parent = mParent.promote();
3821 if (parent != NULL) {
3822 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3823 0, mLatestRequest);
3824 }
3825 }
3826
3827 if (nextRequest.halRequest.settings != NULL) {
3828 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3829 }
3830
3831 // Remove any previously queued triggers (after unlock)
3832 res = removeTriggers(mPrevRequest);
3833 if (res != OK) {
3834 SET_ERR("RequestThread: Unable to remove triggers "
3835 "(capture request %d, HAL device: %s (%d)",
3836 nextRequest.halRequest.frame_number, strerror(-res), res);
3837 cleanUpFailedRequests(/*sendRequestError*/ false);
3838 return false;
3839 }
3840 }
3841 return true;
3842}
3843
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003844bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003845 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003846 status_t res;
3847
3848 // Handle paused state.
3849 if (waitIfPaused()) {
3850 return true;
3851 }
3852
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003853 // Wait for the next batch of requests.
3854 waitForNextRequestBatch();
3855 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003856 return true;
3857 }
3858
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003859 // Get the latest request ID, if any
3860 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003861 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003862 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003863 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003864 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003865 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003866 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3867 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003868 }
3869
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003870 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003871 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003872 if (res == TIMED_OUT) {
3873 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003874 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003875 // Check if any stream is abandoned.
3876 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003877 return true;
3878 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003879 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003880 return false;
3881 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003882
Zhijun Hecc27e112013-10-03 16:12:43 -07003883 // Inform waitUntilRequestProcessed thread of a new request ID
3884 {
3885 Mutex::Autolock al(mLatestRequestMutex);
3886
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003887 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003888 mLatestRequestSignal.signal();
3889 }
3890
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 // Submit a batch of requests to HAL.
3892 // Use flush lock only when submitting multilple requests in a batch.
3893 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3894 // which may take a long time to finish so synchronizing flush() and
3895 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3896 // For now, only synchronize for high speed recording and we should figure something out for
3897 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003898 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003899
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003900 if (useFlushLock) {
3901 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003902 }
3903
Zhijun Hef0645c12016-08-02 00:58:11 -07003904 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003905 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003906
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003907 bool submitRequestSuccess = false;
3908 if (mInterface->supportBatchRequest()) {
3909 submitRequestSuccess = sendRequestsBatch();
3910 } else {
3911 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003912 }
3913
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003914 if (useFlushLock) {
3915 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003916 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003917
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003918 // Unset as current request
3919 {
3920 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003921 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003922 }
3923
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003924 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003925}
3926
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003927status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003928 ATRACE_CALL();
3929
Shuzhen Wang4a472662017-02-26 23:29:04 -08003930 for (size_t i = 0; i < mNextRequests.size(); i++) {
3931 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003932 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3933 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3934 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3935
3936 // Prepare a request to HAL
3937 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3938
3939 // Insert any queued triggers (before metadata is locked)
3940 status_t res = insertTriggers(captureRequest);
3941
3942 if (res < 0) {
3943 SET_ERR("RequestThread: Unable to insert triggers "
3944 "(capture request %d, HAL device: %s (%d)",
3945 halRequest->frame_number, strerror(-res), res);
3946 return INVALID_OPERATION;
3947 }
3948 int triggerCount = res;
3949 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3950 mPrevTriggers = triggerCount;
3951
3952 // If the request is the same as last, or we had triggers last time
3953 if (mPrevRequest != captureRequest || triggersMixedIn) {
3954 /**
3955 * HAL workaround:
3956 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3957 */
3958 res = addDummyTriggerIds(captureRequest);
3959 if (res != OK) {
3960 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3961 "(capture request %d, HAL device: %s (%d)",
3962 halRequest->frame_number, strerror(-res), res);
3963 return INVALID_OPERATION;
3964 }
3965
3966 /**
3967 * The request should be presorted so accesses in HAL
3968 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3969 */
3970 captureRequest->mSettings.sort();
3971 halRequest->settings = captureRequest->mSettings.getAndLock();
3972 mPrevRequest = captureRequest;
3973 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3974
3975 IF_ALOGV() {
3976 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3977 find_camera_metadata_ro_entry(
3978 halRequest->settings,
3979 ANDROID_CONTROL_AF_TRIGGER,
3980 &e
3981 );
3982 if (e.count > 0) {
3983 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3984 __FUNCTION__,
3985 halRequest->frame_number,
3986 e.data.u8[0]);
3987 }
3988 }
3989 } else {
3990 // leave request.settings NULL to indicate 'reuse latest given'
3991 ALOGVV("%s: Request settings are REUSED",
3992 __FUNCTION__);
3993 }
3994
3995 uint32_t totalNumBuffers = 0;
3996
3997 // Fill in buffers
3998 if (captureRequest->mInputStream != NULL) {
3999 halRequest->input_buffer = &captureRequest->mInputBuffer;
4000 totalNumBuffers += 1;
4001 } else {
4002 halRequest->input_buffer = NULL;
4003 }
4004
4005 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4006 captureRequest->mOutputStreams.size());
4007 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004008 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4009 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004010
4011 // Prepare video buffers for high speed recording on the first video request.
4012 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4013 // Only try to prepare video stream on the first video request.
4014 mPrepareVideoStream = false;
4015
4016 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4017 while (res == NOT_ENOUGH_DATA) {
4018 res = outputStream->prepareNextBuffer();
4019 }
4020 if (res != OK) {
4021 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4022 __FUNCTION__, strerror(-res), res);
4023 outputStream->cancelPrepare();
4024 }
4025 }
4026
Shuzhen Wang4a472662017-02-26 23:29:04 -08004027 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4028 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004029 if (res != OK) {
4030 // Can't get output buffer from gralloc queue - this could be due to
4031 // abandoned queue or other consumer misbehavior, so not a fatal
4032 // error
4033 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4034 " %s (%d)", strerror(-res), res);
4035
4036 return TIMED_OUT;
4037 }
4038 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004039
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004040 }
4041 totalNumBuffers += halRequest->num_output_buffers;
4042
4043 // Log request in the in-flight queue
4044 sp<Camera3Device> parent = mParent.promote();
4045 if (parent == NULL) {
4046 // Should not happen, and nowhere to send errors to, so just log it
4047 CLOGE("RequestThread: Parent is gone");
4048 return INVALID_OPERATION;
4049 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004050
4051 // If this request list is for constrained high speed recording (not
4052 // preview), and the current request is not the last one in the batch,
4053 // do not send callback to the app.
4054 bool hasCallback = true;
4055 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4056 hasCallback = false;
4057 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004058 res = parent->registerInFlight(halRequest->frame_number,
4059 totalNumBuffers, captureRequest->mResultExtras,
4060 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004061 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004062 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4063 ", burstId = %" PRId32 ".",
4064 __FUNCTION__,
4065 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4066 captureRequest->mResultExtras.burstId);
4067 if (res != OK) {
4068 SET_ERR("RequestThread: Unable to register new in-flight request:"
4069 " %s (%d)", strerror(-res), res);
4070 return INVALID_OPERATION;
4071 }
4072 }
4073
4074 return OK;
4075}
4076
Igor Murashkin1e479c02013-09-06 16:55:14 -07004077CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4078 Mutex::Autolock al(mLatestRequestMutex);
4079
4080 ALOGV("RequestThread::%s", __FUNCTION__);
4081
4082 return mLatestRequest;
4083}
4084
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004085bool Camera3Device::RequestThread::isStreamPending(
4086 sp<Camera3StreamInterface>& stream) {
4087 Mutex::Autolock l(mRequestLock);
4088
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004089 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004090 if (!nextRequest.submitted) {
4091 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4092 if (stream == s) return true;
4093 }
4094 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004095 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004096 }
4097
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004098 for (const auto& request : mRequestQueue) {
4099 for (const auto& s : request->mOutputStreams) {
4100 if (stream == s) return true;
4101 }
4102 if (stream == request->mInputStream) return true;
4103 }
4104
4105 for (const auto& request : mRepeatingRequests) {
4106 for (const auto& s : request->mOutputStreams) {
4107 if (stream == s) return true;
4108 }
4109 if (stream == request->mInputStream) return true;
4110 }
4111
4112 return false;
4113}
Jianing Weicb0652e2014-03-12 18:29:36 -07004114
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004115void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4116 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004117 return;
4118 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004119
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004120 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004121 // Skip the ones that have been submitted successfully.
4122 if (nextRequest.submitted) {
4123 continue;
4124 }
4125
4126 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4127 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4128 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4129
4130 if (halRequest->settings != NULL) {
4131 captureRequest->mSettings.unlock(halRequest->settings);
4132 }
4133
4134 if (captureRequest->mInputStream != NULL) {
4135 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4136 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4137 }
4138
4139 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4140 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4141 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4142 }
4143
4144 if (sendRequestError) {
4145 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004146 sp<NotificationListener> listener = mListener.promote();
4147 if (listener != NULL) {
4148 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004149 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004150 captureRequest->mResultExtras);
4151 }
4152 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004153
4154 // Remove yet-to-be submitted inflight request from inflightMap
4155 {
4156 sp<Camera3Device> parent = mParent.promote();
4157 if (parent != NULL) {
4158 Mutex::Autolock l(parent->mInFlightLock);
4159 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4160 if (idx >= 0) {
4161 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4162 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4163 parent->removeInFlightMapEntryLocked(idx);
4164 }
4165 }
4166 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004167 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004168
4169 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004170 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004171}
4172
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004173void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004174 // Optimized a bit for the simple steady-state case (single repeating
4175 // request), to avoid putting that request in the queue temporarily.
4176 Mutex::Autolock l(mRequestLock);
4177
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004178 assert(mNextRequests.empty());
4179
4180 NextRequest nextRequest;
4181 nextRequest.captureRequest = waitForNextRequestLocked();
4182 if (nextRequest.captureRequest == nullptr) {
4183 return;
4184 }
4185
4186 nextRequest.halRequest = camera3_capture_request_t();
4187 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004188 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004189
4190 // Wait for additional requests
4191 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4192
4193 for (size_t i = 1; i < batchSize; i++) {
4194 NextRequest additionalRequest;
4195 additionalRequest.captureRequest = waitForNextRequestLocked();
4196 if (additionalRequest.captureRequest == nullptr) {
4197 break;
4198 }
4199
4200 additionalRequest.halRequest = camera3_capture_request_t();
4201 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004202 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004203 }
4204
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004205 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004206 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004207 mNextRequests.size(), batchSize);
4208 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004209 }
4210
4211 return;
4212}
4213
4214sp<Camera3Device::CaptureRequest>
4215 Camera3Device::RequestThread::waitForNextRequestLocked() {
4216 status_t res;
4217 sp<CaptureRequest> nextRequest;
4218
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004219 while (mRequestQueue.empty()) {
4220 if (!mRepeatingRequests.empty()) {
4221 // Always atomically enqueue all requests in a repeating request
4222 // list. Guarantees a complete in-sequence set of captures to
4223 // application.
4224 const RequestList &requests = mRepeatingRequests;
4225 RequestList::const_iterator firstRequest =
4226 requests.begin();
4227 nextRequest = *firstRequest;
4228 mRequestQueue.insert(mRequestQueue.end(),
4229 ++firstRequest,
4230 requests.end());
4231 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004232
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004233 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004234
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004235 break;
4236 }
4237
4238 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4239
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004240 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4241 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004242 Mutex::Autolock pl(mPauseLock);
4243 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004244 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004245 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004246 // Let the tracker know
4247 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4248 if (statusTracker != 0) {
4249 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4250 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251 }
4252 // Stop waiting for now and let thread management happen
4253 return NULL;
4254 }
4255 }
4256
4257 if (nextRequest == NULL) {
4258 // Don't have a repeating request already in hand, so queue
4259 // must have an entry now.
4260 RequestList::iterator firstRequest =
4261 mRequestQueue.begin();
4262 nextRequest = *firstRequest;
4263 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004264 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4265 sp<NotificationListener> listener = mListener.promote();
4266 if (listener != NULL) {
4267 listener->notifyRequestQueueEmpty();
4268 }
4269 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004270 }
4271
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004272 // In case we've been unpaused by setPaused clearing mDoPause, need to
4273 // update internal pause state (capture/setRepeatingRequest unpause
4274 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004275 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004276 if (mPaused) {
4277 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4278 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4279 if (statusTracker != 0) {
4280 statusTracker->markComponentActive(mStatusId);
4281 }
4282 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004283 mPaused = false;
4284
4285 // Check if we've reconfigured since last time, and reset the preview
4286 // request if so. Can't use 'NULL request == repeat' across configure calls.
4287 if (mReconfigured) {
4288 mPrevRequest.clear();
4289 mReconfigured = false;
4290 }
4291
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004292 if (nextRequest != NULL) {
4293 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004294 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4295 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004296
4297 // Since RequestThread::clear() removes buffers from the input stream,
4298 // get the right buffer here before unlocking mRequestLock
4299 if (nextRequest->mInputStream != NULL) {
4300 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4301 if (res != OK) {
4302 // Can't get input buffer from gralloc queue - this could be due to
4303 // disconnected queue or other producer misbehavior, so not a fatal
4304 // error
4305 ALOGE("%s: Can't get input buffer, skipping request:"
4306 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004307
4308 sp<NotificationListener> listener = mListener.promote();
4309 if (listener != NULL) {
4310 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004311 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004312 nextRequest->mResultExtras);
4313 }
4314 return NULL;
4315 }
4316 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004317 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004318
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004319 return nextRequest;
4320}
4321
4322bool Camera3Device::RequestThread::waitIfPaused() {
4323 status_t res;
4324 Mutex::Autolock l(mPauseLock);
4325 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004326 if (mPaused == false) {
4327 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4329 // Let the tracker know
4330 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4331 if (statusTracker != 0) {
4332 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004335
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004336 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004337 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 return true;
4339 }
4340 }
4341 // We don't set mPaused to false here, because waitForNextRequest needs
4342 // to further manage the paused state in case of starvation.
4343 return false;
4344}
4345
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004346void Camera3Device::RequestThread::unpauseForNewRequests() {
4347 // With work to do, mark thread as unpaused.
4348 // If paused by request (setPaused), don't resume, to avoid
4349 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004350 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004351 Mutex::Autolock p(mPauseLock);
4352 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004353 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4354 if (mPaused) {
4355 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4356 if (statusTracker != 0) {
4357 statusTracker->markComponentActive(mStatusId);
4358 }
4359 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004360 mPaused = false;
4361 }
4362}
4363
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004364void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4365 sp<Camera3Device> parent = mParent.promote();
4366 if (parent != NULL) {
4367 va_list args;
4368 va_start(args, fmt);
4369
4370 parent->setErrorStateV(fmt, args);
4371
4372 va_end(args);
4373 }
4374}
4375
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004376status_t Camera3Device::RequestThread::insertTriggers(
4377 const sp<CaptureRequest> &request) {
4378
4379 Mutex::Autolock al(mTriggerMutex);
4380
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004381 sp<Camera3Device> parent = mParent.promote();
4382 if (parent == NULL) {
4383 CLOGE("RequestThread: Parent is gone");
4384 return DEAD_OBJECT;
4385 }
4386
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004387 CameraMetadata &metadata = request->mSettings;
4388 size_t count = mTriggerMap.size();
4389
4390 for (size_t i = 0; i < count; ++i) {
4391 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004392 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004393
4394 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4395 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4396 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004397 if (isAeTrigger) {
4398 request->mResultExtras.precaptureTriggerId = triggerId;
4399 mCurrentPreCaptureTriggerId = triggerId;
4400 } else {
4401 request->mResultExtras.afTriggerId = triggerId;
4402 mCurrentAfTriggerId = triggerId;
4403 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004404 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004405 }
4406
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004407 camera_metadata_entry entry = metadata.find(tag);
4408
4409 if (entry.count > 0) {
4410 /**
4411 * Already has an entry for this trigger in the request.
4412 * Rewrite it with our requested trigger value.
4413 */
4414 RequestTrigger oldTrigger = trigger;
4415
4416 oldTrigger.entryValue = entry.data.u8[0];
4417
4418 mTriggerReplacedMap.add(tag, oldTrigger);
4419 } else {
4420 /**
4421 * More typical, no trigger entry, so we just add it
4422 */
4423 mTriggerRemovedMap.add(tag, trigger);
4424 }
4425
4426 status_t res;
4427
4428 switch (trigger.getTagType()) {
4429 case TYPE_BYTE: {
4430 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4431 res = metadata.update(tag,
4432 &entryValue,
4433 /*count*/1);
4434 break;
4435 }
4436 case TYPE_INT32:
4437 res = metadata.update(tag,
4438 &trigger.entryValue,
4439 /*count*/1);
4440 break;
4441 default:
4442 ALOGE("%s: Type not supported: 0x%x",
4443 __FUNCTION__,
4444 trigger.getTagType());
4445 return INVALID_OPERATION;
4446 }
4447
4448 if (res != OK) {
4449 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4450 ", value %d", __FUNCTION__, trigger.getTagName(),
4451 trigger.entryValue);
4452 return res;
4453 }
4454
4455 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4456 trigger.getTagName(),
4457 trigger.entryValue);
4458 }
4459
4460 mTriggerMap.clear();
4461
4462 return count;
4463}
4464
4465status_t Camera3Device::RequestThread::removeTriggers(
4466 const sp<CaptureRequest> &request) {
4467 Mutex::Autolock al(mTriggerMutex);
4468
4469 CameraMetadata &metadata = request->mSettings;
4470
4471 /**
4472 * Replace all old entries with their old values.
4473 */
4474 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4475 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4476
4477 status_t res;
4478
4479 uint32_t tag = trigger.metadataTag;
4480 switch (trigger.getTagType()) {
4481 case TYPE_BYTE: {
4482 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4483 res = metadata.update(tag,
4484 &entryValue,
4485 /*count*/1);
4486 break;
4487 }
4488 case TYPE_INT32:
4489 res = metadata.update(tag,
4490 &trigger.entryValue,
4491 /*count*/1);
4492 break;
4493 default:
4494 ALOGE("%s: Type not supported: 0x%x",
4495 __FUNCTION__,
4496 trigger.getTagType());
4497 return INVALID_OPERATION;
4498 }
4499
4500 if (res != OK) {
4501 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4502 ", trigger value %d", __FUNCTION__,
4503 trigger.getTagName(), trigger.entryValue);
4504 return res;
4505 }
4506 }
4507 mTriggerReplacedMap.clear();
4508
4509 /**
4510 * Remove all new entries.
4511 */
4512 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4513 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4514 status_t res = metadata.erase(trigger.metadataTag);
4515
4516 if (res != OK) {
4517 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4518 ", trigger value %d", __FUNCTION__,
4519 trigger.getTagName(), trigger.entryValue);
4520 return res;
4521 }
4522 }
4523 mTriggerRemovedMap.clear();
4524
4525 return OK;
4526}
4527
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004528status_t Camera3Device::RequestThread::addDummyTriggerIds(
4529 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004530 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004531 static const int32_t dummyTriggerId = 1;
4532 status_t res;
4533
4534 CameraMetadata &metadata = request->mSettings;
4535
4536 // If AF trigger is active, insert a dummy AF trigger ID if none already
4537 // exists
4538 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4539 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4540 if (afTrigger.count > 0 &&
4541 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4542 afId.count == 0) {
4543 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4544 if (res != OK) return res;
4545 }
4546
4547 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4548 // if none already exists
4549 camera_metadata_entry pcTrigger =
4550 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4551 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4552 if (pcTrigger.count > 0 &&
4553 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4554 pcId.count == 0) {
4555 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4556 &dummyTriggerId, 1);
4557 if (res != OK) return res;
4558 }
4559
4560 return OK;
4561}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004562
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004563/**
4564 * PreparerThread inner class methods
4565 */
4566
4567Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004568 Thread(/*canCallJava*/false), mListener(nullptr),
4569 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004570}
4571
4572Camera3Device::PreparerThread::~PreparerThread() {
4573 Thread::requestExitAndWait();
4574 if (mCurrentStream != nullptr) {
4575 mCurrentStream->cancelPrepare();
4576 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4577 mCurrentStream.clear();
4578 }
4579 clear();
4580}
4581
Ruben Brunkc78ac262015-08-13 17:58:46 -07004582status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004583 status_t res;
4584
4585 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004586 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004587
Ruben Brunkc78ac262015-08-13 17:58:46 -07004588 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004589 if (res == OK) {
4590 // No preparation needed, fire listener right off
4591 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004592 if (listener != NULL) {
4593 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004594 }
4595 return OK;
4596 } else if (res != NOT_ENOUGH_DATA) {
4597 return res;
4598 }
4599
4600 // Need to prepare, start up thread if necessary
4601 if (!mActive) {
4602 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4603 // isn't running
4604 Thread::requestExitAndWait();
4605 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4606 if (res != OK) {
4607 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004608 if (listener != NULL) {
4609 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004610 }
4611 return res;
4612 }
4613 mCancelNow = false;
4614 mActive = true;
4615 ALOGV("%s: Preparer stream started", __FUNCTION__);
4616 }
4617
4618 // queue up the work
4619 mPendingStreams.push_back(stream);
4620 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4621
4622 return OK;
4623}
4624
4625status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004626 Mutex::Autolock l(mLock);
4627
4628 for (const auto& stream : mPendingStreams) {
4629 stream->cancelPrepare();
4630 }
4631 mPendingStreams.clear();
4632 mCancelNow = true;
4633
4634 return OK;
4635}
4636
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004637void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004638 Mutex::Autolock l(mLock);
4639 mListener = listener;
4640}
4641
4642bool Camera3Device::PreparerThread::threadLoop() {
4643 status_t res;
4644 {
4645 Mutex::Autolock l(mLock);
4646 if (mCurrentStream == nullptr) {
4647 // End thread if done with work
4648 if (mPendingStreams.empty()) {
4649 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4650 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4651 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4652 mActive = false;
4653 return false;
4654 }
4655
4656 // Get next stream to prepare
4657 auto it = mPendingStreams.begin();
4658 mCurrentStream = *it;
4659 mPendingStreams.erase(it);
4660 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4661 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4662 } else if (mCancelNow) {
4663 mCurrentStream->cancelPrepare();
4664 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4665 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4666 mCurrentStream.clear();
4667 mCancelNow = false;
4668 return true;
4669 }
4670 }
4671
4672 res = mCurrentStream->prepareNextBuffer();
4673 if (res == NOT_ENOUGH_DATA) return true;
4674 if (res != OK) {
4675 // Something bad happened; try to recover by cancelling prepare and
4676 // signalling listener anyway
4677 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4678 mCurrentStream->getId(), res, strerror(-res));
4679 mCurrentStream->cancelPrepare();
4680 }
4681
4682 // This stream has finished, notify listener
4683 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004684 sp<NotificationListener> listener = mListener.promote();
4685 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004686 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4687 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004688 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004689 }
4690
4691 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4692 mCurrentStream.clear();
4693
4694 return true;
4695}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004696
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004697/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004698 * Static callback forwarding methods from HAL to instance
4699 */
4700
4701void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4702 const camera3_capture_result *result) {
4703 Camera3Device *d =
4704 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004705
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004706 d->processCaptureResult(result);
4707}
4708
4709void Camera3Device::sNotify(const camera3_callback_ops *cb,
4710 const camera3_notify_msg *msg) {
4711 Camera3Device *d =
4712 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4713 d->notify(msg);
4714}
4715
4716}; // namespace android