blob: ff5a149123726f0687e8bbbaf3b6797cd5b724ef [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
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700274 // Determine whether we need to derive sensitivity boost values for older devices.
275 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
276 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800277 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700278 mDerivePostRawSensKey = true;
279 }
280
Ruben Brunk183f0562015-08-12 12:55:02 -0700281 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800282 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700283 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700284 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700285 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800286
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800287 // Measure the clock domain offset between camera and video/hw_composer
288 camera_metadata_entry timestampSource =
289 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
290 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
291 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
292 mTimestampOffset = getMonoToBoottimeOffset();
293 }
294
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700295 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100296 camera_metadata_entry partialResultsCount =
297 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
298 if (partialResultsCount.count > 0) {
299 mNumPartialResults = partialResultsCount.data.i32[0];
300 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700301 }
302
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700303 camera_metadata_entry configs =
304 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
305 for (uint32_t i = 0; i < configs.count; i += 4) {
306 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
307 configs.data.i32[i + 3] ==
308 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
309 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
310 configs.data.i32[i + 2]));
311 }
312 }
313
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800314 return OK;
315}
316
317status_t Camera3Device::disconnect() {
318 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800320
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700321 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700323 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700325 {
326 Mutex::Autolock l(mLock);
327 if (mStatus == STATUS_UNINITIALIZED) return res;
328
329 if (mStatus == STATUS_ACTIVE ||
330 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
331 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700332 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700333 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700334 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700335 } else {
336 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
337 if (res != OK) {
338 SET_ERR_L("Timeout waiting for HAL to drain");
339 // Continue to close device even in case of error
340 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700341 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800342 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 if (mStatus == STATUS_ERROR) {
345 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700347
348 if (mStatusTracker != NULL) {
349 mStatusTracker->requestExit();
350 }
351
352 if (mRequestThread != NULL) {
353 mRequestThread->requestExit();
354 }
355
356 mOutputStreams.clear();
357 mInputStream.clear();
358 }
359
360 // Joining done without holding mLock, otherwise deadlocks may ensue
361 // as the threads try to access parent state
362 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
363 // HAL may be in a bad state, so waiting for request thread
364 // (which may be stuck in the HAL processCaptureRequest call)
365 // could be dangerous.
366 mRequestThread->join();
367 }
368
369 if (mStatusTracker != NULL) {
370 mStatusTracker->join();
371 }
372
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800373 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700374 {
375 Mutex::Autolock l(mLock);
376
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800377 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800379 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800380
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800381 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700382 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800383
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700384 // Call close without internal mutex held, as the HAL close may need to
385 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800386 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700387
388 {
389 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800390 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700391 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700394 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700395 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800396}
397
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398// For dumping/debugging only -
399// try to acquire a lock a few times, eventually give up to proceed with
400// debug/dump operations
401bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
402 bool gotLock = false;
403 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
404 if (lock.tryLock() == NO_ERROR) {
405 gotLock = true;
406 break;
407 } else {
408 usleep(kDumpSleepDuration);
409 }
410 }
411 return gotLock;
412}
413
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700414Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
415 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100416 const int STREAM_CONFIGURATION_SIZE = 4;
417 const int STREAM_FORMAT_OFFSET = 0;
418 const int STREAM_WIDTH_OFFSET = 1;
419 const int STREAM_HEIGHT_OFFSET = 2;
420 const int STREAM_IS_INPUT_OFFSET = 3;
421 camera_metadata_ro_entry_t availableStreamConfigs =
422 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
423 if (availableStreamConfigs.count == 0 ||
424 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
425 return Size(0, 0);
426 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700427
Emilian Peev08dd2452017-04-06 16:55:14 +0100428 // Get max jpeg size (area-wise).
429 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
430 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
431 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
432 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
433 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
434 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
435 && format == HAL_PIXEL_FORMAT_BLOB &&
436 (width * height > maxJpegWidth * maxJpegHeight)) {
437 maxJpegWidth = width;
438 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700439 }
440 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100441
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700442 return Size(maxJpegWidth, maxJpegHeight);
443}
444
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800445nsecs_t Camera3Device::getMonoToBoottimeOffset() {
446 // try three times to get the clock offset, choose the one
447 // with the minimum gap in measurements.
448 const int tries = 3;
449 nsecs_t bestGap, measured;
450 for (int i = 0; i < tries; ++i) {
451 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
452 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
453 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
454 const nsecs_t gap = tmono2 - tmono;
455 if (i == 0 || gap < bestGap) {
456 bestGap = gap;
457 measured = tbase - ((tmono + tmono2) >> 1);
458 }
459 }
460 return measured;
461}
462
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800463hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
464 int frameworkFormat) {
465 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
466}
467
468DataspaceFlags Camera3Device::mapToHidlDataspace(
469 android_dataspace dataSpace) {
470 return dataSpace;
471}
472
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700473BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700474 uint32_t usage) {
475 return usage;
476}
477
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800478StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
479 switch (rotation) {
480 case CAMERA3_STREAM_ROTATION_0:
481 return StreamRotation::ROTATION_0;
482 case CAMERA3_STREAM_ROTATION_90:
483 return StreamRotation::ROTATION_90;
484 case CAMERA3_STREAM_ROTATION_180:
485 return StreamRotation::ROTATION_180;
486 case CAMERA3_STREAM_ROTATION_270:
487 return StreamRotation::ROTATION_270;
488 }
489 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
490 return StreamRotation::ROTATION_0;
491}
492
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800493status_t Camera3Device::mapToStreamConfigurationMode(
494 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
495 if (mode == nullptr) return BAD_VALUE;
496 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
497 switch(operationMode) {
498 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
499 *mode = StreamConfigurationMode::NORMAL_MODE;
500 break;
501 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
502 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
503 break;
504 default:
505 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
506 return BAD_VALUE;
507 }
508 } else {
509 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800510 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800511 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512}
513
514camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
515 switch (status) {
516 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
517 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
518 }
519 return CAMERA3_BUFFER_STATUS_ERROR;
520}
521
522int Camera3Device::mapToFrameworkFormat(
523 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
524 return static_cast<uint32_t>(pixelFormat);
525}
526
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700527uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700528 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700529 return usage;
530}
531
532uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700533 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700534 return usage;
535}
536
Zhijun Hef7da0962014-04-24 13:27:56 -0700537ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700538 // Get max jpeg size (area-wise).
539 Size maxJpegResolution = getMaxJpegResolution();
540 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800541 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
542 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700543 return BAD_VALUE;
544 }
545
Zhijun Hef7da0962014-04-24 13:27:56 -0700546 // Get max jpeg buffer size
547 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700548 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
549 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
551 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700552 return BAD_VALUE;
553 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700554 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800555 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700556
557 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700558 float scaleFactor = ((float) (width * height)) /
559 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800560 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
561 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700562 if (jpegBufferSize > maxJpegBufferSize) {
563 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700564 }
565
566 return jpegBufferSize;
567}
568
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700569ssize_t Camera3Device::getPointCloudBufferSize() const {
570 const int FLOATS_PER_POINT=4;
571 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
572 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800573 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
574 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700575 return BAD_VALUE;
576 }
577 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
578 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
579 return maxBytesForPointCloud;
580}
581
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800582ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800583 const int PER_CONFIGURATION_SIZE = 3;
584 const int WIDTH_OFFSET = 0;
585 const int HEIGHT_OFFSET = 1;
586 const int SIZE_OFFSET = 2;
587 camera_metadata_ro_entry rawOpaqueSizes =
588 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800589 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800590 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
592 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800593 return BAD_VALUE;
594 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700595
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800596 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
597 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
598 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
599 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
600 }
601 }
602
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
604 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800605 return BAD_VALUE;
606}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700607
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800608status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
609 ATRACE_CALL();
610 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700611
612 // Try to lock, but continue in case of failure (to avoid blocking in
613 // deadlocks)
614 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
615 bool gotLock = tryLockSpinRightRound(mLock);
616
617 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
619 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700620 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
622 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700623
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700625
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700627 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800628 int n = args.size();
629 for (int i = 0; i < n; i++) {
630 if (args[i] == templatesOption) {
631 dumpTemplates = true;
632 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700633 if (args[i] == monitorOption) {
634 if (i + 1 < n) {
635 String8 monitorTags = String8(args[i + 1]);
636 if (monitorTags == "off") {
637 mTagMonitor.disableMonitoring();
638 } else {
639 mTagMonitor.parseTagsToMonitor(monitorTags);
640 }
641 } else {
642 mTagMonitor.disableMonitoring();
643 }
644 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800645 }
646
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800648
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800649 const char *status =
650 mStatus == STATUS_ERROR ? "ERROR" :
651 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700652 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
653 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 mStatus == STATUS_ACTIVE ? "ACTIVE" :
655 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700656
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700658 if (mStatus == STATUS_ERROR) {
659 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
660 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800661 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800662 const char *mode =
663 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
664 mOperatingMode == static_cast<int>(
665 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
666 "CUSTOM";
667 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668
669 if (mInputStream != NULL) {
670 write(fd, lines.string(), lines.size());
671 mInputStream->dump(fd, args);
672 } else {
673 lines.appendFormat(" No input stream.\n");
674 write(fd, lines.string(), lines.size());
675 }
676 for (size_t i = 0; i < mOutputStreams.size(); i++) {
677 mOutputStreams[i]->dump(fd,args);
678 }
679
Zhijun He431503c2016-03-07 17:30:16 -0800680 if (mBufferManager != NULL) {
681 lines = String8(" Camera3 Buffer Manager:\n");
682 write(fd, lines.string(), lines.size());
683 mBufferManager->dump(fd, args);
684 }
Zhijun He125684a2015-12-26 15:07:30 -0800685
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700686 lines = String8(" In-flight requests:\n");
687 if (mInFlightMap.size() == 0) {
688 lines.append(" None\n");
689 } else {
690 for (size_t i = 0; i < mInFlightMap.size(); i++) {
691 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700692 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700693 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800694 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700695 r.numBuffersLeft);
696 }
697 }
698 write(fd, lines.string(), lines.size());
699
Igor Murashkin1e479c02013-09-06 16:55:14 -0700700 {
701 lines = String8(" Last request sent:\n");
702 write(fd, lines.string(), lines.size());
703
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700704 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700705 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
706 }
707
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800708 if (dumpTemplates) {
709 const char *templateNames[] = {
710 "TEMPLATE_PREVIEW",
711 "TEMPLATE_STILL_CAPTURE",
712 "TEMPLATE_VIDEO_RECORD",
713 "TEMPLATE_VIDEO_SNAPSHOT",
714 "TEMPLATE_ZERO_SHUTTER_LAG",
715 "TEMPLATE_MANUAL"
716 };
717
718 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800719 camera_metadata_t *templateRequest = nullptr;
720 mInterface->constructDefaultRequestSettings(
721 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800723 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800724 lines.append(" Not supported\n");
725 write(fd, lines.string(), lines.size());
726 } else {
727 write(fd, lines.string(), lines.size());
728 dump_indented_camera_metadata(templateRequest,
729 fd, /*verbosity*/2, /*indentation*/8);
730 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800731 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800732 }
733 }
734
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700735 mTagMonitor.dumpMonitoredMetadata(fd);
736
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800737 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800738 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800739 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800740 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800742
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700743 if (gotLock) mLock.unlock();
744 if (gotInterfaceLock) mInterfaceLock.unlock();
745
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800746 return OK;
747}
748
749const CameraMetadata& Camera3Device::info() const {
750 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
752 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700753 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 mStatus == STATUS_ERROR ?
755 "when in error state" : "before init");
756 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757 return mDeviceInfo;
758}
759
Jianing Wei90e59c92014-03-12 18:29:36 -0700760status_t Camera3Device::checkStatusOkToCaptureLocked() {
761 switch (mStatus) {
762 case STATUS_ERROR:
763 CLOGE("Device has encountered a serious error");
764 return INVALID_OPERATION;
765 case STATUS_UNINITIALIZED:
766 CLOGE("Device not initialized");
767 return INVALID_OPERATION;
768 case STATUS_UNCONFIGURED:
769 case STATUS_CONFIGURED:
770 case STATUS_ACTIVE:
771 // OK
772 break;
773 default:
774 SET_ERR_L("Unexpected status: %d", mStatus);
775 return INVALID_OPERATION;
776 }
777 return OK;
778}
779
780status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700781 const List<const CameraMetadata> &metadataList,
782 const std::list<const SurfaceMap> &surfaceMaps,
783 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700784 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700785 if (requestList == NULL) {
786 CLOGE("requestList cannot be NULL.");
787 return BAD_VALUE;
788 }
789
Jianing Weicb0652e2014-03-12 18:29:36 -0700790 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700791 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
792 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
793 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
794 ++metadataIt, ++surfaceMapIt) {
795 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700796 if (newRequest == 0) {
797 CLOGE("Can't create capture request");
798 return BAD_VALUE;
799 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700800
Shuzhen Wang9d066012016-09-30 11:30:20 -0700801 newRequest->mRepeating = repeating;
802
Jianing Weicb0652e2014-03-12 18:29:36 -0700803 // Setup burst Id and request Id
804 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700805 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
806 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700807 CLOGE("RequestID entry exists; but must not be empty in metadata");
808 return BAD_VALUE;
809 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700810 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700811 } else {
812 CLOGE("RequestID does not exist in metadata");
813 return BAD_VALUE;
814 }
815
Jianing Wei90e59c92014-03-12 18:29:36 -0700816 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700817
818 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700819 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
821 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
822 return BAD_VALUE;
823 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700824
825 // Setup batch size if this is a high speed video recording request.
826 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
827 auto firstRequest = requestList->begin();
828 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
829 if (outputStream->isVideoStream()) {
830 (*firstRequest)->mBatchSize = requestList->size();
831 break;
832 }
833 }
834 }
835
Jianing Wei90e59c92014-03-12 18:29:36 -0700836 return OK;
837}
838
Jianing Weicb0652e2014-03-12 18:29:36 -0700839status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800840 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800841
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700842 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700843 std::list<const SurfaceMap> surfaceMaps;
844 convertToRequestList(requests, surfaceMaps, request);
845
846 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
847}
848
849void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
850 std::list<const SurfaceMap>& surfaceMaps,
851 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700852 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700853
854 SurfaceMap surfaceMap;
855 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
856 // With no surface list passed in, stream and surface will have 1-to-1
857 // mapping. So the surface index is 0 for each stream in the surfaceMap.
858 for (size_t i = 0; i < streams.count; i++) {
859 surfaceMap[streams.data.i32[i]].push_back(0);
860 }
861 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800862}
863
Jianing Wei90e59c92014-03-12 18:29:36 -0700864status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700865 const List<const CameraMetadata> &requests,
866 const std::list<const SurfaceMap> &surfaceMaps,
867 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700868 /*out*/
869 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 ATRACE_CALL();
871 Mutex::Autolock il(mInterfaceLock);
872 Mutex::Autolock l(mLock);
873
874 status_t res = checkStatusOkToCaptureLocked();
875 if (res != OK) {
876 // error logged by previous call
877 return res;
878 }
879
880 RequestList requestList;
881
Shuzhen Wang0129d522016-10-30 22:43:41 -0700882 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
883 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 if (res != OK) {
885 // error logged by previous call
886 return res;
887 }
888
889 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700890 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700891 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700892 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700893 }
894
895 if (res == OK) {
896 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
897 if (res != OK) {
898 SET_ERR_L("Can't transition to active in %f seconds!",
899 kActiveTimeout/1e9);
900 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800901 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700902 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 } else {
904 CLOGE("Cannot queue request. Impossible.");
905 return BAD_VALUE;
906 }
907
908 return res;
909}
910
Yifan Honga640c5a2017-04-12 16:30:31 -0700911// Only one processCaptureResult should be called at a time, so
912// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800913hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800914 const hardware::hidl_vec<
915 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700916
917 if (mProcessCaptureResultLock.tryLock() != OK) {
918 // This should never happen; it indicates a wrong client implementation
919 // that doesn't follow the contract. But, we can be tolerant here.
920 ALOGE("%s: callback overlapped! waiting 1s...",
921 __FUNCTION__);
922 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
923 ALOGE("%s: cannot acquire lock in 1s, dropping results",
924 __FUNCTION__);
925 // really don't know what to do, so bail out.
926 return hardware::Void();
927 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800928 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700929 for (const auto& result : results) {
930 processOneCaptureResultLocked(result);
931 }
932 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800933 return hardware::Void();
934}
935
Yifan Honga640c5a2017-04-12 16:30:31 -0700936void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800937 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800938 camera3_capture_result r;
939 status_t res;
940 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700941
942 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
943 if (result.fmqResultSize > 0) {
944 resultMetadata.resize(result.fmqResultSize);
945 if (mResultMetadataQueue == nullptr) {
946 return; // logged in initialize()
947 }
948 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
949 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
950 __FUNCTION__, result.frameNumber, result.fmqResultSize);
951 return;
952 }
953 } else {
954 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
955 result.result.size());
956 }
957
958 if (resultMetadata.size() != 0) {
959 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
960 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800961 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
962 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
963 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800964 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800965 }
966 } else {
967 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800968 }
969
970 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
971 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
972 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
973 auto& bDst = outputBuffers[i];
974 const StreamBuffer &bSrc = result.outputBuffers[i];
975
976 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100977 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800978 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
979 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800980 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 }
982 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
983
984 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800985 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 if (res != OK) {
987 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
988 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800989 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 }
991 bDst.buffer = buffer;
992 bDst.status = mapHidlBufferStatus(bSrc.status);
993 bDst.acquire_fence = -1;
994 if (bSrc.releaseFence == nullptr) {
995 bDst.release_fence = -1;
996 } else if (bSrc.releaseFence->numFds == 1) {
997 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
998 } else {
999 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1000 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001001 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001002 }
1003 }
1004 r.num_output_buffers = outputBuffers.size();
1005 r.output_buffers = outputBuffers.data();
1006
1007 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001008 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001009 r.input_buffer = nullptr;
1010 } else {
1011 if (mInputStream->getId() != result.inputBuffer.streamId) {
1012 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1013 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001014 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001015 }
1016 inputBuffer.stream = mInputStream->asHalStream();
1017 buffer_handle_t *buffer;
1018 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1019 &buffer);
1020 if (res != OK) {
1021 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1022 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001023 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001024 }
1025 inputBuffer.buffer = buffer;
1026 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1027 inputBuffer.acquire_fence = -1;
1028 if (result.inputBuffer.releaseFence == nullptr) {
1029 inputBuffer.release_fence = -1;
1030 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1031 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1032 } else {
1033 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1034 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001035 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001036 }
1037 r.input_buffer = &inputBuffer;
1038 }
1039
1040 r.partial_result = result.partialResult;
1041
1042 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001043}
1044
1045hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001046 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1047 for (const auto& msg : msgs) {
1048 notify(msg);
1049 }
1050 return hardware::Void();
1051}
1052
1053void Camera3Device::notify(
1054 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1055
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001056 camera3_notify_msg m;
1057 switch (msg.type) {
1058 case MsgType::ERROR:
1059 m.type = CAMERA3_MSG_ERROR;
1060 m.message.error.frame_number = msg.msg.error.frameNumber;
1061 if (msg.msg.error.errorStreamId >= 0) {
1062 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001063 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001064 ALOGE("%s: Frame %d: Invalid error stream id %d",
1065 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001066 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001067 }
1068 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1069 } else {
1070 m.message.error.error_stream = nullptr;
1071 }
1072 switch (msg.msg.error.errorCode) {
1073 case ErrorCode::ERROR_DEVICE:
1074 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1075 break;
1076 case ErrorCode::ERROR_REQUEST:
1077 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1078 break;
1079 case ErrorCode::ERROR_RESULT:
1080 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1081 break;
1082 case ErrorCode::ERROR_BUFFER:
1083 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1084 break;
1085 }
1086 break;
1087 case MsgType::SHUTTER:
1088 m.type = CAMERA3_MSG_SHUTTER;
1089 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1090 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1091 break;
1092 }
1093 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001094}
1095
Jianing Weicb0652e2014-03-12 18:29:36 -07001096status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001097 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001098 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001099 ATRACE_CALL();
1100
Shuzhen Wang0129d522016-10-30 22:43:41 -07001101 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001102}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001103
Jianing Weicb0652e2014-03-12 18:29:36 -07001104status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1105 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001106 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001107
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001108 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001109 std::list<const SurfaceMap> surfaceMaps;
1110 convertToRequestList(requests, surfaceMaps, request);
1111
1112 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1113 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001114}
1115
Jianing Weicb0652e2014-03-12 18:29:36 -07001116status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001117 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001118 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001119 ATRACE_CALL();
1120
Shuzhen Wang0129d522016-10-30 22:43:41 -07001121 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001122}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001123
1124sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001125 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 status_t res;
1127
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001128 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001129 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1130 // so unilaterally select normal operating mode.
1131 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001132 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001133 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001134 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001135 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001136 } else if (mStatus == STATUS_UNCONFIGURED) {
1137 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001138 CLOGE("No streams configured");
1139 return NULL;
1140 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001141 }
1142
Shuzhen Wang0129d522016-10-30 22:43:41 -07001143 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001144 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001145}
1146
Jianing Weicb0652e2014-03-12 18:29:36 -07001147status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001148 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001149 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001150 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 switch (mStatus) {
1153 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001154 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001155 return INVALID_OPERATION;
1156 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001157 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001159 case STATUS_UNCONFIGURED:
1160 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001161 case STATUS_ACTIVE:
1162 // OK
1163 break;
1164 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001165 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001166 return INVALID_OPERATION;
1167 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001168 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001169
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001170 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001171}
1172
1173status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1174 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001175 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001177 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001178}
1179
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180status_t Camera3Device::createInputStream(
1181 uint32_t width, uint32_t height, int format, int *id) {
1182 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001183 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001184 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001185 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1186 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001187
1188 status_t res;
1189 bool wasActive = false;
1190
1191 switch (mStatus) {
1192 case STATUS_ERROR:
1193 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1194 return INVALID_OPERATION;
1195 case STATUS_UNINITIALIZED:
1196 ALOGE("%s: Device not initialized", __FUNCTION__);
1197 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001198 case STATUS_UNCONFIGURED:
1199 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001200 // OK
1201 break;
1202 case STATUS_ACTIVE:
1203 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001205 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001207 return res;
1208 }
1209 wasActive = true;
1210 break;
1211 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001213 return INVALID_OPERATION;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001216
1217 if (mInputStream != 0) {
1218 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1219 return INVALID_OPERATION;
1220 }
1221
1222 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1223 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001225
1226 mInputStream = newStream;
1227
1228 *id = mNextStreamId++;
1229
1230 // Continue captures if active at start
1231 if (wasActive) {
1232 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001233 // Reuse current operating mode for new stream config
1234 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001235 if (res != OK) {
1236 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1237 __FUNCTION__, mNextStreamId, strerror(-res), res);
1238 return res;
1239 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001240 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001241 }
1242
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001243 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001244 return OK;
1245}
1246
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001247status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001248 uint32_t width, uint32_t height, int format,
1249 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001250 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001251 ATRACE_CALL();
1252
1253 if (consumer == nullptr) {
1254 ALOGE("%s: consumer must not be null", __FUNCTION__);
1255 return BAD_VALUE;
1256 }
1257
1258 std::vector<sp<Surface>> consumers;
1259 consumers.push_back(consumer);
1260
1261 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001262 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001263}
1264
1265status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1266 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1267 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001268 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001269 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001272 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001273 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1274 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 status_t res;
1277 bool wasActive = false;
1278
1279 switch (mStatus) {
1280 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001281 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 return INVALID_OPERATION;
1283 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001284 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 case STATUS_UNCONFIGURED:
1287 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 // OK
1289 break;
1290 case STATUS_ACTIVE:
1291 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001294 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001295 return res;
1296 }
1297 wasActive = true;
1298 break;
1299 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001300 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301 return INVALID_OPERATION;
1302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304
1305 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001306
Shuzhen Wang0129d522016-10-30 22:43:41 -07001307 if (consumers.size() == 0 && !hasDeferredConsumer) {
1308 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1309 return BAD_VALUE;
1310 }
Zhijun He5d677d12016-05-29 16:52:39 -07001311
Shuzhen Wang0129d522016-10-30 22:43:41 -07001312 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001313 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1314 return BAD_VALUE;
1315 }
1316
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001318 ssize_t blobBufferSize;
1319 if (dataSpace != HAL_DATASPACE_DEPTH) {
1320 blobBufferSize = getJpegBufferSize(width, height);
1321 if (blobBufferSize <= 0) {
1322 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1323 return BAD_VALUE;
1324 }
1325 } else {
1326 blobBufferSize = getPointCloudBufferSize();
1327 if (blobBufferSize <= 0) {
1328 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1329 return BAD_VALUE;
1330 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001331 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001332 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001333 width, height, blobBufferSize, format, dataSpace, rotation,
1334 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001335 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1336 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1337 if (rawOpaqueBufferSize <= 0) {
1338 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1339 return BAD_VALUE;
1340 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001342 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1343 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001344 } else if (isShared) {
1345 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1346 width, height, format, consumerUsage, dataSpace, rotation,
1347 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001348 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001349 newStream = new Camera3OutputStream(mNextStreamId,
1350 width, height, format, consumerUsage, dataSpace, rotation,
1351 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001353 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001354 width, height, format, dataSpace, rotation,
1355 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001358
Emilian Peev08dd2452017-04-06 16:55:14 +01001359 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361 res = mOutputStreams.add(mNextStreamId, newStream);
1362 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001363 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return res;
1365 }
1366
1367 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001368 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369
1370 // Continue captures if active at start
1371 if (wasActive) {
1372 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001373 // Reuse current operating mode for new stream config
1374 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001376 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1377 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 return res;
1379 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001380 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001384}
1385
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001386status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001387 uint32_t *width, uint32_t *height,
1388 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001389 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001390 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001392
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 switch (mStatus) {
1394 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001395 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 return INVALID_OPERATION;
1397 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001398 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001400 case STATUS_UNCONFIGURED:
1401 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 case STATUS_ACTIVE:
1403 // OK
1404 break;
1405 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001406 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407 return INVALID_OPERATION;
1408 }
1409
1410 ssize_t idx = mOutputStreams.indexOfKey(id);
1411 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return idx;
1414 }
1415
1416 if (width) *width = mOutputStreams[idx]->getWidth();
1417 if (height) *height = mOutputStreams[idx]->getHeight();
1418 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001419 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421}
1422
1423status_t Camera3Device::setStreamTransform(int id,
1424 int transform) {
1425 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001426 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001427 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001428
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 switch (mStatus) {
1430 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001431 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 return INVALID_OPERATION;
1433 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001434 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001436 case STATUS_UNCONFIGURED:
1437 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 case STATUS_ACTIVE:
1439 // OK
1440 break;
1441 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001442 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001443 return INVALID_OPERATION;
1444 }
1445
1446 ssize_t idx = mOutputStreams.indexOfKey(id);
1447 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001448 CLOGE("Stream %d does not exist",
1449 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 return BAD_VALUE;
1451 }
1452
1453 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454}
1455
1456status_t Camera3Device::deleteStream(int id) {
1457 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001458 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 Mutex::Autolock l(mLock);
1460 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001461
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001462 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001463
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 // CameraDevice semantics require device to already be idle before
1465 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001466 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001467 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001468 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 }
1470
Igor Murashkin2fba5842013-04-22 14:03:54 -07001471 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001472 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 if (mInputStream != NULL && id == mInputStream->getId()) {
1474 deletedStream = mInputStream;
1475 mInputStream.clear();
1476 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001477 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001478 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 return BAD_VALUE;
1480 }
Zhijun He5f446352014-01-22 09:49:33 -08001481 }
1482
1483 // Delete output stream or the output part of a bi-directional stream.
1484 if (outputStreamIdx != NAME_NOT_FOUND) {
1485 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 mOutputStreams.removeItem(id);
1487 }
1488
1489 // Free up the stream endpoint so that it can be used by some other stream
1490 res = deletedStream->disconnect();
1491 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001492 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 // fall through since we want to still list the stream as deleted.
1494 }
1495 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001496 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497
1498 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499}
1500
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001501status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001502 ATRACE_CALL();
1503 ALOGV("%s: E", __FUNCTION__);
1504
1505 Mutex::Autolock il(mInterfaceLock);
1506 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001507
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001508 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001509}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001510
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001511status_t Camera3Device::getInputBufferProducer(
1512 sp<IGraphicBufferProducer> *producer) {
1513 Mutex::Autolock il(mInterfaceLock);
1514 Mutex::Autolock l(mLock);
1515
1516 if (producer == NULL) {
1517 return BAD_VALUE;
1518 } else if (mInputStream == NULL) {
1519 return INVALID_OPERATION;
1520 }
1521
1522 return mInputStream->getInputBufferProducer(producer);
1523}
1524
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001525status_t Camera3Device::createDefaultRequest(int templateId,
1526 CameraMetadata *request) {
1527 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001528 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001529
1530 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1531 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1532 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1533 return BAD_VALUE;
1534 }
1535
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 Mutex::Autolock l(mLock);
1538
1539 switch (mStatus) {
1540 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001541 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return INVALID_OPERATION;
1543 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001544 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 case STATUS_UNCONFIGURED:
1547 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 case STATUS_ACTIVE:
1549 // OK
1550 break;
1551 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001552 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 return INVALID_OPERATION;
1554 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555
Zhijun Hea1530f12014-09-14 12:44:20 -07001556 if (!mRequestTemplateCache[templateId].isEmpty()) {
1557 *request = mRequestTemplateCache[templateId];
1558 return OK;
1559 }
1560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001561 camera_metadata_t *rawRequest;
1562 status_t res = mInterface->constructDefaultRequestSettings(
1563 (camera3_request_template_t) templateId, &rawRequest);
1564 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001565 ALOGI("%s: template %d is not supported on this camera device",
1566 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001567 return res;
1568 } else if (res != OK) {
1569 CLOGE("Unable to construct request template %d: %s (%d)",
1570 templateId, strerror(-res), res);
1571 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001572 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001573
Emilian Peev71c73a22017-03-21 16:35:51 +00001574 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001575 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001577 // Derive some new keys for backward compatibility
1578 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1579 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1580 int32_t defaultBoost[1] = {100};
1581 mRequestTemplateCache[templateId].update(
1582 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1583 defaultBoost, 1);
1584 }
1585
1586 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587 return OK;
1588}
1589
1590status_t Camera3Device::waitUntilDrained() {
1591 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594
Zhijun He69a37482014-03-23 18:44:49 -07001595 return waitUntilDrainedLocked();
1596}
1597
1598status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 switch (mStatus) {
1600 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001601 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 ALOGV("%s: Already idle", __FUNCTION__);
1603 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 case STATUS_CONFIGURED:
1605 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 case STATUS_ERROR:
1607 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 break;
1610 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001611 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001612 return INVALID_OPERATION;
1613 }
1614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001615 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001617 if (res != OK) {
1618 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1619 res);
1620 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 return res;
1622}
1623
Ruben Brunk183f0562015-08-12 12:55:02 -07001624
1625void Camera3Device::internalUpdateStatusLocked(Status status) {
1626 mStatus = status;
1627 mRecentStatusUpdates.add(mStatus);
1628 mStatusChanged.broadcast();
1629}
1630
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631// Pause to reconfigure
1632status_t Camera3Device::internalPauseAndWaitLocked() {
1633 mRequestThread->setPaused(true);
1634 mPauseStateNotify = true;
1635
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001636 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1638 if (res != OK) {
1639 SET_ERR_L("Can't idle device in %f seconds!",
1640 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 }
1642
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001643 return res;
1644}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001645
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001646// Resume after internalPauseAndWaitLocked
1647status_t Camera3Device::internalResumeLocked() {
1648 status_t res;
1649
1650 mRequestThread->setPaused(false);
1651
1652 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1653 if (res != OK) {
1654 SET_ERR_L("Can't transition to active in %f seconds!",
1655 kActiveTimeout/1e9);
1656 }
1657 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001658 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659}
1660
Ruben Brunk183f0562015-08-12 12:55:02 -07001661status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001662 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001663
1664 size_t startIndex = 0;
1665 if (mStatusWaiters == 0) {
1666 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1667 // this status list
1668 mRecentStatusUpdates.clear();
1669 } else {
1670 // If other threads are waiting on updates to this status list, set the position of the
1671 // first element that this list will check rather than clearing the list.
1672 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 }
1674
Ruben Brunk183f0562015-08-12 12:55:02 -07001675 mStatusWaiters++;
1676
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001677 bool stateSeen = false;
1678 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001679 if (active == (mStatus == STATUS_ACTIVE)) {
1680 // Desired state is current
1681 break;
1682 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683
1684 res = mStatusChanged.waitRelative(mLock, timeout);
1685 if (res != OK) break;
1686
Ruben Brunk183f0562015-08-12 12:55:02 -07001687 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1688 // transitions.
1689 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1690 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1691 __FUNCTION__);
1692
1693 // Encountered desired state since we began waiting
1694 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1696 stateSeen = true;
1697 break;
1698 }
1699 }
1700 } while (!stateSeen);
1701
Ruben Brunk183f0562015-08-12 12:55:02 -07001702 mStatusWaiters--;
1703
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704 return res;
1705}
1706
1707
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001708status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001709 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001710 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001711
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001712 if (listener != NULL && mListener != NULL) {
1713 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1714 }
1715 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001716 mRequestThread->setNotificationListener(listener);
1717 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001718
1719 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720}
1721
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001722bool Camera3Device::willNotify3A() {
1723 return false;
1724}
1725
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001726status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001727 status_t res;
1728 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001730 while (mResultQueue.empty()) {
1731 res = mResultSignal.waitRelative(mOutputLock, timeout);
1732 if (res == TIMED_OUT) {
1733 return res;
1734 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001735 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1736 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001737 return res;
1738 }
1739 }
1740 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741}
1742
Jianing Weicb0652e2014-03-12 18:29:36 -07001743status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001745 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001747 if (mResultQueue.empty()) {
1748 return NOT_ENOUGH_DATA;
1749 }
1750
Jianing Weicb0652e2014-03-12 18:29:36 -07001751 if (frame == NULL) {
1752 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1753 return BAD_VALUE;
1754 }
1755
1756 CaptureResult &result = *(mResultQueue.begin());
1757 frame->mResultExtras = result.mResultExtras;
1758 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001759 mResultQueue.erase(mResultQueue.begin());
1760
1761 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762}
1763
1764status_t Camera3Device::triggerAutofocus(uint32_t id) {
1765 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001766 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001768 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1769 // Mix-in this trigger into the next request and only the next request.
1770 RequestTrigger trigger[] = {
1771 {
1772 ANDROID_CONTROL_AF_TRIGGER,
1773 ANDROID_CONTROL_AF_TRIGGER_START
1774 },
1775 {
1776 ANDROID_CONTROL_AF_TRIGGER_ID,
1777 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001778 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001779 };
1780
1781 return mRequestThread->queueTrigger(trigger,
1782 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783}
1784
1785status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1786 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001788
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001789 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1790 // Mix-in this trigger into the next request and only the next request.
1791 RequestTrigger trigger[] = {
1792 {
1793 ANDROID_CONTROL_AF_TRIGGER,
1794 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1795 },
1796 {
1797 ANDROID_CONTROL_AF_TRIGGER_ID,
1798 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001799 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001800 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001801
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001802 return mRequestThread->queueTrigger(trigger,
1803 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001804}
1805
1806status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1807 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001810 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1811 // Mix-in this trigger into the next request and only the next request.
1812 RequestTrigger trigger[] = {
1813 {
1814 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1815 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1816 },
1817 {
1818 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1819 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001820 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001821 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001822
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 return mRequestThread->queueTrigger(trigger,
1824 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825}
1826
Jianing Weicb0652e2014-03-12 18:29:36 -07001827status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001828 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001829 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001830 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001831
Zhijun He7ef20392014-04-21 16:04:17 -07001832 {
1833 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001834 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001835 }
1836
Emilian Peev08dd2452017-04-06 16:55:14 +01001837 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001838}
1839
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001840status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001841 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1842}
1843
1844status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001845 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001846 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001847 Mutex::Autolock il(mInterfaceLock);
1848 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001849
1850 sp<Camera3StreamInterface> stream;
1851 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1852 if (outputStreamIdx == NAME_NOT_FOUND) {
1853 CLOGE("Stream %d does not exist", streamId);
1854 return BAD_VALUE;
1855 }
1856
1857 stream = mOutputStreams.editValueAt(outputStreamIdx);
1858
1859 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001860 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001861 return BAD_VALUE;
1862 }
1863
1864 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001865 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001866 return BAD_VALUE;
1867 }
1868
Ruben Brunkc78ac262015-08-13 17:58:46 -07001869 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001870}
1871
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001872status_t Camera3Device::tearDown(int streamId) {
1873 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001874 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001875 Mutex::Autolock il(mInterfaceLock);
1876 Mutex::Autolock l(mLock);
1877
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001878 sp<Camera3StreamInterface> stream;
1879 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1880 if (outputStreamIdx == NAME_NOT_FOUND) {
1881 CLOGE("Stream %d does not exist", streamId);
1882 return BAD_VALUE;
1883 }
1884
1885 stream = mOutputStreams.editValueAt(outputStreamIdx);
1886
1887 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1888 CLOGE("Stream %d is a target of a in-progress request", streamId);
1889 return BAD_VALUE;
1890 }
1891
1892 return stream->tearDown();
1893}
1894
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001895status_t Camera3Device::addBufferListenerForStream(int streamId,
1896 wp<Camera3StreamBufferListener> listener) {
1897 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001898 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001899 Mutex::Autolock il(mInterfaceLock);
1900 Mutex::Autolock l(mLock);
1901
1902 sp<Camera3StreamInterface> stream;
1903 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1904 if (outputStreamIdx == NAME_NOT_FOUND) {
1905 CLOGE("Stream %d does not exist", streamId);
1906 return BAD_VALUE;
1907 }
1908
1909 stream = mOutputStreams.editValueAt(outputStreamIdx);
1910 stream->addBufferListener(listener);
1911
1912 return OK;
1913}
1914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001916 * Methods called by subclasses
1917 */
1918
1919void Camera3Device::notifyStatus(bool idle) {
1920 {
1921 // Need mLock to safely update state and synchronize to current
1922 // state of methods in flight.
1923 Mutex::Autolock l(mLock);
1924 // We can get various system-idle notices from the status tracker
1925 // while starting up. Only care about them if we've actually sent
1926 // in some requests recently.
1927 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1928 return;
1929 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001930 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001931 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001932 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933
1934 // Skip notifying listener if we're doing some user-transparent
1935 // state changes
1936 if (mPauseStateNotify) return;
1937 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001938
1939 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001940 {
1941 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001942 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001943 }
1944 if (idle && listener != NULL) {
1945 listener->notifyIdle();
1946 }
1947}
1948
Shuzhen Wang758c2152017-01-10 18:26:18 -08001949status_t Camera3Device::setConsumerSurfaces(int streamId,
1950 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001951 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001952 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1953 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001954 Mutex::Autolock il(mInterfaceLock);
1955 Mutex::Autolock l(mLock);
1956
Shuzhen Wang758c2152017-01-10 18:26:18 -08001957 if (consumers.size() == 0) {
1958 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001959 return BAD_VALUE;
1960 }
1961
1962 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1963 if (idx == NAME_NOT_FOUND) {
1964 CLOGE("Stream %d is unknown", streamId);
1965 return idx;
1966 }
1967 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001968 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001969 if (res != OK) {
1970 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1971 return res;
1972 }
1973
Shuzhen Wang0129d522016-10-30 22:43:41 -07001974 if (stream->isConsumerConfigurationDeferred()) {
1975 if (!stream->isConfiguring()) {
1976 CLOGE("Stream %d was already fully configured.", streamId);
1977 return INVALID_OPERATION;
1978 }
Zhijun He5d677d12016-05-29 16:52:39 -07001979
Shuzhen Wang0129d522016-10-30 22:43:41 -07001980 res = stream->finishConfiguration();
1981 if (res != OK) {
1982 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1983 stream->getId(), strerror(-res), res);
1984 return res;
1985 }
Zhijun He5d677d12016-05-29 16:52:39 -07001986 }
1987
1988 return OK;
1989}
1990
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001991/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992 * Camera3Device private methods
1993 */
1994
1995sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001996 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001997 ATRACE_CALL();
1998 status_t res;
1999
2000 sp<CaptureRequest> newRequest = new CaptureRequest;
2001 newRequest->mSettings = request;
2002
2003 camera_metadata_entry_t inputStreams =
2004 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2005 if (inputStreams.count > 0) {
2006 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002007 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002008 CLOGE("Request references unknown input stream %d",
2009 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002010 return NULL;
2011 }
2012 // Lazy completion of stream configuration (allocation/registration)
2013 // on first use
2014 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002015 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002017 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002018 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002019 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002020 return NULL;
2021 }
2022 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 // Check if stream is being prepared
2024 if (mInputStream->isPreparing()) {
2025 CLOGE("Request references an input stream that's being prepared!");
2026 return NULL;
2027 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002028
2029 newRequest->mInputStream = mInputStream;
2030 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2031 }
2032
2033 camera_metadata_entry_t streams =
2034 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2035 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002036 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037 return NULL;
2038 }
2039
2040 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002041 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002042 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002043 CLOGE("Request references unknown stream %d",
2044 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002045 return NULL;
2046 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002047 sp<Camera3OutputStreamInterface> stream =
2048 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049
Zhijun He5d677d12016-05-29 16:52:39 -07002050 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002051 auto iter = surfaceMap.find(streams.data.i32[i]);
2052 if (iter != surfaceMap.end()) {
2053 const std::vector<size_t>& surfaces = iter->second;
2054 for (const auto& surface : surfaces) {
2055 if (stream->isConsumerConfigurationDeferred(surface)) {
2056 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2057 "due to deferred consumer", stream->getId(), surface);
2058 return NULL;
2059 }
2060 }
2061 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002062 }
2063
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 // Lazy completion of stream configuration (allocation/registration)
2065 // on first use
2066 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002067 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002068 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002069 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2070 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return NULL;
2072 }
2073 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002074 // Check if stream is being prepared
2075 if (stream->isPreparing()) {
2076 CLOGE("Request references an output stream that's being prepared!");
2077 return NULL;
2078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079
2080 newRequest->mOutputStreams.push(stream);
2081 }
2082 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002083 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084
2085 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002086}
2087
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002088bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2089 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2090 Size size = mSupportedOpaqueInputSizes[i];
2091 if (size.width == width && size.height == height) {
2092 return true;
2093 }
2094 }
2095
2096 return false;
2097}
2098
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002099void Camera3Device::cancelStreamsConfigurationLocked() {
2100 int res = OK;
2101 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2102 res = mInputStream->cancelConfiguration();
2103 if (res != OK) {
2104 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2105 mInputStream->getId(), strerror(-res), res);
2106 }
2107 }
2108
2109 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2110 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2111 if (outputStream->isConfiguring()) {
2112 res = outputStream->cancelConfiguration();
2113 if (res != OK) {
2114 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2115 outputStream->getId(), strerror(-res), res);
2116 }
2117 }
2118 }
2119
2120 // Return state to that at start of call, so that future configures
2121 // properly clean things up
2122 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2123 mNeedConfig = true;
2124}
2125
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002126status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127 ATRACE_CALL();
2128 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002129
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002130 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002131 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 return INVALID_OPERATION;
2133 }
2134
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002135 if (operatingMode < 0) {
2136 CLOGE("Invalid operating mode: %d", operatingMode);
2137 return BAD_VALUE;
2138 }
2139
2140 bool isConstrainedHighSpeed =
2141 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2142 operatingMode;
2143
2144 if (mOperatingMode != operatingMode) {
2145 mNeedConfig = true;
2146 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2147 mOperatingMode = operatingMode;
2148 }
2149
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002150 if (!mNeedConfig) {
2151 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2152 return OK;
2153 }
2154
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002155 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2156 // adding a dummy stream instead.
2157 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2158 if (mOutputStreams.size() == 0) {
2159 addDummyStreamLocked();
2160 } else {
2161 tryRemoveDummyStreamLocked();
2162 }
2163
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002165 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166
2167 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002168 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2170
2171 Vector<camera3_stream_t*> streams;
2172 streams.setCapacity(config.num_streams);
2173
2174 if (mInputStream != NULL) {
2175 camera3_stream_t *inputStream;
2176 inputStream = mInputStream->startConfiguration();
2177 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002178 CLOGE("Can't start input stream configuration");
2179 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002180 return INVALID_OPERATION;
2181 }
2182 streams.add(inputStream);
2183 }
2184
2185 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002186
2187 // Don't configure bidi streams twice, nor add them twice to the list
2188 if (mOutputStreams[i].get() ==
2189 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2190
2191 config.num_streams--;
2192 continue;
2193 }
2194
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195 camera3_stream_t *outputStream;
2196 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2197 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002198 CLOGE("Can't start output stream configuration");
2199 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200 return INVALID_OPERATION;
2201 }
2202 streams.add(outputStream);
2203 }
2204
2205 config.streams = streams.editArray();
2206
2207 // Do the HAL configuration; will potentially touch stream
2208 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002209
2210 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002211
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002212 if (res == BAD_VALUE) {
2213 // HAL rejected this set of streams as unsupported, clean up config
2214 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002215 CLOGE("Set of requested inputs/outputs not supported by HAL");
2216 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002217 return BAD_VALUE;
2218 } else if (res != OK) {
2219 // Some other kind of error from configure_streams - this is not
2220 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002221 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2222 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 return res;
2224 }
2225
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002226 // Finish all stream configuration immediately.
2227 // TODO: Try to relax this later back to lazy completion, which should be
2228 // faster
2229
Igor Murashkin073f8572013-05-02 14:59:28 -07002230 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002231 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002232 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002233 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002234 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002235 cancelStreamsConfigurationLocked();
2236 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002237 }
2238 }
2239
2240 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002241 sp<Camera3OutputStreamInterface> outputStream =
2242 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002243 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002244 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002245 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002246 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002247 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002248 cancelStreamsConfigurationLocked();
2249 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002250 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002251 }
2252 }
2253
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 // Request thread needs to know to avoid using repeat-last-settings protocol
2255 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002256 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002257
Zhijun He90f7c372016-08-16 16:19:43 -07002258 char value[PROPERTY_VALUE_MAX];
2259 property_get("camera.fifo.disable", value, "0");
2260 int32_t disableFifo = atoi(value);
2261 if (disableFifo != 1) {
2262 // Boost priority of request thread to SCHED_FIFO.
2263 pid_t requestThreadTid = mRequestThread->getTid();
2264 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002265 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002266 if (res != OK) {
2267 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2268 strerror(-res), res);
2269 } else {
2270 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2271 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002272 }
2273
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002274 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002276 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002277
Ruben Brunk183f0562015-08-12 12:55:02 -07002278 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2279 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002280
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002281 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002282
Zhijun He0a210512014-07-24 13:45:15 -07002283 // tear down the deleted streams after configure streams.
2284 mDeletedStreams.clear();
2285
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002286 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002287}
2288
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002289status_t Camera3Device::addDummyStreamLocked() {
2290 ATRACE_CALL();
2291 status_t res;
2292
2293 if (mDummyStreamId != NO_STREAM) {
2294 // Should never be adding a second dummy stream when one is already
2295 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002296 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2297 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002298 return INVALID_OPERATION;
2299 }
2300
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002301 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002302
2303 sp<Camera3OutputStreamInterface> dummyStream =
2304 new Camera3DummyStream(mNextStreamId);
2305
2306 res = mOutputStreams.add(mNextStreamId, dummyStream);
2307 if (res < 0) {
2308 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2309 return res;
2310 }
2311
2312 mDummyStreamId = mNextStreamId;
2313 mNextStreamId++;
2314
2315 return OK;
2316}
2317
2318status_t Camera3Device::tryRemoveDummyStreamLocked() {
2319 ATRACE_CALL();
2320 status_t res;
2321
2322 if (mDummyStreamId == NO_STREAM) return OK;
2323 if (mOutputStreams.size() == 1) return OK;
2324
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002325 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002326
2327 // Ok, have a dummy stream and there's at least one other output stream,
2328 // so remove the dummy
2329
2330 sp<Camera3StreamInterface> deletedStream;
2331 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2332 if (outputStreamIdx == NAME_NOT_FOUND) {
2333 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2334 return INVALID_OPERATION;
2335 }
2336
2337 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2338 mOutputStreams.removeItemsAt(outputStreamIdx);
2339
2340 // Free up the stream endpoint so that it can be used by some other stream
2341 res = deletedStream->disconnect();
2342 if (res != OK) {
2343 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2344 // fall through since we want to still list the stream as deleted.
2345 }
2346 mDeletedStreams.add(deletedStream);
2347 mDummyStreamId = NO_STREAM;
2348
2349 return res;
2350}
2351
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002352void Camera3Device::setErrorState(const char *fmt, ...) {
2353 Mutex::Autolock l(mLock);
2354 va_list args;
2355 va_start(args, fmt);
2356
2357 setErrorStateLockedV(fmt, args);
2358
2359 va_end(args);
2360}
2361
2362void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2363 Mutex::Autolock l(mLock);
2364 setErrorStateLockedV(fmt, args);
2365}
2366
2367void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2368 va_list args;
2369 va_start(args, fmt);
2370
2371 setErrorStateLockedV(fmt, args);
2372
2373 va_end(args);
2374}
2375
2376void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002377 // Print out all error messages to log
2378 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002379 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002380
2381 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002382 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002383
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002384 mErrorCause = errorCause;
2385
2386 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002387 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002388
2389 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002390 sp<NotificationListener> listener = mListener.promote();
2391 if (listener != NULL) {
2392 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002393 CaptureResultExtras());
2394 }
2395
2396 // Save stack trace. View by dumping it later.
2397 CameraTraces::saveTrace();
2398 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002399}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002400
2401/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002402 * In-flight request management
2403 */
2404
Jianing Weicb0652e2014-03-12 18:29:36 -07002405status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002406 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002407 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002408 ATRACE_CALL();
2409 Mutex::Autolock l(mInFlightLock);
2410
2411 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002412 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002413 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002414 if (res < 0) return res;
2415
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002416 if (mInFlightMap.size() == 1) {
2417 mStatusTracker->markComponentActive(mInFlightStatusId);
2418 }
2419
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002420 return OK;
2421}
2422
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002423void Camera3Device::returnOutputBuffers(
2424 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2425 nsecs_t timestamp) {
2426 for (size_t i = 0; i < numBuffers; i++)
2427 {
2428 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2429 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2430 // Note: stream may be deallocated at this point, if this buffer was
2431 // the last reference to it.
2432 if (res != OK) {
2433 ALOGE("Can't return buffer to its stream: %s (%d)",
2434 strerror(-res), res);
2435 }
2436 }
2437}
2438
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002439void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2440 mInFlightMap.removeItemsAt(idx, 1);
2441
2442 // Indicate idle inFlightMap to the status tracker
2443 if (mInFlightMap.size() == 0) {
2444 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2445 }
2446}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002447
2448void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2449
2450 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2451 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2452
2453 nsecs_t sensorTimestamp = request.sensorTimestamp;
2454 nsecs_t shutterTimestamp = request.shutterTimestamp;
2455
2456 // Check if it's okay to remove the request from InFlightMap:
2457 // In the case of a successful request:
2458 // all input and output buffers, all result metadata, shutter callback
2459 // arrived.
2460 // In the case of a unsuccessful request:
2461 // all input and output buffers arrived.
2462 if (request.numBuffersLeft == 0 &&
2463 (request.requestStatus != OK ||
2464 (request.haveResultMetadata && shutterTimestamp != 0))) {
2465 ATRACE_ASYNC_END("frame capture", frameNumber);
2466
Shuzhen Wang403044a2017-02-26 23:29:04 -08002467 // Sanity check - if sensor timestamp matches shutter timestamp in the
2468 // case of request having callback.
2469 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002470 sensorTimestamp != shutterTimestamp) {
2471 SET_ERR("sensor timestamp (%" PRId64
2472 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2473 sensorTimestamp, frameNumber, shutterTimestamp);
2474 }
2475
2476 // for an unsuccessful request, it may have pending output buffers to
2477 // return.
2478 assert(request.requestStatus != OK ||
2479 request.pendingOutputBuffers.size() == 0);
2480 returnOutputBuffers(request.pendingOutputBuffers.array(),
2481 request.pendingOutputBuffers.size(), 0);
2482
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002483 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002484 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2485 }
2486
2487 // Sanity check - if we have too many in-flight frames, something has
2488 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002489 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002490 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002491 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2492 kInFlightWarnLimitHighSpeed) {
2493 CLOGE("In-flight list too large for high speed configuration: %zu",
2494 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002495 }
2496}
2497
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002498void Camera3Device::insertResultLocked(CaptureResult *result,
2499 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002500 if (result == nullptr) return;
2501
Emilian Peev71c73a22017-03-21 16:35:51 +00002502 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2503 result->mMetadata.getAndLock());
2504 set_camera_metadata_vendor_id(meta, mVendorTagId);
2505 result->mMetadata.unlock(meta);
2506
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002507 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2508 (int32_t*)&frameNumber, 1) != OK) {
2509 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2510 return;
2511 }
2512
2513 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2514 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2515 return;
2516 }
2517
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002518 // Valid result, insert into queue
2519 List<CaptureResult>::iterator queuedResult =
2520 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2521 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2522 ", burstId = %" PRId32, __FUNCTION__,
2523 queuedResult->mResultExtras.requestId,
2524 queuedResult->mResultExtras.frameNumber,
2525 queuedResult->mResultExtras.burstId);
2526
2527 mResultSignal.signal();
2528}
2529
2530
2531void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002532 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002533 Mutex::Autolock l(mOutputLock);
2534
2535 CaptureResult captureResult;
2536 captureResult.mResultExtras = resultExtras;
2537 captureResult.mMetadata = partialResult;
2538
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002539 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002540}
2541
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002542
2543void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2544 CaptureResultExtras &resultExtras,
2545 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002546 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002547 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002548 if (pendingMetadata.isEmpty())
2549 return;
2550
2551 Mutex::Autolock l(mOutputLock);
2552
2553 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002554 if (reprocess) {
2555 if (frameNumber < mNextReprocessResultFrameNumber) {
2556 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002557 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002558 frameNumber, mNextReprocessResultFrameNumber);
2559 return;
2560 }
2561 mNextReprocessResultFrameNumber = frameNumber + 1;
2562 } else {
2563 if (frameNumber < mNextResultFrameNumber) {
2564 SET_ERR("Out-of-order capture result metadata submitted! "
2565 "(got frame number %d, expecting %d)",
2566 frameNumber, mNextResultFrameNumber);
2567 return;
2568 }
2569 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002570 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002571
2572 CaptureResult captureResult;
2573 captureResult.mResultExtras = resultExtras;
2574 captureResult.mMetadata = pendingMetadata;
2575
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002576 // Append any previous partials to form a complete result
2577 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2578 captureResult.mMetadata.append(collectedPartialResult);
2579 }
2580
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002581 // Derive some new keys for backward compaibility
2582 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2583 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2584 int32_t defaultBoost[1] = {100};
2585 captureResult.mMetadata.update(
2586 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2587 defaultBoost, 1);
2588 }
2589
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002590 captureResult.mMetadata.sort();
2591
2592 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002593 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2594 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002595 SET_ERR("No timestamp provided by HAL for frame %d!",
2596 frameNumber);
2597 return;
2598 }
2599
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002600 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2601 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2602
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002603 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002604}
2605
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002606/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002607 * Camera HAL device callback methods
2608 */
2609
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002610void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002611 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002612
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002613 status_t res;
2614
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002615 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002616 if (result->result == NULL && result->num_output_buffers == 0 &&
2617 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002618 SET_ERR("No result data provided by HAL for frame %d",
2619 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002620 return;
2621 }
Zhijun He204e3292014-07-14 17:09:23 -07002622
Zhijun He204e3292014-07-14 17:09:23 -07002623 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002624 result->result != NULL &&
2625 result->partial_result != 1) {
2626 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2627 " if partial result is not supported",
2628 frameNumber, result->partial_result);
2629 return;
2630 }
2631
2632 bool isPartialResult = false;
2633 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002634 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002635 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002636
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002637 // Get shutter timestamp and resultExtras from list of in-flight requests,
2638 // where it was added by the shutter notification for this frame. If the
2639 // shutter timestamp isn't received yet, append the output buffers to the
2640 // in-flight request and they will be returned when the shutter timestamp
2641 // arrives. Update the in-flight status and remove the in-flight entry if
2642 // all result data and shutter timestamp have been received.
2643 nsecs_t shutterTimestamp = 0;
2644
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002645 {
2646 Mutex::Autolock l(mInFlightLock);
2647 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2648 if (idx == NAME_NOT_FOUND) {
2649 SET_ERR("Unknown frame number for capture result: %d",
2650 frameNumber);
2651 return;
2652 }
2653 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002654 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2655 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002656 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002657 __FUNCTION__, request.resultExtras.requestId,
2658 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002659 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002660 // Always update the partial count to the latest one if it's not 0
2661 // (buffers only). When framework aggregates adjacent partial results
2662 // into one, the latest partial count will be used.
2663 if (result->partial_result != 0)
2664 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002665
2666 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002667 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002668 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2669 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2670 " the range of [1, %d] when metadata is included in the result",
2671 frameNumber, result->partial_result, mNumPartialResults);
2672 return;
2673 }
2674 isPartialResult = (result->partial_result < mNumPartialResults);
2675 if (isPartialResult) {
2676 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002677 }
2678
Shuzhen Wang4a472662017-02-26 23:29:04 -08002679 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002680 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002681 sendPartialCaptureResult(result->result, request.resultExtras,
2682 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002683 }
2684 }
2685
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002686 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002687 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002688
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002689 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002690 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002691 if (request.haveResultMetadata) {
2692 SET_ERR("Called multiple times with metadata for frame %d",
2693 frameNumber);
2694 return;
2695 }
Zhijun He204e3292014-07-14 17:09:23 -07002696 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002697 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002698 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002699 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002700 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002701 request.haveResultMetadata = true;
2702 }
2703
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002704 uint32_t numBuffersReturned = result->num_output_buffers;
2705 if (result->input_buffer != NULL) {
2706 if (hasInputBufferInRequest) {
2707 numBuffersReturned += 1;
2708 } else {
2709 ALOGW("%s: Input buffer should be NULL if there is no input"
2710 " buffer sent in the request",
2711 __FUNCTION__);
2712 }
2713 }
2714 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002715 if (request.numBuffersLeft < 0) {
2716 SET_ERR("Too many buffers returned for frame %d",
2717 frameNumber);
2718 return;
2719 }
2720
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002721 camera_metadata_ro_entry_t entry;
2722 res = find_camera_metadata_ro_entry(result->result,
2723 ANDROID_SENSOR_TIMESTAMP, &entry);
2724 if (res == OK && entry.count == 1) {
2725 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002726 }
2727
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002728 // If shutter event isn't received yet, append the output buffers to
2729 // the in-flight request. Otherwise, return the output buffers to
2730 // streams.
2731 if (shutterTimestamp == 0) {
2732 request.pendingOutputBuffers.appendArray(result->output_buffers,
2733 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002734 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002735 returnOutputBuffers(result->output_buffers,
2736 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002737 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002738
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002739 if (result->result != NULL && !isPartialResult) {
2740 if (shutterTimestamp == 0) {
2741 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002742 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002743 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002744 CameraMetadata metadata;
2745 metadata = result->result;
2746 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002747 collectedPartialResult, frameNumber,
2748 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002749 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002750 }
2751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 removeInFlightRequestIfReadyLocked(idx);
2753 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002754
Zhijun Hef0d962a2014-06-30 10:24:11 -07002755 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002756 if (hasInputBufferInRequest) {
2757 Camera3Stream *stream =
2758 Camera3Stream::cast(result->input_buffer->stream);
2759 res = stream->returnInputBuffer(*(result->input_buffer));
2760 // Note: stream may be deallocated at this point, if this buffer was the
2761 // last reference to it.
2762 if (res != OK) {
2763 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2764 " its stream:%s (%d)", __FUNCTION__,
2765 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002766 }
2767 } else {
2768 ALOGW("%s: Input buffer should be NULL if there is no input"
2769 " buffer sent in the request, skipping input buffer return.",
2770 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002771 }
2772 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002773}
2774
2775void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002776 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002777 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002778 {
2779 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002780 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002781 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002782
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002783 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002784 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002785 return;
2786 }
2787
2788 switch (msg->type) {
2789 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002790 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002791 break;
2792 }
2793 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002794 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002795 break;
2796 }
2797 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002798 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002799 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002800 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002801}
2802
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002803void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002804 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002805
2806 // Map camera HAL error codes to ICameraDeviceCallback error codes
2807 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002808 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002809 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002810 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002811 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002812 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002813 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002814 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002815 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002816 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002817 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002818 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002819 };
2820
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002821 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002822 ((msg.error_code >= 0) &&
2823 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2824 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002825 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002826
2827 int streamId = 0;
2828 if (msg.error_stream != NULL) {
2829 Camera3Stream *stream =
2830 Camera3Stream::cast(msg.error_stream);
2831 streamId = stream->getId();
2832 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002833 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2834 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 streamId, msg.error_code);
2836
2837 CaptureResultExtras resultExtras;
2838 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002839 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 // SET_ERR calls notifyError
2841 SET_ERR("Camera HAL reported serious device error");
2842 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002843 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2844 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2845 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002846 {
2847 Mutex::Autolock l(mInFlightLock);
2848 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2849 if (idx >= 0) {
2850 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2851 r.requestStatus = msg.error_code;
2852 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002853 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2854 errorCode) {
2855 // In case of missing result check whether the buffers
2856 // returned. If they returned, then remove inflight
2857 // request.
2858 removeInFlightRequestIfReadyLocked(idx);
2859 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002860 } else {
2861 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002862 ALOGE("Camera %s: %s: cannot find in-flight request on "
2863 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002864 resultExtras.frameNumber);
2865 }
2866 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002867 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868 if (listener != NULL) {
2869 listener->notifyError(errorCode, resultExtras);
2870 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002871 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002872 }
2873 break;
2874 default:
2875 // SET_ERR calls notifyError
2876 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2877 break;
2878 }
2879}
2880
2881void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002882 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002883 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002884
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 // Set timestamp for the request in the in-flight tracking
2886 // and get the request ID to send upstream
2887 {
2888 Mutex::Autolock l(mInFlightLock);
2889 idx = mInFlightMap.indexOfKey(msg.frame_number);
2890 if (idx >= 0) {
2891 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002892
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002893 // Verify ordering of shutter notifications
2894 {
2895 Mutex::Autolock l(mOutputLock);
2896 // TODO: need to track errors for tighter bounds on expected frame number.
2897 if (r.hasInputBuffer) {
2898 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2899 SET_ERR("Shutter notification out-of-order. Expected "
2900 "notification for frame %d, got frame %d",
2901 mNextReprocessShutterFrameNumber, msg.frame_number);
2902 return;
2903 }
2904 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2905 } else {
2906 if (msg.frame_number < mNextShutterFrameNumber) {
2907 SET_ERR("Shutter notification out-of-order. Expected "
2908 "notification for frame %d, got frame %d",
2909 mNextShutterFrameNumber, msg.frame_number);
2910 return;
2911 }
2912 mNextShutterFrameNumber = msg.frame_number + 1;
2913 }
2914 }
2915
Shuzhen Wang4a472662017-02-26 23:29:04 -08002916 r.shutterTimestamp = msg.timestamp;
2917 if (r.hasCallback) {
2918 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002920 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002921 // Call listener, if any
2922 if (listener != NULL) {
2923 listener->notifyShutter(r.resultExtras, msg.timestamp);
2924 }
2925 // send pending result and buffers
2926 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2927 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002928 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002929 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002930 returnOutputBuffers(r.pendingOutputBuffers.array(),
2931 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2932 r.pendingOutputBuffers.clear();
2933
2934 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002935 }
2936 }
2937 if (idx < 0) {
2938 SET_ERR("Shutter notification for non-existent frame number %d",
2939 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002940 }
2941}
2942
2943
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002944CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002945 ALOGV("%s", __FUNCTION__);
2946
Igor Murashkin1e479c02013-09-06 16:55:14 -07002947 CameraMetadata retVal;
2948
2949 if (mRequestThread != NULL) {
2950 retVal = mRequestThread->getLatestRequest();
2951 }
2952
Igor Murashkin1e479c02013-09-06 16:55:14 -07002953 return retVal;
2954}
2955
Jianing Weicb0652e2014-03-12 18:29:36 -07002956
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002957void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2958 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2959 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2960}
2961
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002962/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002963 * HalInterface inner class methods
2964 */
2965
2966Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
2967 mHal3Device(device) {}
2968
Yifan Hongf79b5542017-04-11 14:44:25 -07002969Camera3Device::HalInterface::HalInterface(
2970 sp<ICameraDeviceSession> &session,
2971 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002972 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002973 mHidlSession(session),
2974 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002975
2976Camera3Device::HalInterface::HalInterface() :
2977 mHal3Device(nullptr) {}
2978
2979Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002980 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002981 mHidlSession(other.mHidlSession),
2982 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002983
2984bool Camera3Device::HalInterface::valid() {
2985 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2986}
2987
2988void Camera3Device::HalInterface::clear() {
2989 mHal3Device = nullptr;
2990 mHidlSession.clear();
2991}
2992
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002993bool Camera3Device::HalInterface::supportBatchRequest() {
2994 return mHidlSession != nullptr;
2995}
2996
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002997status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2998 camera3_request_template_t templateId,
2999 /*out*/ camera_metadata_t **requestTemplate) {
3000 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3001 if (!valid()) return INVALID_OPERATION;
3002 status_t res = OK;
3003
3004 if (mHal3Device != nullptr) {
3005 const camera_metadata *r;
3006 r = mHal3Device->ops->construct_default_request_settings(
3007 mHal3Device, templateId);
3008 if (r == nullptr) return BAD_VALUE;
3009 *requestTemplate = clone_camera_metadata(r);
3010 if (requestTemplate == nullptr) {
3011 ALOGE("%s: Unable to clone camera metadata received from HAL",
3012 __FUNCTION__);
3013 return INVALID_OPERATION;
3014 }
3015 } else {
3016 common::V1_0::Status status;
3017 RequestTemplate id;
3018 switch (templateId) {
3019 case CAMERA3_TEMPLATE_PREVIEW:
3020 id = RequestTemplate::PREVIEW;
3021 break;
3022 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3023 id = RequestTemplate::STILL_CAPTURE;
3024 break;
3025 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3026 id = RequestTemplate::VIDEO_RECORD;
3027 break;
3028 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3029 id = RequestTemplate::VIDEO_SNAPSHOT;
3030 break;
3031 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3032 id = RequestTemplate::ZERO_SHUTTER_LAG;
3033 break;
3034 case CAMERA3_TEMPLATE_MANUAL:
3035 id = RequestTemplate::MANUAL;
3036 break;
3037 default:
3038 // Unknown template ID
3039 return BAD_VALUE;
3040 }
3041 mHidlSession->constructDefaultRequestSettings(id,
3042 [&status, &requestTemplate]
3043 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3044 status = s;
3045 if (status == common::V1_0::Status::OK) {
3046 const camera_metadata *r =
3047 reinterpret_cast<const camera_metadata_t*>(request.data());
3048 size_t expectedSize = request.size();
3049 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003050 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003051 *requestTemplate = clone_camera_metadata(r);
3052 if (*requestTemplate == nullptr) {
3053 ALOGE("%s: Unable to clone camera metadata received from HAL",
3054 __FUNCTION__);
3055 status = common::V1_0::Status::INTERNAL_ERROR;
3056 }
3057 } else {
3058 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3059 status = common::V1_0::Status::INTERNAL_ERROR;
3060 }
3061 }
3062 });
3063 res = CameraProviderManager::mapToStatusT(status);
3064 }
3065 return res;
3066}
3067
3068status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3069 ATRACE_NAME("CameraHal::configureStreams");
3070 if (!valid()) return INVALID_OPERATION;
3071 status_t res = OK;
3072
3073 if (mHal3Device != nullptr) {
3074 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3075 } else {
3076 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003077 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003078 StreamConfiguration requestedConfiguration;
3079 requestedConfiguration.streams.resize(config->num_streams);
3080 for (size_t i = 0; i < config->num_streams; i++) {
3081 Stream &dst = requestedConfiguration.streams[i];
3082 camera3_stream_t *src = config->streams[i];
3083
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003084 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3085 cam3stream->setBufferFreedListener(this);
3086 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003087 StreamType streamType;
3088 switch (src->stream_type) {
3089 case CAMERA3_STREAM_OUTPUT:
3090 streamType = StreamType::OUTPUT;
3091 break;
3092 case CAMERA3_STREAM_INPUT:
3093 streamType = StreamType::INPUT;
3094 break;
3095 default:
3096 ALOGE("%s: Stream %d: Unsupported stream type %d",
3097 __FUNCTION__, streamId, config->streams[i]->stream_type);
3098 return BAD_VALUE;
3099 }
3100 dst.id = streamId;
3101 dst.streamType = streamType;
3102 dst.width = src->width;
3103 dst.height = src->height;
3104 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003105 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003106 dst.dataSpace = mapToHidlDataspace(src->data_space);
3107 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003108
3109 activeStreams.insert(streamId);
3110 // Create Buffer ID map if necessary
3111 if (mBufferIdMaps.count(streamId) == 0) {
3112 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3113 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003114 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003115 // remove BufferIdMap for deleted streams
3116 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3117 int streamId = it->first;
3118 bool active = activeStreams.count(streamId) > 0;
3119 if (!active) {
3120 it = mBufferIdMaps.erase(it);
3121 } else {
3122 ++it;
3123 }
3124 }
3125
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003126 res = mapToStreamConfigurationMode(
3127 (camera3_stream_configuration_mode_t) config->operation_mode,
3128 /*out*/ &requestedConfiguration.operationMode);
3129 if (res != OK) {
3130 return res;
3131 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003132
3133 // Invoke configureStreams
3134
3135 HalStreamConfiguration finalConfiguration;
3136 common::V1_0::Status status;
3137 mHidlSession->configureStreams(requestedConfiguration,
3138 [&status, &finalConfiguration]
3139 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3140 finalConfiguration = halConfiguration;
3141 status = s;
3142 });
3143 if (status != common::V1_0::Status::OK ) {
3144 return CameraProviderManager::mapToStatusT(status);
3145 }
3146
3147 // And convert output stream configuration from HIDL
3148
3149 for (size_t i = 0; i < config->num_streams; i++) {
3150 camera3_stream_t *dst = config->streams[i];
3151 int streamId = Camera3Stream::cast(dst)->getId();
3152
3153 // Start scan at i, with the assumption that the stream order matches
3154 size_t realIdx = i;
3155 bool found = false;
3156 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3157 if (finalConfiguration.streams[realIdx].id == streamId) {
3158 found = true;
3159 break;
3160 }
3161 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3162 }
3163 if (!found) {
3164 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3165 __FUNCTION__, streamId);
3166 return INVALID_OPERATION;
3167 }
3168 HalStream &src = finalConfiguration.streams[realIdx];
3169
3170 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3171 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3172 if (dst->format != overrideFormat) {
3173 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3174 streamId, dst->format);
3175 }
3176 } else {
3177 // Override allowed with IMPLEMENTATION_DEFINED
3178 dst->format = overrideFormat;
3179 }
3180
3181 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3182 if (src.producerUsage != 0) {
3183 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3184 __FUNCTION__, streamId);
3185 return INVALID_OPERATION;
3186 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003187 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003188 } else {
3189 // OUTPUT
3190 if (src.consumerUsage != 0) {
3191 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3192 __FUNCTION__, streamId);
3193 return INVALID_OPERATION;
3194 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003195 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003196 }
3197 dst->max_buffers = src.maxBuffers;
3198 }
3199 }
3200 return res;
3201}
3202
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003203void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3204 /*out*/device::V3_2::CaptureRequest* captureRequest,
3205 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3206
3207 if (captureRequest == nullptr || handlesCreated == nullptr) {
3208 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3209 __FUNCTION__, captureRequest, handlesCreated);
3210 return;
3211 }
3212
3213 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003214
3215 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003216
3217 {
3218 std::lock_guard<std::mutex> lock(mInflightLock);
3219 if (request->input_buffer != nullptr) {
3220 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3221 buffer_handle_t buf = *(request->input_buffer->buffer);
3222 auto pair = getBufferId(buf, streamId);
3223 bool isNewBuffer = pair.first;
3224 uint64_t bufferId = pair.second;
3225 captureRequest->inputBuffer.streamId = streamId;
3226 captureRequest->inputBuffer.bufferId = bufferId;
3227 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3228 captureRequest->inputBuffer.status = BufferStatus::OK;
3229 native_handle_t *acquireFence = nullptr;
3230 if (request->input_buffer->acquire_fence != -1) {
3231 acquireFence = native_handle_create(1,0);
3232 acquireFence->data[0] = request->input_buffer->acquire_fence;
3233 handlesCreated->push_back(acquireFence);
3234 }
3235 captureRequest->inputBuffer.acquireFence = acquireFence;
3236 captureRequest->inputBuffer.releaseFence = nullptr;
3237
3238 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3239 request->input_buffer->buffer,
3240 request->input_buffer->acquire_fence);
3241 } else {
3242 captureRequest->inputBuffer.streamId = -1;
3243 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3244 }
3245
3246 captureRequest->outputBuffers.resize(request->num_output_buffers);
3247 for (size_t i = 0; i < request->num_output_buffers; i++) {
3248 const camera3_stream_buffer_t *src = request->output_buffers + i;
3249 StreamBuffer &dst = captureRequest->outputBuffers[i];
3250 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3251 buffer_handle_t buf = *(src->buffer);
3252 auto pair = getBufferId(buf, streamId);
3253 bool isNewBuffer = pair.first;
3254 dst.streamId = streamId;
3255 dst.bufferId = pair.second;
3256 dst.buffer = isNewBuffer ? buf : nullptr;
3257 dst.status = BufferStatus::OK;
3258 native_handle_t *acquireFence = nullptr;
3259 if (src->acquire_fence != -1) {
3260 acquireFence = native_handle_create(1,0);
3261 acquireFence->data[0] = src->acquire_fence;
3262 handlesCreated->push_back(acquireFence);
3263 }
3264 dst.acquireFence = acquireFence;
3265 dst.releaseFence = nullptr;
3266
3267 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3268 src->buffer, src->acquire_fence);
3269 }
3270 }
3271}
3272
3273status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3274 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3275 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3276 if (!valid()) return INVALID_OPERATION;
3277
3278 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3279 size_t batchSize = requests.size();
3280 captureRequests.resize(batchSize);
3281 std::vector<native_handle_t*> handlesCreated;
3282
3283 for (size_t i = 0; i < batchSize; i++) {
3284 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3285 }
3286
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003287 std::vector<device::V3_2::BufferCache> cachesToRemove;
3288 {
3289 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3290 for (auto& pair : mFreedBuffers) {
3291 // The stream might have been removed since onBufferFreed
3292 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3293 cachesToRemove.push_back({pair.first, pair.second});
3294 }
3295 }
3296 mFreedBuffers.clear();
3297 }
3298
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003299 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3300 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003301
3302 // Write metadata to FMQ.
3303 for (size_t i = 0; i < batchSize; i++) {
3304 camera3_capture_request_t* request = requests[i];
3305 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3306
3307 if (request->settings != nullptr) {
3308 size_t settingsSize = get_camera_metadata_size(request->settings);
3309 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3310 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3311 captureRequest->settings.resize(0);
3312 captureRequest->fmqSettingsSize = settingsSize;
3313 } else {
3314 if (mRequestMetadataQueue != nullptr) {
3315 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3316 }
3317 captureRequest->settings.setToExternal(
3318 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3319 get_camera_metadata_size(request->settings));
3320 captureRequest->fmqSettingsSize = 0u;
3321 }
3322 } else {
3323 // A null request settings maps to a size-0 CameraMetadata
3324 captureRequest->settings.resize(0);
3325 captureRequest->fmqSettingsSize = 0u;
3326 }
3327 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003328 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003329 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3330 status = s;
3331 *numRequestProcessed = n;
3332 });
3333
3334 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3335 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3336 __FUNCTION__, *numRequestProcessed, batchSize);
3337 status = common::V1_0::Status::INTERNAL_ERROR;
3338 }
3339
3340 for (auto& handle : handlesCreated) {
3341 native_handle_delete(handle);
3342 }
3343 return CameraProviderManager::mapToStatusT(status);
3344}
3345
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003346status_t Camera3Device::HalInterface::processCaptureRequest(
3347 camera3_capture_request_t *request) {
3348 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003349 if (!valid()) return INVALID_OPERATION;
3350 status_t res = OK;
3351
3352 if (mHal3Device != nullptr) {
3353 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3354 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003355 uint32_t numRequestProcessed = 0;
3356 std::vector<camera3_capture_request_t*> requests(1);
3357 requests[0] = request;
3358 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003359 }
3360 return res;
3361}
3362
3363status_t Camera3Device::HalInterface::flush() {
3364 ATRACE_NAME("CameraHal::flush");
3365 if (!valid()) return INVALID_OPERATION;
3366 status_t res = OK;
3367
3368 if (mHal3Device != nullptr) {
3369 res = mHal3Device->ops->flush(mHal3Device);
3370 } else {
3371 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3372 }
3373 return res;
3374}
3375
3376status_t Camera3Device::HalInterface::dump(int fd) {
3377 ATRACE_NAME("CameraHal::dump");
3378 if (!valid()) return INVALID_OPERATION;
3379 status_t res = OK;
3380
3381 if (mHal3Device != nullptr) {
3382 mHal3Device->ops->dump(mHal3Device, fd);
3383 } else {
3384 // Handled by CameraProviderManager::dump
3385 }
3386 return res;
3387}
3388
3389status_t Camera3Device::HalInterface::close() {
3390 ATRACE_NAME("CameraHal::close()");
3391 if (!valid()) return INVALID_OPERATION;
3392 status_t res = OK;
3393
3394 if (mHal3Device != nullptr) {
3395 mHal3Device->common.close(&mHal3Device->common);
3396 } else {
3397 mHidlSession->close();
3398 }
3399 return res;
3400}
3401
3402status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003403 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003404 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003405 auto pair = std::make_pair(buffer, acquireFence);
3406 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003407 return OK;
3408}
3409
3410status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003411 int32_t frameNumber, int32_t streamId,
3412 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003413 std::lock_guard<std::mutex> lock(mInflightLock);
3414
3415 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3416 auto it = mInflightBufferMap.find(key);
3417 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003418 auto pair = it->second;
3419 *buffer = pair.first;
3420 int acquireFence = pair.second;
3421 if (acquireFence > 0) {
3422 ::close(acquireFence);
3423 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003424 mInflightBufferMap.erase(it);
3425 return OK;
3426}
3427
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003428std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3429 const buffer_handle_t& buf, int streamId) {
3430 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3431
3432 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3433 auto it = bIdMap.find(buf);
3434 if (it == bIdMap.end()) {
3435 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003436 ALOGV("stream %d now have %zu buffer caches, buf %p",
3437 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003438 return std::make_pair(true, mNextBufferId - 1);
3439 } else {
3440 return std::make_pair(false, it->second);
3441 }
3442}
3443
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003444void Camera3Device::HalInterface::onBufferFreed(
3445 int streamId, const native_handle_t* handle) {
3446 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3447 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3448 auto mapIt = mBufferIdMaps.find(streamId);
3449 if (mapIt == mBufferIdMaps.end()) {
3450 // streamId might be from a deleted stream here
3451 ALOGI("%s: stream %d has been removed",
3452 __FUNCTION__, streamId);
3453 return;
3454 }
3455 BufferIdMap& bIdMap = mapIt->second;
3456 auto it = bIdMap.find(handle);
3457 if (it == bIdMap.end()) {
3458 ALOGW("%s: cannot find buffer %p in stream %d",
3459 __FUNCTION__, handle, streamId);
3460 return;
3461 } else {
3462 bufferId = it->second;
3463 bIdMap.erase(it);
3464 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3465 __FUNCTION__, streamId, bIdMap.size(), handle);
3466 }
3467 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3468}
3469
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003470/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003471 * RequestThread inner class methods
3472 */
3473
3474Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003475 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003476 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003477 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003478 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003479 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003480 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003481 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003482 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003483 mReconfigured(false),
3484 mDoPause(false),
3485 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003486 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003487 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003488 mCurrentAfTriggerId(0),
3489 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003490 mRepeatingLastFrameNumber(
3491 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003492 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003493 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003494}
3495
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003496Camera3Device::RequestThread::~RequestThread() {}
3497
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003498void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003499 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003500 Mutex::Autolock l(mRequestLock);
3501 mListener = listener;
3502}
3503
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003504void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003505 Mutex::Autolock l(mRequestLock);
3506 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003507 // Prepare video stream for high speed recording.
3508 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003509}
3510
Jianing Wei90e59c92014-03-12 18:29:36 -07003511status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003512 List<sp<CaptureRequest> > &requests,
3513 /*out*/
3514 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003515 Mutex::Autolock l(mRequestLock);
3516 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3517 ++it) {
3518 mRequestQueue.push_back(*it);
3519 }
3520
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003521 if (lastFrameNumber != NULL) {
3522 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3523 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3524 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3525 *lastFrameNumber);
3526 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003527
Jianing Wei90e59c92014-03-12 18:29:36 -07003528 unpauseForNewRequests();
3529
3530 return OK;
3531}
3532
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003533
3534status_t Camera3Device::RequestThread::queueTrigger(
3535 RequestTrigger trigger[],
3536 size_t count) {
3537
3538 Mutex::Autolock l(mTriggerMutex);
3539 status_t ret;
3540
3541 for (size_t i = 0; i < count; ++i) {
3542 ret = queueTriggerLocked(trigger[i]);
3543
3544 if (ret != OK) {
3545 return ret;
3546 }
3547 }
3548
3549 return OK;
3550}
3551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003552const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3553 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003554 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003555 if (d != nullptr) return d->mId;
3556 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003557}
3558
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003559status_t Camera3Device::RequestThread::queueTriggerLocked(
3560 RequestTrigger trigger) {
3561
3562 uint32_t tag = trigger.metadataTag;
3563 ssize_t index = mTriggerMap.indexOfKey(tag);
3564
3565 switch (trigger.getTagType()) {
3566 case TYPE_BYTE:
3567 // fall-through
3568 case TYPE_INT32:
3569 break;
3570 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003571 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3572 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003573 return INVALID_OPERATION;
3574 }
3575
3576 /**
3577 * Collect only the latest trigger, since we only have 1 field
3578 * in the request settings per trigger tag, and can't send more than 1
3579 * trigger per request.
3580 */
3581 if (index != NAME_NOT_FOUND) {
3582 mTriggerMap.editValueAt(index) = trigger;
3583 } else {
3584 mTriggerMap.add(tag, trigger);
3585 }
3586
3587 return OK;
3588}
3589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003590status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003591 const RequestList &requests,
3592 /*out*/
3593 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003594 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003595 if (lastFrameNumber != NULL) {
3596 *lastFrameNumber = mRepeatingLastFrameNumber;
3597 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003598 mRepeatingRequests.clear();
3599 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3600 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003601
3602 unpauseForNewRequests();
3603
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003604 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003605 return OK;
3606}
3607
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003608bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003609 if (mRepeatingRequests.empty()) {
3610 return false;
3611 }
3612 int32_t requestId = requestIn->mResultExtras.requestId;
3613 const RequestList &repeatRequests = mRepeatingRequests;
3614 // All repeating requests are guaranteed to have same id so only check first quest
3615 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3616 return (firstRequest->mResultExtras.requestId == requestId);
3617}
3618
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003619status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003620 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003621 return clearRepeatingRequestsLocked(lastFrameNumber);
3622
3623}
3624
3625status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003626 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003627 if (lastFrameNumber != NULL) {
3628 *lastFrameNumber = mRepeatingLastFrameNumber;
3629 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003630 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003631 return OK;
3632}
3633
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003634status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003635 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003636 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003637 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003638
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003639 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003640
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003641 // Send errors for all requests pending in the request queue, including
3642 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003643 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003644 if (listener != NULL) {
3645 for (RequestList::iterator it = mRequestQueue.begin();
3646 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003647 // Abort the input buffers for reprocess requests.
3648 if ((*it)->mInputStream != NULL) {
3649 camera3_stream_buffer_t inputBuffer;
3650 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3651 if (res != OK) {
3652 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3653 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3654 } else {
3655 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3656 if (res != OK) {
3657 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3658 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3659 }
3660 }
3661 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003662 // Set the frame number this request would have had, if it
3663 // had been submitted; this frame number will not be reused.
3664 // The requestId and burstId fields were set when the request was
3665 // submitted originally (in convertMetadataListToRequestListLocked)
3666 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003667 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003668 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003669 }
3670 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003671 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003672
3673 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003674 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003675 if (lastFrameNumber != NULL) {
3676 *lastFrameNumber = mRepeatingLastFrameNumber;
3677 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003678 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003679 return OK;
3680}
3681
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003682status_t Camera3Device::RequestThread::flush() {
3683 ATRACE_CALL();
3684 Mutex::Autolock l(mFlushLock);
3685
Emilian Peev08dd2452017-04-06 16:55:14 +01003686 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003687}
3688
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003689void Camera3Device::RequestThread::setPaused(bool paused) {
3690 Mutex::Autolock l(mPauseLock);
3691 mDoPause = paused;
3692 mDoPauseSignal.signal();
3693}
3694
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003695status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3696 int32_t requestId, nsecs_t timeout) {
3697 Mutex::Autolock l(mLatestRequestMutex);
3698 status_t res;
3699 while (mLatestRequestId != requestId) {
3700 nsecs_t startTime = systemTime();
3701
3702 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3703 if (res != OK) return res;
3704
3705 timeout -= (systemTime() - startTime);
3706 }
3707
3708 return OK;
3709}
3710
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003711void Camera3Device::RequestThread::requestExit() {
3712 // Call parent to set up shutdown
3713 Thread::requestExit();
3714 // The exit from any possible waits
3715 mDoPauseSignal.signal();
3716 mRequestSignal.signal();
3717}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003718
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003719void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003720 bool surfaceAbandoned = false;
3721 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003722 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003723 {
3724 Mutex::Autolock l(mRequestLock);
3725 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3726 // repeating requests.
3727 for (const auto& request : mRepeatingRequests) {
3728 for (const auto& s : request->mOutputStreams) {
3729 if (s->isAbandoned()) {
3730 surfaceAbandoned = true;
3731 clearRepeatingRequestsLocked(&lastFrameNumber);
3732 break;
3733 }
3734 }
3735 if (surfaceAbandoned) {
3736 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003737 }
3738 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003739 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003740 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003741
3742 if (listener != NULL && surfaceAbandoned) {
3743 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003744 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003745}
3746
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003747bool Camera3Device::RequestThread::sendRequestsBatch() {
3748 status_t res;
3749 size_t batchSize = mNextRequests.size();
3750 std::vector<camera3_capture_request_t*> requests(batchSize);
3751 uint32_t numRequestProcessed = 0;
3752 for (size_t i = 0; i < batchSize; i++) {
3753 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3754 }
3755
3756 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3757 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3758
3759 bool triggerRemoveFailed = false;
3760 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3761 for (size_t i = 0; i < numRequestProcessed; i++) {
3762 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3763 nextRequest.submitted = true;
3764
3765
3766 // Update the latest request sent to HAL
3767 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3768 Mutex::Autolock al(mLatestRequestMutex);
3769
3770 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3771 mLatestRequest.acquire(cloned);
3772
3773 sp<Camera3Device> parent = mParent.promote();
3774 if (parent != NULL) {
3775 parent->monitorMetadata(TagMonitor::REQUEST,
3776 nextRequest.halRequest.frame_number,
3777 0, mLatestRequest);
3778 }
3779 }
3780
3781 if (nextRequest.halRequest.settings != NULL) {
3782 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3783 }
3784
3785 if (!triggerRemoveFailed) {
3786 // Remove any previously queued triggers (after unlock)
3787 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3788 if (removeTriggerRes != OK) {
3789 triggerRemoveFailed = true;
3790 triggerFailedRequest = nextRequest;
3791 }
3792 }
3793 }
3794
3795 if (triggerRemoveFailed) {
3796 SET_ERR("RequestThread: Unable to remove triggers "
3797 "(capture request %d, HAL device: %s (%d)",
3798 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3799 cleanUpFailedRequests(/*sendRequestError*/ false);
3800 return false;
3801 }
3802
3803 if (res != OK) {
3804 // Should only get a failure here for malformed requests or device-level
3805 // errors, so consider all errors fatal. Bad metadata failures should
3806 // come through notify.
3807 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3808 mNextRequests[numRequestProcessed].halRequest.frame_number,
3809 strerror(-res), res);
3810 cleanUpFailedRequests(/*sendRequestError*/ false);
3811 return false;
3812 }
3813 return true;
3814}
3815
3816bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3817 status_t res;
3818
3819 for (auto& nextRequest : mNextRequests) {
3820 // Submit request and block until ready for next one
3821 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3822 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3823
3824 if (res != OK) {
3825 // Should only get a failure here for malformed requests or device-level
3826 // errors, so consider all errors fatal. Bad metadata failures should
3827 // come through notify.
3828 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3829 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3830 res);
3831 cleanUpFailedRequests(/*sendRequestError*/ false);
3832 return false;
3833 }
3834
3835 // Mark that the request has be submitted successfully.
3836 nextRequest.submitted = true;
3837
3838 // Update the latest request sent to HAL
3839 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3840 Mutex::Autolock al(mLatestRequestMutex);
3841
3842 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3843 mLatestRequest.acquire(cloned);
3844
3845 sp<Camera3Device> parent = mParent.promote();
3846 if (parent != NULL) {
3847 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3848 0, mLatestRequest);
3849 }
3850 }
3851
3852 if (nextRequest.halRequest.settings != NULL) {
3853 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3854 }
3855
3856 // Remove any previously queued triggers (after unlock)
3857 res = removeTriggers(mPrevRequest);
3858 if (res != OK) {
3859 SET_ERR("RequestThread: Unable to remove triggers "
3860 "(capture request %d, HAL device: %s (%d)",
3861 nextRequest.halRequest.frame_number, strerror(-res), res);
3862 cleanUpFailedRequests(/*sendRequestError*/ false);
3863 return false;
3864 }
3865 }
3866 return true;
3867}
3868
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003869bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003870 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003871 status_t res;
3872
3873 // Handle paused state.
3874 if (waitIfPaused()) {
3875 return true;
3876 }
3877
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003878 // Wait for the next batch of requests.
3879 waitForNextRequestBatch();
3880 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003881 return true;
3882 }
3883
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003884 // Get the latest request ID, if any
3885 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003886 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003887 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003888 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003889 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003890 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3892 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003893 }
3894
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003895 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003896 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003897 if (res == TIMED_OUT) {
3898 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003899 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003900 // Check if any stream is abandoned.
3901 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003902 return true;
3903 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003904 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003905 return false;
3906 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003907
Zhijun Hecc27e112013-10-03 16:12:43 -07003908 // Inform waitUntilRequestProcessed thread of a new request ID
3909 {
3910 Mutex::Autolock al(mLatestRequestMutex);
3911
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003912 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003913 mLatestRequestSignal.signal();
3914 }
3915
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003916 // Submit a batch of requests to HAL.
3917 // Use flush lock only when submitting multilple requests in a batch.
3918 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3919 // which may take a long time to finish so synchronizing flush() and
3920 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3921 // For now, only synchronize for high speed recording and we should figure something out for
3922 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003923 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003924
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003925 if (useFlushLock) {
3926 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003927 }
3928
Zhijun Hef0645c12016-08-02 00:58:11 -07003929 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003930 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003931
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003932 bool submitRequestSuccess = false;
3933 if (mInterface->supportBatchRequest()) {
3934 submitRequestSuccess = sendRequestsBatch();
3935 } else {
3936 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003937 }
3938
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003939 if (useFlushLock) {
3940 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003941 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003942
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003943 // Unset as current request
3944 {
3945 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003946 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003947 }
3948
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003949 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003950}
3951
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003952status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003953 ATRACE_CALL();
3954
Shuzhen Wang4a472662017-02-26 23:29:04 -08003955 for (size_t i = 0; i < mNextRequests.size(); i++) {
3956 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003957 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3958 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3959 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3960
3961 // Prepare a request to HAL
3962 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3963
3964 // Insert any queued triggers (before metadata is locked)
3965 status_t res = insertTriggers(captureRequest);
3966
3967 if (res < 0) {
3968 SET_ERR("RequestThread: Unable to insert triggers "
3969 "(capture request %d, HAL device: %s (%d)",
3970 halRequest->frame_number, strerror(-res), res);
3971 return INVALID_OPERATION;
3972 }
3973 int triggerCount = res;
3974 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3975 mPrevTriggers = triggerCount;
3976
3977 // If the request is the same as last, or we had triggers last time
3978 if (mPrevRequest != captureRequest || triggersMixedIn) {
3979 /**
3980 * HAL workaround:
3981 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3982 */
3983 res = addDummyTriggerIds(captureRequest);
3984 if (res != OK) {
3985 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3986 "(capture request %d, HAL device: %s (%d)",
3987 halRequest->frame_number, strerror(-res), res);
3988 return INVALID_OPERATION;
3989 }
3990
3991 /**
3992 * The request should be presorted so accesses in HAL
3993 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3994 */
3995 captureRequest->mSettings.sort();
3996 halRequest->settings = captureRequest->mSettings.getAndLock();
3997 mPrevRequest = captureRequest;
3998 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3999
4000 IF_ALOGV() {
4001 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4002 find_camera_metadata_ro_entry(
4003 halRequest->settings,
4004 ANDROID_CONTROL_AF_TRIGGER,
4005 &e
4006 );
4007 if (e.count > 0) {
4008 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4009 __FUNCTION__,
4010 halRequest->frame_number,
4011 e.data.u8[0]);
4012 }
4013 }
4014 } else {
4015 // leave request.settings NULL to indicate 'reuse latest given'
4016 ALOGVV("%s: Request settings are REUSED",
4017 __FUNCTION__);
4018 }
4019
4020 uint32_t totalNumBuffers = 0;
4021
4022 // Fill in buffers
4023 if (captureRequest->mInputStream != NULL) {
4024 halRequest->input_buffer = &captureRequest->mInputBuffer;
4025 totalNumBuffers += 1;
4026 } else {
4027 halRequest->input_buffer = NULL;
4028 }
4029
4030 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4031 captureRequest->mOutputStreams.size());
4032 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004033 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4034 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004035
4036 // Prepare video buffers for high speed recording on the first video request.
4037 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4038 // Only try to prepare video stream on the first video request.
4039 mPrepareVideoStream = false;
4040
4041 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4042 while (res == NOT_ENOUGH_DATA) {
4043 res = outputStream->prepareNextBuffer();
4044 }
4045 if (res != OK) {
4046 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4047 __FUNCTION__, strerror(-res), res);
4048 outputStream->cancelPrepare();
4049 }
4050 }
4051
Shuzhen Wang4a472662017-02-26 23:29:04 -08004052 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4053 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004054 if (res != OK) {
4055 // Can't get output buffer from gralloc queue - this could be due to
4056 // abandoned queue or other consumer misbehavior, so not a fatal
4057 // error
4058 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4059 " %s (%d)", strerror(-res), res);
4060
4061 return TIMED_OUT;
4062 }
4063 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004064
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004065 }
4066 totalNumBuffers += halRequest->num_output_buffers;
4067
4068 // Log request in the in-flight queue
4069 sp<Camera3Device> parent = mParent.promote();
4070 if (parent == NULL) {
4071 // Should not happen, and nowhere to send errors to, so just log it
4072 CLOGE("RequestThread: Parent is gone");
4073 return INVALID_OPERATION;
4074 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004075
4076 // If this request list is for constrained high speed recording (not
4077 // preview), and the current request is not the last one in the batch,
4078 // do not send callback to the app.
4079 bool hasCallback = true;
4080 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4081 hasCallback = false;
4082 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 res = parent->registerInFlight(halRequest->frame_number,
4084 totalNumBuffers, captureRequest->mResultExtras,
4085 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004086 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004087 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4088 ", burstId = %" PRId32 ".",
4089 __FUNCTION__,
4090 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4091 captureRequest->mResultExtras.burstId);
4092 if (res != OK) {
4093 SET_ERR("RequestThread: Unable to register new in-flight request:"
4094 " %s (%d)", strerror(-res), res);
4095 return INVALID_OPERATION;
4096 }
4097 }
4098
4099 return OK;
4100}
4101
Igor Murashkin1e479c02013-09-06 16:55:14 -07004102CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4103 Mutex::Autolock al(mLatestRequestMutex);
4104
4105 ALOGV("RequestThread::%s", __FUNCTION__);
4106
4107 return mLatestRequest;
4108}
4109
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004110bool Camera3Device::RequestThread::isStreamPending(
4111 sp<Camera3StreamInterface>& stream) {
4112 Mutex::Autolock l(mRequestLock);
4113
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004114 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004115 if (!nextRequest.submitted) {
4116 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4117 if (stream == s) return true;
4118 }
4119 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004120 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004121 }
4122
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004123 for (const auto& request : mRequestQueue) {
4124 for (const auto& s : request->mOutputStreams) {
4125 if (stream == s) return true;
4126 }
4127 if (stream == request->mInputStream) return true;
4128 }
4129
4130 for (const auto& request : mRepeatingRequests) {
4131 for (const auto& s : request->mOutputStreams) {
4132 if (stream == s) return true;
4133 }
4134 if (stream == request->mInputStream) return true;
4135 }
4136
4137 return false;
4138}
Jianing Weicb0652e2014-03-12 18:29:36 -07004139
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004140void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4141 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004142 return;
4143 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004144
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004145 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004146 // Skip the ones that have been submitted successfully.
4147 if (nextRequest.submitted) {
4148 continue;
4149 }
4150
4151 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4152 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4153 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4154
4155 if (halRequest->settings != NULL) {
4156 captureRequest->mSettings.unlock(halRequest->settings);
4157 }
4158
4159 if (captureRequest->mInputStream != NULL) {
4160 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4161 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4162 }
4163
4164 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4165 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4166 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4167 }
4168
4169 if (sendRequestError) {
4170 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004171 sp<NotificationListener> listener = mListener.promote();
4172 if (listener != NULL) {
4173 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004174 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004175 captureRequest->mResultExtras);
4176 }
4177 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004178
4179 // Remove yet-to-be submitted inflight request from inflightMap
4180 {
4181 sp<Camera3Device> parent = mParent.promote();
4182 if (parent != NULL) {
4183 Mutex::Autolock l(parent->mInFlightLock);
4184 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4185 if (idx >= 0) {
4186 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4187 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4188 parent->removeInFlightMapEntryLocked(idx);
4189 }
4190 }
4191 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004192 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004193
4194 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004195 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196}
4197
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004198void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199 // Optimized a bit for the simple steady-state case (single repeating
4200 // request), to avoid putting that request in the queue temporarily.
4201 Mutex::Autolock l(mRequestLock);
4202
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004203 assert(mNextRequests.empty());
4204
4205 NextRequest nextRequest;
4206 nextRequest.captureRequest = waitForNextRequestLocked();
4207 if (nextRequest.captureRequest == nullptr) {
4208 return;
4209 }
4210
4211 nextRequest.halRequest = camera3_capture_request_t();
4212 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004213 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004214
4215 // Wait for additional requests
4216 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4217
4218 for (size_t i = 1; i < batchSize; i++) {
4219 NextRequest additionalRequest;
4220 additionalRequest.captureRequest = waitForNextRequestLocked();
4221 if (additionalRequest.captureRequest == nullptr) {
4222 break;
4223 }
4224
4225 additionalRequest.halRequest = camera3_capture_request_t();
4226 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004227 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004228 }
4229
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004230 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004231 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004232 mNextRequests.size(), batchSize);
4233 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004234 }
4235
4236 return;
4237}
4238
4239sp<Camera3Device::CaptureRequest>
4240 Camera3Device::RequestThread::waitForNextRequestLocked() {
4241 status_t res;
4242 sp<CaptureRequest> nextRequest;
4243
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004244 while (mRequestQueue.empty()) {
4245 if (!mRepeatingRequests.empty()) {
4246 // Always atomically enqueue all requests in a repeating request
4247 // list. Guarantees a complete in-sequence set of captures to
4248 // application.
4249 const RequestList &requests = mRepeatingRequests;
4250 RequestList::const_iterator firstRequest =
4251 requests.begin();
4252 nextRequest = *firstRequest;
4253 mRequestQueue.insert(mRequestQueue.end(),
4254 ++firstRequest,
4255 requests.end());
4256 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004257
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004258 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 break;
4261 }
4262
4263 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4264
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004265 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4266 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004267 Mutex::Autolock pl(mPauseLock);
4268 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004269 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004270 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004271 // Let the tracker know
4272 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4273 if (statusTracker != 0) {
4274 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4275 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276 }
4277 // Stop waiting for now and let thread management happen
4278 return NULL;
4279 }
4280 }
4281
4282 if (nextRequest == NULL) {
4283 // Don't have a repeating request already in hand, so queue
4284 // must have an entry now.
4285 RequestList::iterator firstRequest =
4286 mRequestQueue.begin();
4287 nextRequest = *firstRequest;
4288 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004289 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4290 sp<NotificationListener> listener = mListener.promote();
4291 if (listener != NULL) {
4292 listener->notifyRequestQueueEmpty();
4293 }
4294 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 }
4296
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004297 // In case we've been unpaused by setPaused clearing mDoPause, need to
4298 // update internal pause state (capture/setRepeatingRequest unpause
4299 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004300 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004301 if (mPaused) {
4302 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4303 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4304 if (statusTracker != 0) {
4305 statusTracker->markComponentActive(mStatusId);
4306 }
4307 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004308 mPaused = false;
4309
4310 // Check if we've reconfigured since last time, and reset the preview
4311 // request if so. Can't use 'NULL request == repeat' across configure calls.
4312 if (mReconfigured) {
4313 mPrevRequest.clear();
4314 mReconfigured = false;
4315 }
4316
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004317 if (nextRequest != NULL) {
4318 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004319 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4320 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004321
4322 // Since RequestThread::clear() removes buffers from the input stream,
4323 // get the right buffer here before unlocking mRequestLock
4324 if (nextRequest->mInputStream != NULL) {
4325 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4326 if (res != OK) {
4327 // Can't get input buffer from gralloc queue - this could be due to
4328 // disconnected queue or other producer misbehavior, so not a fatal
4329 // error
4330 ALOGE("%s: Can't get input buffer, skipping request:"
4331 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004332
4333 sp<NotificationListener> listener = mListener.promote();
4334 if (listener != NULL) {
4335 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004336 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004337 nextRequest->mResultExtras);
4338 }
4339 return NULL;
4340 }
4341 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004342 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004343
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004344 return nextRequest;
4345}
4346
4347bool Camera3Device::RequestThread::waitIfPaused() {
4348 status_t res;
4349 Mutex::Autolock l(mPauseLock);
4350 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 if (mPaused == false) {
4352 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004353 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4354 // Let the tracker know
4355 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4356 if (statusTracker != 0) {
4357 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004359 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004361 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004362 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363 return true;
4364 }
4365 }
4366 // We don't set mPaused to false here, because waitForNextRequest needs
4367 // to further manage the paused state in case of starvation.
4368 return false;
4369}
4370
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004371void Camera3Device::RequestThread::unpauseForNewRequests() {
4372 // With work to do, mark thread as unpaused.
4373 // If paused by request (setPaused), don't resume, to avoid
4374 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004375 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004376 Mutex::Autolock p(mPauseLock);
4377 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004378 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4379 if (mPaused) {
4380 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4381 if (statusTracker != 0) {
4382 statusTracker->markComponentActive(mStatusId);
4383 }
4384 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004385 mPaused = false;
4386 }
4387}
4388
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004389void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4390 sp<Camera3Device> parent = mParent.promote();
4391 if (parent != NULL) {
4392 va_list args;
4393 va_start(args, fmt);
4394
4395 parent->setErrorStateV(fmt, args);
4396
4397 va_end(args);
4398 }
4399}
4400
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004401status_t Camera3Device::RequestThread::insertTriggers(
4402 const sp<CaptureRequest> &request) {
4403
4404 Mutex::Autolock al(mTriggerMutex);
4405
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004406 sp<Camera3Device> parent = mParent.promote();
4407 if (parent == NULL) {
4408 CLOGE("RequestThread: Parent is gone");
4409 return DEAD_OBJECT;
4410 }
4411
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004412 CameraMetadata &metadata = request->mSettings;
4413 size_t count = mTriggerMap.size();
4414
4415 for (size_t i = 0; i < count; ++i) {
4416 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004417 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004418
4419 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4420 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4421 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004422 if (isAeTrigger) {
4423 request->mResultExtras.precaptureTriggerId = triggerId;
4424 mCurrentPreCaptureTriggerId = triggerId;
4425 } else {
4426 request->mResultExtras.afTriggerId = triggerId;
4427 mCurrentAfTriggerId = triggerId;
4428 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004429 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004430 }
4431
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004432 camera_metadata_entry entry = metadata.find(tag);
4433
4434 if (entry.count > 0) {
4435 /**
4436 * Already has an entry for this trigger in the request.
4437 * Rewrite it with our requested trigger value.
4438 */
4439 RequestTrigger oldTrigger = trigger;
4440
4441 oldTrigger.entryValue = entry.data.u8[0];
4442
4443 mTriggerReplacedMap.add(tag, oldTrigger);
4444 } else {
4445 /**
4446 * More typical, no trigger entry, so we just add it
4447 */
4448 mTriggerRemovedMap.add(tag, trigger);
4449 }
4450
4451 status_t res;
4452
4453 switch (trigger.getTagType()) {
4454 case TYPE_BYTE: {
4455 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4456 res = metadata.update(tag,
4457 &entryValue,
4458 /*count*/1);
4459 break;
4460 }
4461 case TYPE_INT32:
4462 res = metadata.update(tag,
4463 &trigger.entryValue,
4464 /*count*/1);
4465 break;
4466 default:
4467 ALOGE("%s: Type not supported: 0x%x",
4468 __FUNCTION__,
4469 trigger.getTagType());
4470 return INVALID_OPERATION;
4471 }
4472
4473 if (res != OK) {
4474 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4475 ", value %d", __FUNCTION__, trigger.getTagName(),
4476 trigger.entryValue);
4477 return res;
4478 }
4479
4480 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4481 trigger.getTagName(),
4482 trigger.entryValue);
4483 }
4484
4485 mTriggerMap.clear();
4486
4487 return count;
4488}
4489
4490status_t Camera3Device::RequestThread::removeTriggers(
4491 const sp<CaptureRequest> &request) {
4492 Mutex::Autolock al(mTriggerMutex);
4493
4494 CameraMetadata &metadata = request->mSettings;
4495
4496 /**
4497 * Replace all old entries with their old values.
4498 */
4499 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4500 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4501
4502 status_t res;
4503
4504 uint32_t tag = trigger.metadataTag;
4505 switch (trigger.getTagType()) {
4506 case TYPE_BYTE: {
4507 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4508 res = metadata.update(tag,
4509 &entryValue,
4510 /*count*/1);
4511 break;
4512 }
4513 case TYPE_INT32:
4514 res = metadata.update(tag,
4515 &trigger.entryValue,
4516 /*count*/1);
4517 break;
4518 default:
4519 ALOGE("%s: Type not supported: 0x%x",
4520 __FUNCTION__,
4521 trigger.getTagType());
4522 return INVALID_OPERATION;
4523 }
4524
4525 if (res != OK) {
4526 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4527 ", trigger value %d", __FUNCTION__,
4528 trigger.getTagName(), trigger.entryValue);
4529 return res;
4530 }
4531 }
4532 mTriggerReplacedMap.clear();
4533
4534 /**
4535 * Remove all new entries.
4536 */
4537 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4538 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4539 status_t res = metadata.erase(trigger.metadataTag);
4540
4541 if (res != OK) {
4542 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4543 ", trigger value %d", __FUNCTION__,
4544 trigger.getTagName(), trigger.entryValue);
4545 return res;
4546 }
4547 }
4548 mTriggerRemovedMap.clear();
4549
4550 return OK;
4551}
4552
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004553status_t Camera3Device::RequestThread::addDummyTriggerIds(
4554 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004555 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004556 static const int32_t dummyTriggerId = 1;
4557 status_t res;
4558
4559 CameraMetadata &metadata = request->mSettings;
4560
4561 // If AF trigger is active, insert a dummy AF trigger ID if none already
4562 // exists
4563 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4564 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4565 if (afTrigger.count > 0 &&
4566 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4567 afId.count == 0) {
4568 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4569 if (res != OK) return res;
4570 }
4571
4572 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4573 // if none already exists
4574 camera_metadata_entry pcTrigger =
4575 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4576 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4577 if (pcTrigger.count > 0 &&
4578 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4579 pcId.count == 0) {
4580 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4581 &dummyTriggerId, 1);
4582 if (res != OK) return res;
4583 }
4584
4585 return OK;
4586}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004587
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004588/**
4589 * PreparerThread inner class methods
4590 */
4591
4592Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004593 Thread(/*canCallJava*/false), mListener(nullptr),
4594 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004595}
4596
4597Camera3Device::PreparerThread::~PreparerThread() {
4598 Thread::requestExitAndWait();
4599 if (mCurrentStream != nullptr) {
4600 mCurrentStream->cancelPrepare();
4601 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4602 mCurrentStream.clear();
4603 }
4604 clear();
4605}
4606
Ruben Brunkc78ac262015-08-13 17:58:46 -07004607status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004608 status_t res;
4609
4610 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004611 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004612
Ruben Brunkc78ac262015-08-13 17:58:46 -07004613 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004614 if (res == OK) {
4615 // No preparation needed, fire listener right off
4616 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004617 if (listener != NULL) {
4618 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004619 }
4620 return OK;
4621 } else if (res != NOT_ENOUGH_DATA) {
4622 return res;
4623 }
4624
4625 // Need to prepare, start up thread if necessary
4626 if (!mActive) {
4627 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4628 // isn't running
4629 Thread::requestExitAndWait();
4630 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4631 if (res != OK) {
4632 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004633 if (listener != NULL) {
4634 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004635 }
4636 return res;
4637 }
4638 mCancelNow = false;
4639 mActive = true;
4640 ALOGV("%s: Preparer stream started", __FUNCTION__);
4641 }
4642
4643 // queue up the work
4644 mPendingStreams.push_back(stream);
4645 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4646
4647 return OK;
4648}
4649
4650status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004651 Mutex::Autolock l(mLock);
4652
4653 for (const auto& stream : mPendingStreams) {
4654 stream->cancelPrepare();
4655 }
4656 mPendingStreams.clear();
4657 mCancelNow = true;
4658
4659 return OK;
4660}
4661
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004662void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004663 Mutex::Autolock l(mLock);
4664 mListener = listener;
4665}
4666
4667bool Camera3Device::PreparerThread::threadLoop() {
4668 status_t res;
4669 {
4670 Mutex::Autolock l(mLock);
4671 if (mCurrentStream == nullptr) {
4672 // End thread if done with work
4673 if (mPendingStreams.empty()) {
4674 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4675 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4676 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4677 mActive = false;
4678 return false;
4679 }
4680
4681 // Get next stream to prepare
4682 auto it = mPendingStreams.begin();
4683 mCurrentStream = *it;
4684 mPendingStreams.erase(it);
4685 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4686 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4687 } else if (mCancelNow) {
4688 mCurrentStream->cancelPrepare();
4689 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4690 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4691 mCurrentStream.clear();
4692 mCancelNow = false;
4693 return true;
4694 }
4695 }
4696
4697 res = mCurrentStream->prepareNextBuffer();
4698 if (res == NOT_ENOUGH_DATA) return true;
4699 if (res != OK) {
4700 // Something bad happened; try to recover by cancelling prepare and
4701 // signalling listener anyway
4702 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4703 mCurrentStream->getId(), res, strerror(-res));
4704 mCurrentStream->cancelPrepare();
4705 }
4706
4707 // This stream has finished, notify listener
4708 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004709 sp<NotificationListener> listener = mListener.promote();
4710 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004711 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4712 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004713 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004714 }
4715
4716 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4717 mCurrentStream.clear();
4718
4719 return true;
4720}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004721
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004722/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004723 * Static callback forwarding methods from HAL to instance
4724 */
4725
4726void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4727 const camera3_capture_result *result) {
4728 Camera3Device *d =
4729 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004730
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004731 d->processCaptureResult(result);
4732}
4733
4734void Camera3Device::sNotify(const camera3_callback_ops *cb,
4735 const camera3_notify_msg *msg) {
4736 Camera3Device *d =
4737 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4738 d->notify(msg);
4739}
4740
4741}; // namespace android