blob: 47c7e3f24aa66de6e3f67899511dbc70c8159725 [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
166 mDeviceVersion = device->common.version;
167 mDeviceInfo = info.static_camera_characteristics;
168 mInterface = std::make_unique<HalInterface>(device);
169
170 return initializeCommonLocked();
171}
172
173status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
174 ATRACE_CALL();
175 Mutex::Autolock il(mInterfaceLock);
176 Mutex::Autolock l(mLock);
177
178 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
179 if (mStatus != STATUS_UNINITIALIZED) {
180 CLOGE("Already initialized!");
181 return INVALID_OPERATION;
182 }
183 if (manager == nullptr) return INVALID_OPERATION;
184
185 sp<ICameraDeviceSession> session;
186 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800187 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 /*out*/ &session);
189 ATRACE_END();
190 if (res != OK) {
191 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
192 return res;
193 }
194
Steven Moreland5ff9c912017-03-09 23:13:00 -0800195 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800196 if (res != OK) {
197 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
198 session->close();
199 return res;
200 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800201
Yifan Hongf79b5542017-04-11 14:44:25 -0700202 std::shared_ptr<RequestMetadataQueue> queue;
203 auto getQueueRet = session->getCaptureRequestMetadataQueue([&queue](const auto& descriptor) {
204 queue = std::make_shared<RequestMetadataQueue>(descriptor);
205 if (!queue->isValid() || queue->availableToWrite() <= 0) {
206 ALOGW("HAL returns empty request metadata fmq, not use it");
207 queue = nullptr;
208 // don't use the queue onwards.
209 }
210 });
211 if (!getQueueRet.isOk()) {
212 ALOGW("Transaction error when getting request metadata fmq: %s, not use it",
213 getQueueRet.description().c_str());
214 queue = nullptr;
215 // Don't use the queue onwards.
216 }
217
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800218 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
219 // for now use 3_4 to keep legacy devices working
220 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Yifan Hongf79b5542017-04-11 14:44:25 -0700221 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000222 std::string providerType;
223 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800224
225 return initializeCommonLocked();
226}
227
228status_t Camera3Device::initializeCommonLocked() {
229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700230 /** Start up status tracker thread */
231 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800232 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700233 if (res != OK) {
234 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
235 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800236 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 mStatusTracker.clear();
238 return res;
239 }
240
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700241 /** Register in-flight map to the status tracker */
242 mInFlightStatusId = mStatusTracker->addComponent();
243
Zhijun He125684a2015-12-26 15:07:30 -0800244 /** Create buffer manager */
245 mBufferManager = new Camera3BufferManager();
246
Emilian Peev71c73a22017-03-21 16:35:51 +0000247 mTagMonitor.initialize(mVendorTagId);
248
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700249 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800250 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
251 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
252 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700253 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
254 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
255 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800256
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700257 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800258 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
259 aeLockAvailable);
260 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800261 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700262 SET_ERR_L("Unable to start request queue thread: %s (%d)",
263 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800265 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800266 return res;
267 }
268
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700269 mPreparerThread = new PreparerThread();
270
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700271 // Determine whether we need to derive sensitivity boost values for older devices.
272 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
273 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800274 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700275 mDerivePostRawSensKey = true;
276 }
277
Ruben Brunk183f0562015-08-12 12:55:02 -0700278 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800279 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700280 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700281 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800283
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800284 // Measure the clock domain offset between camera and video/hw_composer
285 camera_metadata_entry timestampSource =
286 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
287 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
288 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
289 mTimestampOffset = getMonoToBoottimeOffset();
290 }
291
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700292 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700293 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
294 camera_metadata_entry partialResultsCount =
295 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
296 if (partialResultsCount.count > 0) {
297 mNumPartialResults = partialResultsCount.data.i32[0];
298 mUsePartialResult = (mNumPartialResults > 1);
299 }
300 } else {
301 camera_metadata_entry partialResultsQuirk =
302 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
303 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
304 mUsePartialResult = true;
305 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700306 }
307
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700308 camera_metadata_entry configs =
309 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
310 for (uint32_t i = 0; i < configs.count; i += 4) {
311 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
312 configs.data.i32[i + 3] ==
313 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
314 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
315 configs.data.i32[i + 2]));
316 }
317 }
318
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800319 return OK;
320}
321
322status_t Camera3Device::disconnect() {
323 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800325
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700326 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800329
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700330 {
331 Mutex::Autolock l(mLock);
332 if (mStatus == STATUS_UNINITIALIZED) return res;
333
334 if (mStatus == STATUS_ACTIVE ||
335 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
336 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700337 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700338 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700339 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700340 } else {
341 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
342 if (res != OK) {
343 SET_ERR_L("Timeout waiting for HAL to drain");
344 // Continue to close device even in case of error
345 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700346 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800347 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800348
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700349 if (mStatus == STATUS_ERROR) {
350 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700351 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700352
353 if (mStatusTracker != NULL) {
354 mStatusTracker->requestExit();
355 }
356
357 if (mRequestThread != NULL) {
358 mRequestThread->requestExit();
359 }
360
361 mOutputStreams.clear();
362 mInputStream.clear();
363 }
364
365 // Joining done without holding mLock, otherwise deadlocks may ensue
366 // as the threads try to access parent state
367 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
368 // HAL may be in a bad state, so waiting for request thread
369 // (which may be stuck in the HAL processCaptureRequest call)
370 // could be dangerous.
371 mRequestThread->join();
372 }
373
374 if (mStatusTracker != NULL) {
375 mStatusTracker->join();
376 }
377
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800378 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700379 {
380 Mutex::Autolock l(mLock);
381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800382 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800384 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800385
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800386 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700387 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800388
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700389 // Call close without internal mutex held, as the HAL close may need to
390 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700392
393 {
394 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800395 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700396 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800398
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700399 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700400 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800401}
402
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403// For dumping/debugging only -
404// try to acquire a lock a few times, eventually give up to proceed with
405// debug/dump operations
406bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
407 bool gotLock = false;
408 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
409 if (lock.tryLock() == NO_ERROR) {
410 gotLock = true;
411 break;
412 } else {
413 usleep(kDumpSleepDuration);
414 }
415 }
416 return gotLock;
417}
418
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700419Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
420 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
421 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
422 const int STREAM_CONFIGURATION_SIZE = 4;
423 const int STREAM_FORMAT_OFFSET = 0;
424 const int STREAM_WIDTH_OFFSET = 1;
425 const int STREAM_HEIGHT_OFFSET = 2;
426 const int STREAM_IS_INPUT_OFFSET = 3;
427 camera_metadata_ro_entry_t availableStreamConfigs =
428 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
429 if (availableStreamConfigs.count == 0 ||
430 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
431 return Size(0, 0);
432 }
433
434 // Get max jpeg size (area-wise).
435 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
436 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
437 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
438 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
439 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
440 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
441 && format == HAL_PIXEL_FORMAT_BLOB &&
442 (width * height > maxJpegWidth * maxJpegHeight)) {
443 maxJpegWidth = width;
444 maxJpegHeight = height;
445 }
446 }
447 } else {
448 camera_metadata_ro_entry availableJpegSizes =
449 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
450 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
451 return Size(0, 0);
452 }
453
454 // Get max jpeg size (area-wise).
455 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
456 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
457 > (maxJpegWidth * maxJpegHeight)) {
458 maxJpegWidth = availableJpegSizes.data.i32[i];
459 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
460 }
461 }
462 }
463 return Size(maxJpegWidth, maxJpegHeight);
464}
465
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800466nsecs_t Camera3Device::getMonoToBoottimeOffset() {
467 // try three times to get the clock offset, choose the one
468 // with the minimum gap in measurements.
469 const int tries = 3;
470 nsecs_t bestGap, measured;
471 for (int i = 0; i < tries; ++i) {
472 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
473 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
474 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
475 const nsecs_t gap = tmono2 - tmono;
476 if (i == 0 || gap < bestGap) {
477 bestGap = gap;
478 measured = tbase - ((tmono + tmono2) >> 1);
479 }
480 }
481 return measured;
482}
483
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700484/**
485 * Map Android N dataspace definitions back to Android M definitions, for
486 * use with HALv3.3 or older.
487 *
488 * Only map where correspondences exist, and otherwise preserve the value.
489 */
490android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
491 switch (dataSpace) {
492 case HAL_DATASPACE_V0_SRGB_LINEAR:
493 return HAL_DATASPACE_SRGB_LINEAR;
494 case HAL_DATASPACE_V0_SRGB:
495 return HAL_DATASPACE_SRGB;
496 case HAL_DATASPACE_V0_JFIF:
497 return HAL_DATASPACE_JFIF;
498 case HAL_DATASPACE_V0_BT601_625:
499 return HAL_DATASPACE_BT601_625;
500 case HAL_DATASPACE_V0_BT601_525:
501 return HAL_DATASPACE_BT601_525;
502 case HAL_DATASPACE_V0_BT709:
503 return HAL_DATASPACE_BT709;
504 default:
505 return dataSpace;
506 }
507}
508
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800509hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
510 int frameworkFormat) {
511 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
512}
513
514DataspaceFlags Camera3Device::mapToHidlDataspace(
515 android_dataspace dataSpace) {
516 return dataSpace;
517}
518
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700519BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700520 uint32_t usage) {
521 return usage;
522}
523
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800524StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
525 switch (rotation) {
526 case CAMERA3_STREAM_ROTATION_0:
527 return StreamRotation::ROTATION_0;
528 case CAMERA3_STREAM_ROTATION_90:
529 return StreamRotation::ROTATION_90;
530 case CAMERA3_STREAM_ROTATION_180:
531 return StreamRotation::ROTATION_180;
532 case CAMERA3_STREAM_ROTATION_270:
533 return StreamRotation::ROTATION_270;
534 }
535 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
536 return StreamRotation::ROTATION_0;
537}
538
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800539status_t Camera3Device::mapToStreamConfigurationMode(
540 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
541 if (mode == nullptr) return BAD_VALUE;
542 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
543 switch(operationMode) {
544 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
545 *mode = StreamConfigurationMode::NORMAL_MODE;
546 break;
547 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
548 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
549 break;
550 default:
551 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
552 return BAD_VALUE;
553 }
554 } else {
555 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800557 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558}
559
560camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
561 switch (status) {
562 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
563 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
564 }
565 return CAMERA3_BUFFER_STATUS_ERROR;
566}
567
568int Camera3Device::mapToFrameworkFormat(
569 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
570 return static_cast<uint32_t>(pixelFormat);
571}
572
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700573uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700574 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700575 return usage;
576}
577
578uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700579 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700580 return usage;
581}
582
Zhijun Hef7da0962014-04-24 13:27:56 -0700583ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700584 // Get max jpeg size (area-wise).
585 Size maxJpegResolution = getMaxJpegResolution();
586 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800587 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
588 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700589 return BAD_VALUE;
590 }
591
Zhijun Hef7da0962014-04-24 13:27:56 -0700592 // Get max jpeg buffer size
593 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700594 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
595 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800596 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
597 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700598 return BAD_VALUE;
599 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700600 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800601 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700602
603 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700604 float scaleFactor = ((float) (width * height)) /
605 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800606 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
607 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700608 if (jpegBufferSize > maxJpegBufferSize) {
609 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700610 }
611
612 return jpegBufferSize;
613}
614
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700615ssize_t Camera3Device::getPointCloudBufferSize() const {
616 const int FLOATS_PER_POINT=4;
617 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
618 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
620 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700621 return BAD_VALUE;
622 }
623 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
624 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
625 return maxBytesForPointCloud;
626}
627
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800628ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800629 const int PER_CONFIGURATION_SIZE = 3;
630 const int WIDTH_OFFSET = 0;
631 const int HEIGHT_OFFSET = 1;
632 const int SIZE_OFFSET = 2;
633 camera_metadata_ro_entry rawOpaqueSizes =
634 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800635 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800636 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
638 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800639 return BAD_VALUE;
640 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700641
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800642 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
643 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
644 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
645 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
646 }
647 }
648
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800649 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
650 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 return BAD_VALUE;
652}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700653
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800654status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
655 ATRACE_CALL();
656 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700657
658 // Try to lock, but continue in case of failure (to avoid blocking in
659 // deadlocks)
660 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
661 bool gotLock = tryLockSpinRightRound(mLock);
662
663 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800664 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
665 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700666 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800667 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
668 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700669
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800670 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700671
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800672 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700673 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800674 int n = args.size();
675 for (int i = 0; i < n; i++) {
676 if (args[i] == templatesOption) {
677 dumpTemplates = true;
678 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700679 if (args[i] == monitorOption) {
680 if (i + 1 < n) {
681 String8 monitorTags = String8(args[i + 1]);
682 if (monitorTags == "off") {
683 mTagMonitor.disableMonitoring();
684 } else {
685 mTagMonitor.parseTagsToMonitor(monitorTags);
686 }
687 } else {
688 mTagMonitor.disableMonitoring();
689 }
690 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 }
692
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800693 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800694
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800695 const char *status =
696 mStatus == STATUS_ERROR ? "ERROR" :
697 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
699 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800700 mStatus == STATUS_ACTIVE ? "ACTIVE" :
701 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700702
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700704 if (mStatus == STATUS_ERROR) {
705 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
706 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800707 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800708 const char *mode =
709 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
710 mOperatingMode == static_cast<int>(
711 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
712 "CUSTOM";
713 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714
715 if (mInputStream != NULL) {
716 write(fd, lines.string(), lines.size());
717 mInputStream->dump(fd, args);
718 } else {
719 lines.appendFormat(" No input stream.\n");
720 write(fd, lines.string(), lines.size());
721 }
722 for (size_t i = 0; i < mOutputStreams.size(); i++) {
723 mOutputStreams[i]->dump(fd,args);
724 }
725
Zhijun He431503c2016-03-07 17:30:16 -0800726 if (mBufferManager != NULL) {
727 lines = String8(" Camera3 Buffer Manager:\n");
728 write(fd, lines.string(), lines.size());
729 mBufferManager->dump(fd, args);
730 }
Zhijun He125684a2015-12-26 15:07:30 -0800731
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700732 lines = String8(" In-flight requests:\n");
733 if (mInFlightMap.size() == 0) {
734 lines.append(" None\n");
735 } else {
736 for (size_t i = 0; i < mInFlightMap.size(); i++) {
737 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700738 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700739 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800740 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700741 r.numBuffersLeft);
742 }
743 }
744 write(fd, lines.string(), lines.size());
745
Igor Murashkin1e479c02013-09-06 16:55:14 -0700746 {
747 lines = String8(" Last request sent:\n");
748 write(fd, lines.string(), lines.size());
749
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700750 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700751 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
752 }
753
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800754 if (dumpTemplates) {
755 const char *templateNames[] = {
756 "TEMPLATE_PREVIEW",
757 "TEMPLATE_STILL_CAPTURE",
758 "TEMPLATE_VIDEO_RECORD",
759 "TEMPLATE_VIDEO_SNAPSHOT",
760 "TEMPLATE_ZERO_SHUTTER_LAG",
761 "TEMPLATE_MANUAL"
762 };
763
764 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800765 camera_metadata_t *templateRequest = nullptr;
766 mInterface->constructDefaultRequestSettings(
767 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800768 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800769 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800770 lines.append(" Not supported\n");
771 write(fd, lines.string(), lines.size());
772 } else {
773 write(fd, lines.string(), lines.size());
774 dump_indented_camera_metadata(templateRequest,
775 fd, /*verbosity*/2, /*indentation*/8);
776 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800777 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800778 }
779 }
780
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700781 mTagMonitor.dumpMonitoredMetadata(fd);
782
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800783 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800784 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800785 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800786 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800787 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700789 if (gotLock) mLock.unlock();
790 if (gotInterfaceLock) mInterfaceLock.unlock();
791
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800792 return OK;
793}
794
795const CameraMetadata& Camera3Device::info() const {
796 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800797 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
798 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700799 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800800 mStatus == STATUS_ERROR ?
801 "when in error state" : "before init");
802 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800803 return mDeviceInfo;
804}
805
Jianing Wei90e59c92014-03-12 18:29:36 -0700806status_t Camera3Device::checkStatusOkToCaptureLocked() {
807 switch (mStatus) {
808 case STATUS_ERROR:
809 CLOGE("Device has encountered a serious error");
810 return INVALID_OPERATION;
811 case STATUS_UNINITIALIZED:
812 CLOGE("Device not initialized");
813 return INVALID_OPERATION;
814 case STATUS_UNCONFIGURED:
815 case STATUS_CONFIGURED:
816 case STATUS_ACTIVE:
817 // OK
818 break;
819 default:
820 SET_ERR_L("Unexpected status: %d", mStatus);
821 return INVALID_OPERATION;
822 }
823 return OK;
824}
825
826status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700827 const List<const CameraMetadata> &metadataList,
828 const std::list<const SurfaceMap> &surfaceMaps,
829 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700830 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 if (requestList == NULL) {
832 CLOGE("requestList cannot be NULL.");
833 return BAD_VALUE;
834 }
835
Jianing Weicb0652e2014-03-12 18:29:36 -0700836 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700837 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
838 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
839 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
840 ++metadataIt, ++surfaceMapIt) {
841 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700842 if (newRequest == 0) {
843 CLOGE("Can't create capture request");
844 return BAD_VALUE;
845 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700846
Shuzhen Wang9d066012016-09-30 11:30:20 -0700847 newRequest->mRepeating = repeating;
848
Jianing Weicb0652e2014-03-12 18:29:36 -0700849 // Setup burst Id and request Id
850 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
852 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700853 CLOGE("RequestID entry exists; but must not be empty in metadata");
854 return BAD_VALUE;
855 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700856 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700857 } else {
858 CLOGE("RequestID does not exist in metadata");
859 return BAD_VALUE;
860 }
861
Jianing Wei90e59c92014-03-12 18:29:36 -0700862 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700863
864 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700866 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
867 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
868 return BAD_VALUE;
869 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700870
871 // Setup batch size if this is a high speed video recording request.
872 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
873 auto firstRequest = requestList->begin();
874 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
875 if (outputStream->isVideoStream()) {
876 (*firstRequest)->mBatchSize = requestList->size();
877 break;
878 }
879 }
880 }
881
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 return OK;
883}
884
Jianing Weicb0652e2014-03-12 18:29:36 -0700885status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800886 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800887
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700888 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700889 std::list<const SurfaceMap> surfaceMaps;
890 convertToRequestList(requests, surfaceMaps, request);
891
892 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
893}
894
895void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
896 std::list<const SurfaceMap>& surfaceMaps,
897 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700898 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899
900 SurfaceMap surfaceMap;
901 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
902 // With no surface list passed in, stream and surface will have 1-to-1
903 // mapping. So the surface index is 0 for each stream in the surfaceMap.
904 for (size_t i = 0; i < streams.count; i++) {
905 surfaceMap[streams.data.i32[i]].push_back(0);
906 }
907 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800908}
909
Jianing Wei90e59c92014-03-12 18:29:36 -0700910status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700911 const List<const CameraMetadata> &requests,
912 const std::list<const SurfaceMap> &surfaceMaps,
913 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700914 /*out*/
915 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700916 ATRACE_CALL();
917 Mutex::Autolock il(mInterfaceLock);
918 Mutex::Autolock l(mLock);
919
920 status_t res = checkStatusOkToCaptureLocked();
921 if (res != OK) {
922 // error logged by previous call
923 return res;
924 }
925
926 RequestList requestList;
927
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
929 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700930 if (res != OK) {
931 // error logged by previous call
932 return res;
933 }
934
935 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700936 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700937 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700938 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700939 }
940
941 if (res == OK) {
942 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
943 if (res != OK) {
944 SET_ERR_L("Can't transition to active in %f seconds!",
945 kActiveTimeout/1e9);
946 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800947 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700948 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700949 } else {
950 CLOGE("Cannot queue request. Impossible.");
951 return BAD_VALUE;
952 }
953
954 return res;
955}
956
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800957
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800958hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800959 const hardware::hidl_vec<
960 hardware::camera::device::V3_2::CaptureResult>& results) {
961 for (const auto& result : results) {
962 processOneCaptureResult(result);
963 }
964 return hardware::Void();
965}
966
967void Camera3Device::processOneCaptureResult(
968 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800969 camera3_capture_result r;
970 status_t res;
971 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800972 if (result.result.size() != 0) {
973 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
974 size_t expected_metadata_size = result.result.size();
975 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
976 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
977 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800978 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800979 }
980 } else {
981 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800982 }
983
984 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
985 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
986 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
987 auto& bDst = outputBuffers[i];
988 const StreamBuffer &bSrc = result.outputBuffers[i];
989
990 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100991 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800992 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
993 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800994 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 }
996 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
997
998 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800999 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 if (res != OK) {
1001 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1002 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001003 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001004 }
1005 bDst.buffer = buffer;
1006 bDst.status = mapHidlBufferStatus(bSrc.status);
1007 bDst.acquire_fence = -1;
1008 if (bSrc.releaseFence == nullptr) {
1009 bDst.release_fence = -1;
1010 } else if (bSrc.releaseFence->numFds == 1) {
1011 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1012 } else {
1013 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1014 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001015 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 }
1017 }
1018 r.num_output_buffers = outputBuffers.size();
1019 r.output_buffers = outputBuffers.data();
1020
1021 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001022 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023 r.input_buffer = nullptr;
1024 } else {
1025 if (mInputStream->getId() != result.inputBuffer.streamId) {
1026 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1027 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001028 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001029 }
1030 inputBuffer.stream = mInputStream->asHalStream();
1031 buffer_handle_t *buffer;
1032 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1033 &buffer);
1034 if (res != OK) {
1035 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1036 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001037 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001038 }
1039 inputBuffer.buffer = buffer;
1040 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1041 inputBuffer.acquire_fence = -1;
1042 if (result.inputBuffer.releaseFence == nullptr) {
1043 inputBuffer.release_fence = -1;
1044 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1045 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1046 } else {
1047 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1048 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001050 }
1051 r.input_buffer = &inputBuffer;
1052 }
1053
1054 r.partial_result = result.partialResult;
1055
1056 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001057}
1058
1059hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001060 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1061 for (const auto& msg : msgs) {
1062 notify(msg);
1063 }
1064 return hardware::Void();
1065}
1066
1067void Camera3Device::notify(
1068 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1069
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001070 camera3_notify_msg m;
1071 switch (msg.type) {
1072 case MsgType::ERROR:
1073 m.type = CAMERA3_MSG_ERROR;
1074 m.message.error.frame_number = msg.msg.error.frameNumber;
1075 if (msg.msg.error.errorStreamId >= 0) {
1076 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001077 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001078 ALOGE("%s: Frame %d: Invalid error stream id %d",
1079 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001080 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001081 }
1082 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1083 } else {
1084 m.message.error.error_stream = nullptr;
1085 }
1086 switch (msg.msg.error.errorCode) {
1087 case ErrorCode::ERROR_DEVICE:
1088 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1089 break;
1090 case ErrorCode::ERROR_REQUEST:
1091 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1092 break;
1093 case ErrorCode::ERROR_RESULT:
1094 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1095 break;
1096 case ErrorCode::ERROR_BUFFER:
1097 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1098 break;
1099 }
1100 break;
1101 case MsgType::SHUTTER:
1102 m.type = CAMERA3_MSG_SHUTTER;
1103 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1104 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1105 break;
1106 }
1107 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001108}
1109
Jianing Weicb0652e2014-03-12 18:29:36 -07001110status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001111 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001112 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001113 ATRACE_CALL();
1114
Shuzhen Wang0129d522016-10-30 22:43:41 -07001115 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001116}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001117
Jianing Weicb0652e2014-03-12 18:29:36 -07001118status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1119 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001120 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001121
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001122 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001123 std::list<const SurfaceMap> surfaceMaps;
1124 convertToRequestList(requests, surfaceMaps, request);
1125
1126 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1127 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128}
1129
Jianing Weicb0652e2014-03-12 18:29:36 -07001130status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001131 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001132 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001133 ATRACE_CALL();
1134
Shuzhen Wang0129d522016-10-30 22:43:41 -07001135 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001136}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137
1138sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001139 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001140 status_t res;
1141
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001142 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001143 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1144 // so unilaterally select normal operating mode.
1145 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001146 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001147 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001148 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001150 } else if (mStatus == STATUS_UNCONFIGURED) {
1151 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001152 CLOGE("No streams configured");
1153 return NULL;
1154 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001155 }
1156
Shuzhen Wang0129d522016-10-30 22:43:41 -07001157 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001159}
1160
Jianing Weicb0652e2014-03-12 18:29:36 -07001161status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001162 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001164 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001165
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001166 switch (mStatus) {
1167 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001168 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001169 return INVALID_OPERATION;
1170 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001171 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001172 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 case STATUS_UNCONFIGURED:
1174 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 case STATUS_ACTIVE:
1176 // OK
1177 break;
1178 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001179 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001180 return INVALID_OPERATION;
1181 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001182 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001183
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001184 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001185}
1186
1187status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1188 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001190
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001191 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001192}
1193
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001194status_t Camera3Device::createInputStream(
1195 uint32_t width, uint32_t height, int format, int *id) {
1196 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001197 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001198 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001199 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1200 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001201
1202 status_t res;
1203 bool wasActive = false;
1204
1205 switch (mStatus) {
1206 case STATUS_ERROR:
1207 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1208 return INVALID_OPERATION;
1209 case STATUS_UNINITIALIZED:
1210 ALOGE("%s: Device not initialized", __FUNCTION__);
1211 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 case STATUS_UNCONFIGURED:
1213 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001214 // OK
1215 break;
1216 case STATUS_ACTIVE:
1217 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001218 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001219 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001221 return res;
1222 }
1223 wasActive = true;
1224 break;
1225 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001227 return INVALID_OPERATION;
1228 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001229 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001230
1231 if (mInputStream != 0) {
1232 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1233 return INVALID_OPERATION;
1234 }
1235
1236 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1237 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001238 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001239
1240 mInputStream = newStream;
1241
1242 *id = mNextStreamId++;
1243
1244 // Continue captures if active at start
1245 if (wasActive) {
1246 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001247 // Reuse current operating mode for new stream config
1248 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001249 if (res != OK) {
1250 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1251 __FUNCTION__, mNextStreamId, strerror(-res), res);
1252 return res;
1253 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255 }
1256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001257 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001258 return OK;
1259}
1260
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001261status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001262 uint32_t width, uint32_t height, int format,
1263 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001264 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001265 ATRACE_CALL();
1266
1267 if (consumer == nullptr) {
1268 ALOGE("%s: consumer must not be null", __FUNCTION__);
1269 return BAD_VALUE;
1270 }
1271
1272 std::vector<sp<Surface>> consumers;
1273 consumers.push_back(consumer);
1274
1275 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001276 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001277}
1278
1279status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1280 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1281 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001282 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001287 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1288 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001289
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 status_t res;
1291 bool wasActive = false;
1292
1293 switch (mStatus) {
1294 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001295 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 return INVALID_OPERATION;
1297 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001298 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 case STATUS_UNCONFIGURED:
1301 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 // OK
1303 break;
1304 case STATUS_ACTIVE:
1305 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001307 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001308 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 return res;
1310 }
1311 wasActive = true;
1312 break;
1313 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001314 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001315 return INVALID_OPERATION;
1316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318
1319 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001320 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001321 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001322 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001323 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1324 }
Zhijun He5d677d12016-05-29 16:52:39 -07001325
Shuzhen Wang0129d522016-10-30 22:43:41 -07001326 if (consumers.size() == 0 && !hasDeferredConsumer) {
1327 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1328 return BAD_VALUE;
1329 }
Zhijun He5d677d12016-05-29 16:52:39 -07001330 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1331 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001332 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001333 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1334 return BAD_VALUE;
1335 }
1336
Shuzhen Wang0129d522016-10-30 22:43:41 -07001337 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001338 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1339 return BAD_VALUE;
1340 }
1341
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001342 // Use legacy dataspace values for older HALs
1343 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1344 dataSpace = mapToLegacyDataspace(dataSpace);
1345 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001346 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001347 ssize_t blobBufferSize;
1348 if (dataSpace != HAL_DATASPACE_DEPTH) {
1349 blobBufferSize = getJpegBufferSize(width, height);
1350 if (blobBufferSize <= 0) {
1351 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1352 return BAD_VALUE;
1353 }
1354 } else {
1355 blobBufferSize = getPointCloudBufferSize();
1356 if (blobBufferSize <= 0) {
1357 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1358 return BAD_VALUE;
1359 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001360 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001361 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001362 width, height, blobBufferSize, format, dataSpace, rotation,
1363 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001364 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1365 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1366 if (rawOpaqueBufferSize <= 0) {
1367 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1368 return BAD_VALUE;
1369 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001370 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001371 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1372 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001373 } else if (isShared) {
1374 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1375 width, height, format, consumerUsage, dataSpace, rotation,
1376 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001377 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001378 newStream = new Camera3OutputStream(mNextStreamId,
1379 width, height, format, consumerUsage, dataSpace, rotation,
1380 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001382 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001383 width, height, format, dataSpace, rotation,
1384 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387
Zhijun He125684a2015-12-26 15:07:30 -08001388 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001389 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1390 * requires buffers to be statically allocated for internal static buffer registration, while
1391 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1392 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001393 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001394 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001395 newStream->setBufferManager(mBufferManager);
1396 }
1397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 res = mOutputStreams.add(mNextStreamId, newStream);
1399 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001400 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001401 return res;
1402 }
1403
1404 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001405 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406
1407 // Continue captures if active at start
1408 if (wasActive) {
1409 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001410 // Reuse current operating mode for new stream config
1411 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001413 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1414 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 return res;
1416 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001417 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001418 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001419 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421}
1422
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001423status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001424 uint32_t *width, uint32_t *height,
1425 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001426 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001427 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001429
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 switch (mStatus) {
1431 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001432 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 return INVALID_OPERATION;
1434 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001435 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001436 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001437 case STATUS_UNCONFIGURED:
1438 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 case STATUS_ACTIVE:
1440 // OK
1441 break;
1442 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001444 return INVALID_OPERATION;
1445 }
1446
1447 ssize_t idx = mOutputStreams.indexOfKey(id);
1448 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001449 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 return idx;
1451 }
1452
1453 if (width) *width = mOutputStreams[idx]->getWidth();
1454 if (height) *height = mOutputStreams[idx]->getHeight();
1455 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001456 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001458}
1459
1460status_t Camera3Device::setStreamTransform(int id,
1461 int transform) {
1462 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001463 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001465
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 switch (mStatus) {
1467 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001468 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return INVALID_OPERATION;
1470 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001471 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001473 case STATUS_UNCONFIGURED:
1474 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 case STATUS_ACTIVE:
1476 // OK
1477 break;
1478 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return INVALID_OPERATION;
1481 }
1482
1483 ssize_t idx = mOutputStreams.indexOfKey(id);
1484 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001485 CLOGE("Stream %d does not exist",
1486 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return BAD_VALUE;
1488 }
1489
1490 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001491}
1492
1493status_t Camera3Device::deleteStream(int id) {
1494 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 Mutex::Autolock l(mLock);
1497 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001498
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001499 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001500
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 // CameraDevice semantics require device to already be idle before
1502 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001503 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001504 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001505 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 }
1507
Igor Murashkin2fba5842013-04-22 14:03:54 -07001508 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001509 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 if (mInputStream != NULL && id == mInputStream->getId()) {
1511 deletedStream = mInputStream;
1512 mInputStream.clear();
1513 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001514 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001515 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 return BAD_VALUE;
1517 }
Zhijun He5f446352014-01-22 09:49:33 -08001518 }
1519
1520 // Delete output stream or the output part of a bi-directional stream.
1521 if (outputStreamIdx != NAME_NOT_FOUND) {
1522 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 mOutputStreams.removeItem(id);
1524 }
1525
1526 // Free up the stream endpoint so that it can be used by some other stream
1527 res = deletedStream->disconnect();
1528 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 // fall through since we want to still list the stream as deleted.
1531 }
1532 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001533 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534
1535 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001536}
1537
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001538status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001539 ATRACE_CALL();
1540 ALOGV("%s: E", __FUNCTION__);
1541
1542 Mutex::Autolock il(mInterfaceLock);
1543 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001544
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001545 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001546}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001548status_t Camera3Device::getInputBufferProducer(
1549 sp<IGraphicBufferProducer> *producer) {
1550 Mutex::Autolock il(mInterfaceLock);
1551 Mutex::Autolock l(mLock);
1552
1553 if (producer == NULL) {
1554 return BAD_VALUE;
1555 } else if (mInputStream == NULL) {
1556 return INVALID_OPERATION;
1557 }
1558
1559 return mInputStream->getInputBufferProducer(producer);
1560}
1561
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562status_t Camera3Device::createDefaultRequest(int templateId,
1563 CameraMetadata *request) {
1564 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001565 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001566
1567 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1568 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1569 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1570 return BAD_VALUE;
1571 }
1572
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 Mutex::Autolock l(mLock);
1575
1576 switch (mStatus) {
1577 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001578 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return INVALID_OPERATION;
1580 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001581 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001582 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 case STATUS_UNCONFIGURED:
1584 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 case STATUS_ACTIVE:
1586 // OK
1587 break;
1588 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001589 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590 return INVALID_OPERATION;
1591 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001592
Zhijun Hea1530f12014-09-14 12:44:20 -07001593 if (!mRequestTemplateCache[templateId].isEmpty()) {
1594 *request = mRequestTemplateCache[templateId];
1595 return OK;
1596 }
1597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001598 camera_metadata_t *rawRequest;
1599 status_t res = mInterface->constructDefaultRequestSettings(
1600 (camera3_request_template_t) templateId, &rawRequest);
1601 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001602 ALOGI("%s: template %d is not supported on this camera device",
1603 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001604 return res;
1605 } else if (res != OK) {
1606 CLOGE("Unable to construct request template %d: %s (%d)",
1607 templateId, strerror(-res), res);
1608 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001609 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001610
Emilian Peev71c73a22017-03-21 16:35:51 +00001611 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001612 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001613
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001614 // Derive some new keys for backward compatibility
1615 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1616 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1617 int32_t defaultBoost[1] = {100};
1618 mRequestTemplateCache[templateId].update(
1619 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1620 defaultBoost, 1);
1621 }
1622
1623 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001624 return OK;
1625}
1626
1627status_t Camera3Device::waitUntilDrained() {
1628 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631
Zhijun He69a37482014-03-23 18:44:49 -07001632 return waitUntilDrainedLocked();
1633}
1634
1635status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 switch (mStatus) {
1637 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 ALOGV("%s: Already idle", __FUNCTION__);
1640 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 case STATUS_CONFIGURED:
1642 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 case STATUS_ERROR:
1644 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 break;
1647 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001648 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001649 return INVALID_OPERATION;
1650 }
1651
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001652 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001653 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001654 if (res != OK) {
1655 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1656 res);
1657 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 return res;
1659}
1660
Ruben Brunk183f0562015-08-12 12:55:02 -07001661
1662void Camera3Device::internalUpdateStatusLocked(Status status) {
1663 mStatus = status;
1664 mRecentStatusUpdates.add(mStatus);
1665 mStatusChanged.broadcast();
1666}
1667
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001668// Pause to reconfigure
1669status_t Camera3Device::internalPauseAndWaitLocked() {
1670 mRequestThread->setPaused(true);
1671 mPauseStateNotify = true;
1672
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001673 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001674 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1675 if (res != OK) {
1676 SET_ERR_L("Can't idle device in %f seconds!",
1677 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001678 }
1679
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001680 return res;
1681}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001682
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683// Resume after internalPauseAndWaitLocked
1684status_t Camera3Device::internalResumeLocked() {
1685 status_t res;
1686
1687 mRequestThread->setPaused(false);
1688
1689 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1690 if (res != OK) {
1691 SET_ERR_L("Can't transition to active in %f seconds!",
1692 kActiveTimeout/1e9);
1693 }
1694 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001695 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696}
1697
Ruben Brunk183f0562015-08-12 12:55:02 -07001698status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001699 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001700
1701 size_t startIndex = 0;
1702 if (mStatusWaiters == 0) {
1703 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1704 // this status list
1705 mRecentStatusUpdates.clear();
1706 } else {
1707 // If other threads are waiting on updates to this status list, set the position of the
1708 // first element that this list will check rather than clearing the list.
1709 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001710 }
1711
Ruben Brunk183f0562015-08-12 12:55:02 -07001712 mStatusWaiters++;
1713
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001714 bool stateSeen = false;
1715 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001716 if (active == (mStatus == STATUS_ACTIVE)) {
1717 // Desired state is current
1718 break;
1719 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001720
1721 res = mStatusChanged.waitRelative(mLock, timeout);
1722 if (res != OK) break;
1723
Ruben Brunk183f0562015-08-12 12:55:02 -07001724 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1725 // transitions.
1726 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1727 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1728 __FUNCTION__);
1729
1730 // Encountered desired state since we began waiting
1731 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001732 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1733 stateSeen = true;
1734 break;
1735 }
1736 }
1737 } while (!stateSeen);
1738
Ruben Brunk183f0562015-08-12 12:55:02 -07001739 mStatusWaiters--;
1740
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001741 return res;
1742}
1743
1744
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001745status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001747 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001749 if (listener != NULL && mListener != NULL) {
1750 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1751 }
1752 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001753 mRequestThread->setNotificationListener(listener);
1754 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001755
1756 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757}
1758
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001759bool Camera3Device::willNotify3A() {
1760 return false;
1761}
1762
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001763status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001764 status_t res;
1765 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001766
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001767 while (mResultQueue.empty()) {
1768 res = mResultSignal.waitRelative(mOutputLock, timeout);
1769 if (res == TIMED_OUT) {
1770 return res;
1771 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001772 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1773 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001774 return res;
1775 }
1776 }
1777 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001778}
1779
Jianing Weicb0652e2014-03-12 18:29:36 -07001780status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001781 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001782 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001784 if (mResultQueue.empty()) {
1785 return NOT_ENOUGH_DATA;
1786 }
1787
Jianing Weicb0652e2014-03-12 18:29:36 -07001788 if (frame == NULL) {
1789 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1790 return BAD_VALUE;
1791 }
1792
1793 CaptureResult &result = *(mResultQueue.begin());
1794 frame->mResultExtras = result.mResultExtras;
1795 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001796 mResultQueue.erase(mResultQueue.begin());
1797
1798 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001799}
1800
1801status_t Camera3Device::triggerAutofocus(uint32_t id) {
1802 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001804
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001805 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1806 // Mix-in this trigger into the next request and only the next request.
1807 RequestTrigger trigger[] = {
1808 {
1809 ANDROID_CONTROL_AF_TRIGGER,
1810 ANDROID_CONTROL_AF_TRIGGER_START
1811 },
1812 {
1813 ANDROID_CONTROL_AF_TRIGGER_ID,
1814 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001815 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001816 };
1817
1818 return mRequestThread->queueTrigger(trigger,
1819 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820}
1821
1822status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1823 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001826 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1827 // Mix-in this trigger into the next request and only the next request.
1828 RequestTrigger trigger[] = {
1829 {
1830 ANDROID_CONTROL_AF_TRIGGER,
1831 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1832 },
1833 {
1834 ANDROID_CONTROL_AF_TRIGGER_ID,
1835 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001836 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001837 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001838
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001839 return mRequestThread->queueTrigger(trigger,
1840 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001841}
1842
1843status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1844 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001847 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1848 // Mix-in this trigger into the next request and only the next request.
1849 RequestTrigger trigger[] = {
1850 {
1851 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1852 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1853 },
1854 {
1855 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1856 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001857 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001858 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001859
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001860 return mRequestThread->queueTrigger(trigger,
1861 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001862}
1863
Jianing Weicb0652e2014-03-12 18:29:36 -07001864status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001865 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001866 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001868
Zhijun He7ef20392014-04-21 16:04:17 -07001869 {
1870 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001871 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001872 }
1873
Zhijun He491e3412013-12-27 10:57:44 -08001874 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001875 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001876 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001877 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001878 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001879 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001880 }
1881
1882 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001883}
1884
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001885status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001886 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1887}
1888
1889status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001891 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001892 Mutex::Autolock il(mInterfaceLock);
1893 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001894
1895 sp<Camera3StreamInterface> stream;
1896 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1897 if (outputStreamIdx == NAME_NOT_FOUND) {
1898 CLOGE("Stream %d does not exist", streamId);
1899 return BAD_VALUE;
1900 }
1901
1902 stream = mOutputStreams.editValueAt(outputStreamIdx);
1903
1904 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001905 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001906 return BAD_VALUE;
1907 }
1908
1909 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001910 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001911 return BAD_VALUE;
1912 }
1913
Ruben Brunkc78ac262015-08-13 17:58:46 -07001914 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001915}
1916
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001917status_t Camera3Device::tearDown(int streamId) {
1918 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001919 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001920 Mutex::Autolock il(mInterfaceLock);
1921 Mutex::Autolock l(mLock);
1922
1923 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1924 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001925 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001926 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001927 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001928 return NO_INIT;
1929 }
1930
1931 sp<Camera3StreamInterface> stream;
1932 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1933 if (outputStreamIdx == NAME_NOT_FOUND) {
1934 CLOGE("Stream %d does not exist", streamId);
1935 return BAD_VALUE;
1936 }
1937
1938 stream = mOutputStreams.editValueAt(outputStreamIdx);
1939
1940 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1941 CLOGE("Stream %d is a target of a in-progress request", streamId);
1942 return BAD_VALUE;
1943 }
1944
1945 return stream->tearDown();
1946}
1947
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001948status_t Camera3Device::addBufferListenerForStream(int streamId,
1949 wp<Camera3StreamBufferListener> listener) {
1950 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001951 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001952 Mutex::Autolock il(mInterfaceLock);
1953 Mutex::Autolock l(mLock);
1954
1955 sp<Camera3StreamInterface> stream;
1956 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1957 if (outputStreamIdx == NAME_NOT_FOUND) {
1958 CLOGE("Stream %d does not exist", streamId);
1959 return BAD_VALUE;
1960 }
1961
1962 stream = mOutputStreams.editValueAt(outputStreamIdx);
1963 stream->addBufferListener(listener);
1964
1965 return OK;
1966}
1967
Zhijun He204e3292014-07-14 17:09:23 -07001968uint32_t Camera3Device::getDeviceVersion() {
1969 ATRACE_CALL();
1970 Mutex::Autolock il(mInterfaceLock);
1971 return mDeviceVersion;
1972}
1973
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001974/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001975 * Methods called by subclasses
1976 */
1977
1978void Camera3Device::notifyStatus(bool idle) {
1979 {
1980 // Need mLock to safely update state and synchronize to current
1981 // state of methods in flight.
1982 Mutex::Autolock l(mLock);
1983 // We can get various system-idle notices from the status tracker
1984 // while starting up. Only care about them if we've actually sent
1985 // in some requests recently.
1986 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1987 return;
1988 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001989 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001990 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001991 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001992
1993 // Skip notifying listener if we're doing some user-transparent
1994 // state changes
1995 if (mPauseStateNotify) return;
1996 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001997
1998 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001999 {
2000 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002001 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002002 }
2003 if (idle && listener != NULL) {
2004 listener->notifyIdle();
2005 }
2006}
2007
Shuzhen Wang758c2152017-01-10 18:26:18 -08002008status_t Camera3Device::setConsumerSurfaces(int streamId,
2009 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07002010 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002011 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2012 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002013 Mutex::Autolock il(mInterfaceLock);
2014 Mutex::Autolock l(mLock);
2015
Shuzhen Wang758c2152017-01-10 18:26:18 -08002016 if (consumers.size() == 0) {
2017 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002018 return BAD_VALUE;
2019 }
2020
2021 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2022 if (idx == NAME_NOT_FOUND) {
2023 CLOGE("Stream %d is unknown", streamId);
2024 return idx;
2025 }
2026 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002027 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002028 if (res != OK) {
2029 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2030 return res;
2031 }
2032
Shuzhen Wang0129d522016-10-30 22:43:41 -07002033 if (stream->isConsumerConfigurationDeferred()) {
2034 if (!stream->isConfiguring()) {
2035 CLOGE("Stream %d was already fully configured.", streamId);
2036 return INVALID_OPERATION;
2037 }
Zhijun He5d677d12016-05-29 16:52:39 -07002038
Shuzhen Wang0129d522016-10-30 22:43:41 -07002039 res = stream->finishConfiguration();
2040 if (res != OK) {
2041 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2042 stream->getId(), strerror(-res), res);
2043 return res;
2044 }
Zhijun He5d677d12016-05-29 16:52:39 -07002045 }
2046
2047 return OK;
2048}
2049
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 * Camera3Device private methods
2052 */
2053
2054sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002055 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 ATRACE_CALL();
2057 status_t res;
2058
2059 sp<CaptureRequest> newRequest = new CaptureRequest;
2060 newRequest->mSettings = request;
2061
2062 camera_metadata_entry_t inputStreams =
2063 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2064 if (inputStreams.count > 0) {
2065 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002066 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002067 CLOGE("Request references unknown input stream %d",
2068 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 return NULL;
2070 }
2071 // Lazy completion of stream configuration (allocation/registration)
2072 // on first use
2073 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002074 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002076 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002077 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002078 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 return NULL;
2080 }
2081 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002082 // Check if stream is being prepared
2083 if (mInputStream->isPreparing()) {
2084 CLOGE("Request references an input stream that's being prepared!");
2085 return NULL;
2086 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087
2088 newRequest->mInputStream = mInputStream;
2089 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2090 }
2091
2092 camera_metadata_entry_t streams =
2093 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2094 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002095 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096 return NULL;
2097 }
2098
2099 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002100 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002101 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002102 CLOGE("Request references unknown stream %d",
2103 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 return NULL;
2105 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002106 sp<Camera3OutputStreamInterface> stream =
2107 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002108
Zhijun He5d677d12016-05-29 16:52:39 -07002109 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002110 auto iter = surfaceMap.find(streams.data.i32[i]);
2111 if (iter != surfaceMap.end()) {
2112 const std::vector<size_t>& surfaces = iter->second;
2113 for (const auto& surface : surfaces) {
2114 if (stream->isConsumerConfigurationDeferred(surface)) {
2115 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2116 "due to deferred consumer", stream->getId(), surface);
2117 return NULL;
2118 }
2119 }
2120 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002121 }
2122
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123 // Lazy completion of stream configuration (allocation/registration)
2124 // on first use
2125 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002126 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002128 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2129 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 return NULL;
2131 }
2132 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002133 // Check if stream is being prepared
2134 if (stream->isPreparing()) {
2135 CLOGE("Request references an output stream that's being prepared!");
2136 return NULL;
2137 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
2139 newRequest->mOutputStreams.push(stream);
2140 }
2141 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002142 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143
2144 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002145}
2146
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002147bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2148 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2149 Size size = mSupportedOpaqueInputSizes[i];
2150 if (size.width == width && size.height == height) {
2151 return true;
2152 }
2153 }
2154
2155 return false;
2156}
2157
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002158void Camera3Device::cancelStreamsConfigurationLocked() {
2159 int res = OK;
2160 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2161 res = mInputStream->cancelConfiguration();
2162 if (res != OK) {
2163 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2164 mInputStream->getId(), strerror(-res), res);
2165 }
2166 }
2167
2168 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2169 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2170 if (outputStream->isConfiguring()) {
2171 res = outputStream->cancelConfiguration();
2172 if (res != OK) {
2173 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2174 outputStream->getId(), strerror(-res), res);
2175 }
2176 }
2177 }
2178
2179 // Return state to that at start of call, so that future configures
2180 // properly clean things up
2181 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2182 mNeedConfig = true;
2183}
2184
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002185status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002186 ATRACE_CALL();
2187 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002188
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002190 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191 return INVALID_OPERATION;
2192 }
2193
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002194 if (operatingMode < 0) {
2195 CLOGE("Invalid operating mode: %d", operatingMode);
2196 return BAD_VALUE;
2197 }
2198
2199 bool isConstrainedHighSpeed =
2200 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2201 operatingMode;
2202
2203 if (mOperatingMode != operatingMode) {
2204 mNeedConfig = true;
2205 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2206 mOperatingMode = operatingMode;
2207 }
2208
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002209 if (!mNeedConfig) {
2210 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2211 return OK;
2212 }
2213
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002214 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2215 // adding a dummy stream instead.
2216 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2217 if (mOutputStreams.size() == 0) {
2218 addDummyStreamLocked();
2219 } else {
2220 tryRemoveDummyStreamLocked();
2221 }
2222
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002224 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225
2226 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002227 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2229
2230 Vector<camera3_stream_t*> streams;
2231 streams.setCapacity(config.num_streams);
2232
2233 if (mInputStream != NULL) {
2234 camera3_stream_t *inputStream;
2235 inputStream = mInputStream->startConfiguration();
2236 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002237 CLOGE("Can't start input stream configuration");
2238 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 return INVALID_OPERATION;
2240 }
2241 streams.add(inputStream);
2242 }
2243
2244 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002245
2246 // Don't configure bidi streams twice, nor add them twice to the list
2247 if (mOutputStreams[i].get() ==
2248 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2249
2250 config.num_streams--;
2251 continue;
2252 }
2253
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 camera3_stream_t *outputStream;
2255 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2256 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002257 CLOGE("Can't start output stream configuration");
2258 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259 return INVALID_OPERATION;
2260 }
2261 streams.add(outputStream);
2262 }
2263
2264 config.streams = streams.editArray();
2265
2266 // Do the HAL configuration; will potentially touch stream
2267 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002268
2269 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002271 if (res == BAD_VALUE) {
2272 // HAL rejected this set of streams as unsupported, clean up config
2273 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002274 CLOGE("Set of requested inputs/outputs not supported by HAL");
2275 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002276 return BAD_VALUE;
2277 } else if (res != OK) {
2278 // Some other kind of error from configure_streams - this is not
2279 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002280 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2281 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002282 return res;
2283 }
2284
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002285 // Finish all stream configuration immediately.
2286 // TODO: Try to relax this later back to lazy completion, which should be
2287 // faster
2288
Igor Murashkin073f8572013-05-02 14:59:28 -07002289 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002290 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002291 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002292 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002293 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002294 cancelStreamsConfigurationLocked();
2295 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002296 }
2297 }
2298
2299 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002300 sp<Camera3OutputStreamInterface> outputStream =
2301 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002302 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002303 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002304 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002305 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002306 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002307 cancelStreamsConfigurationLocked();
2308 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002309 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002310 }
2311 }
2312
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 // Request thread needs to know to avoid using repeat-last-settings protocol
2314 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002315 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316
Zhijun He90f7c372016-08-16 16:19:43 -07002317 char value[PROPERTY_VALUE_MAX];
2318 property_get("camera.fifo.disable", value, "0");
2319 int32_t disableFifo = atoi(value);
2320 if (disableFifo != 1) {
2321 // Boost priority of request thread to SCHED_FIFO.
2322 pid_t requestThreadTid = mRequestThread->getTid();
2323 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002324 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002325 if (res != OK) {
2326 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2327 strerror(-res), res);
2328 } else {
2329 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2330 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002331 }
2332
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002333 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002334
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002335 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002336
Ruben Brunk183f0562015-08-12 12:55:02 -07002337 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2338 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002339
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002340 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002341
Zhijun He0a210512014-07-24 13:45:15 -07002342 // tear down the deleted streams after configure streams.
2343 mDeletedStreams.clear();
2344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002346}
2347
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002348status_t Camera3Device::addDummyStreamLocked() {
2349 ATRACE_CALL();
2350 status_t res;
2351
2352 if (mDummyStreamId != NO_STREAM) {
2353 // Should never be adding a second dummy stream when one is already
2354 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002355 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2356 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002357 return INVALID_OPERATION;
2358 }
2359
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002360 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002361
2362 sp<Camera3OutputStreamInterface> dummyStream =
2363 new Camera3DummyStream(mNextStreamId);
2364
2365 res = mOutputStreams.add(mNextStreamId, dummyStream);
2366 if (res < 0) {
2367 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2368 return res;
2369 }
2370
2371 mDummyStreamId = mNextStreamId;
2372 mNextStreamId++;
2373
2374 return OK;
2375}
2376
2377status_t Camera3Device::tryRemoveDummyStreamLocked() {
2378 ATRACE_CALL();
2379 status_t res;
2380
2381 if (mDummyStreamId == NO_STREAM) return OK;
2382 if (mOutputStreams.size() == 1) return OK;
2383
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002384 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002385
2386 // Ok, have a dummy stream and there's at least one other output stream,
2387 // so remove the dummy
2388
2389 sp<Camera3StreamInterface> deletedStream;
2390 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2391 if (outputStreamIdx == NAME_NOT_FOUND) {
2392 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2393 return INVALID_OPERATION;
2394 }
2395
2396 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2397 mOutputStreams.removeItemsAt(outputStreamIdx);
2398
2399 // Free up the stream endpoint so that it can be used by some other stream
2400 res = deletedStream->disconnect();
2401 if (res != OK) {
2402 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2403 // fall through since we want to still list the stream as deleted.
2404 }
2405 mDeletedStreams.add(deletedStream);
2406 mDummyStreamId = NO_STREAM;
2407
2408 return res;
2409}
2410
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002411void Camera3Device::setErrorState(const char *fmt, ...) {
2412 Mutex::Autolock l(mLock);
2413 va_list args;
2414 va_start(args, fmt);
2415
2416 setErrorStateLockedV(fmt, args);
2417
2418 va_end(args);
2419}
2420
2421void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2422 Mutex::Autolock l(mLock);
2423 setErrorStateLockedV(fmt, args);
2424}
2425
2426void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2427 va_list args;
2428 va_start(args, fmt);
2429
2430 setErrorStateLockedV(fmt, args);
2431
2432 va_end(args);
2433}
2434
2435void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002436 // Print out all error messages to log
2437 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002438 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002439
2440 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002441 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002442
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002443 mErrorCause = errorCause;
2444
2445 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002446 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002447
2448 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002449 sp<NotificationListener> listener = mListener.promote();
2450 if (listener != NULL) {
2451 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002452 CaptureResultExtras());
2453 }
2454
2455 // Save stack trace. View by dumping it later.
2456 CameraTraces::saveTrace();
2457 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002458}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459
2460/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002461 * In-flight request management
2462 */
2463
Jianing Weicb0652e2014-03-12 18:29:36 -07002464status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002465 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002466 const AeTriggerCancelOverride_t &aeTriggerCancelOverride,
2467 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002468 ATRACE_CALL();
2469 Mutex::Autolock l(mInFlightLock);
2470
2471 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002472 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002473 aeTriggerCancelOverride, hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002474 if (res < 0) return res;
2475
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002476 if (mInFlightMap.size() == 1) {
2477 mStatusTracker->markComponentActive(mInFlightStatusId);
2478 }
2479
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002480 return OK;
2481}
2482
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002483void Camera3Device::returnOutputBuffers(
2484 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2485 nsecs_t timestamp) {
2486 for (size_t i = 0; i < numBuffers; i++)
2487 {
2488 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2489 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2490 // Note: stream may be deallocated at this point, if this buffer was
2491 // the last reference to it.
2492 if (res != OK) {
2493 ALOGE("Can't return buffer to its stream: %s (%d)",
2494 strerror(-res), res);
2495 }
2496 }
2497}
2498
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002499void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2500 mInFlightMap.removeItemsAt(idx, 1);
2501
2502 // Indicate idle inFlightMap to the status tracker
2503 if (mInFlightMap.size() == 0) {
2504 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2505 }
2506}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002507
2508void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2509
2510 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2511 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2512
2513 nsecs_t sensorTimestamp = request.sensorTimestamp;
2514 nsecs_t shutterTimestamp = request.shutterTimestamp;
2515
2516 // Check if it's okay to remove the request from InFlightMap:
2517 // In the case of a successful request:
2518 // all input and output buffers, all result metadata, shutter callback
2519 // arrived.
2520 // In the case of a unsuccessful request:
2521 // all input and output buffers arrived.
2522 if (request.numBuffersLeft == 0 &&
2523 (request.requestStatus != OK ||
2524 (request.haveResultMetadata && shutterTimestamp != 0))) {
2525 ATRACE_ASYNC_END("frame capture", frameNumber);
2526
Shuzhen Wang403044a2017-02-26 23:29:04 -08002527 // Sanity check - if sensor timestamp matches shutter timestamp in the
2528 // case of request having callback.
2529 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002530 sensorTimestamp != shutterTimestamp) {
2531 SET_ERR("sensor timestamp (%" PRId64
2532 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2533 sensorTimestamp, frameNumber, shutterTimestamp);
2534 }
2535
2536 // for an unsuccessful request, it may have pending output buffers to
2537 // return.
2538 assert(request.requestStatus != OK ||
2539 request.pendingOutputBuffers.size() == 0);
2540 returnOutputBuffers(request.pendingOutputBuffers.array(),
2541 request.pendingOutputBuffers.size(), 0);
2542
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002543 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002544 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2545 }
2546
2547 // Sanity check - if we have too many in-flight frames, something has
2548 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002549 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002550 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002551 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2552 kInFlightWarnLimitHighSpeed) {
2553 CLOGE("In-flight list too large for high speed configuration: %zu",
2554 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002555 }
2556}
2557
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002558void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2559 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2560 if (result == nullptr) return;
2561
Emilian Peev71c73a22017-03-21 16:35:51 +00002562 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2563 result->mMetadata.getAndLock());
2564 set_camera_metadata_vendor_id(meta, mVendorTagId);
2565 result->mMetadata.unlock(meta);
2566
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002567 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2568 (int32_t*)&frameNumber, 1) != OK) {
2569 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2570 return;
2571 }
2572
2573 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2574 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2575 return;
2576 }
2577
2578 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2579
2580 // Valid result, insert into queue
2581 List<CaptureResult>::iterator queuedResult =
2582 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2583 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2584 ", burstId = %" PRId32, __FUNCTION__,
2585 queuedResult->mResultExtras.requestId,
2586 queuedResult->mResultExtras.frameNumber,
2587 queuedResult->mResultExtras.burstId);
2588
2589 mResultSignal.signal();
2590}
2591
2592
2593void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2594 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2595 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2596 Mutex::Autolock l(mOutputLock);
2597
2598 CaptureResult captureResult;
2599 captureResult.mResultExtras = resultExtras;
2600 captureResult.mMetadata = partialResult;
2601
2602 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2603}
2604
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002605
2606void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2607 CaptureResultExtras &resultExtras,
2608 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002609 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002610 bool reprocess,
2611 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002612 if (pendingMetadata.isEmpty())
2613 return;
2614
2615 Mutex::Autolock l(mOutputLock);
2616
2617 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002618 if (reprocess) {
2619 if (frameNumber < mNextReprocessResultFrameNumber) {
2620 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002621 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002622 frameNumber, mNextReprocessResultFrameNumber);
2623 return;
2624 }
2625 mNextReprocessResultFrameNumber = frameNumber + 1;
2626 } else {
2627 if (frameNumber < mNextResultFrameNumber) {
2628 SET_ERR("Out-of-order capture result metadata submitted! "
2629 "(got frame number %d, expecting %d)",
2630 frameNumber, mNextResultFrameNumber);
2631 return;
2632 }
2633 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002634 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002635
2636 CaptureResult captureResult;
2637 captureResult.mResultExtras = resultExtras;
2638 captureResult.mMetadata = pendingMetadata;
2639
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002640 // Append any previous partials to form a complete result
2641 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2642 captureResult.mMetadata.append(collectedPartialResult);
2643 }
2644
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002645 // Derive some new keys for backward compaibility
2646 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2647 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2648 int32_t defaultBoost[1] = {100};
2649 captureResult.mMetadata.update(
2650 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2651 defaultBoost, 1);
2652 }
2653
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002654 captureResult.mMetadata.sort();
2655
2656 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002657 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2658 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002659 SET_ERR("No timestamp provided by HAL for frame %d!",
2660 frameNumber);
2661 return;
2662 }
2663
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002664 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2665 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2666
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002667 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002668}
2669
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002670/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671 * Camera HAL device callback methods
2672 */
2673
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002674void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002675 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002676
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002677 status_t res;
2678
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002679 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002680 if (result->result == NULL && result->num_output_buffers == 0 &&
2681 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002682 SET_ERR("No result data provided by HAL for frame %d",
2683 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002684 return;
2685 }
Zhijun He204e3292014-07-14 17:09:23 -07002686
2687 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2688 // partial_result to 1 when metadata is included in this result.
2689 if (!mUsePartialResult &&
2690 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2691 result->result != NULL &&
2692 result->partial_result != 1) {
2693 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2694 " if partial result is not supported",
2695 frameNumber, result->partial_result);
2696 return;
2697 }
2698
2699 bool isPartialResult = false;
2700 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002701 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002702 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002703
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002704 // Get shutter timestamp and resultExtras from list of in-flight requests,
2705 // where it was added by the shutter notification for this frame. If the
2706 // shutter timestamp isn't received yet, append the output buffers to the
2707 // in-flight request and they will be returned when the shutter timestamp
2708 // arrives. Update the in-flight status and remove the in-flight entry if
2709 // all result data and shutter timestamp have been received.
2710 nsecs_t shutterTimestamp = 0;
2711
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002712 {
2713 Mutex::Autolock l(mInFlightLock);
2714 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2715 if (idx == NAME_NOT_FOUND) {
2716 SET_ERR("Unknown frame number for capture result: %d",
2717 frameNumber);
2718 return;
2719 }
2720 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002721 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2722 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002723 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002724 __FUNCTION__, request.resultExtras.requestId,
2725 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002726 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002727 // Always update the partial count to the latest one if it's not 0
2728 // (buffers only). When framework aggregates adjacent partial results
2729 // into one, the latest partial count will be used.
2730 if (result->partial_result != 0)
2731 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002732
2733 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002734 if (mUsePartialResult && result->result != NULL) {
2735 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2736 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2737 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2738 " the range of [1, %d] when metadata is included in the result",
2739 frameNumber, result->partial_result, mNumPartialResults);
2740 return;
2741 }
2742 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002743 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002744 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002745 }
Zhijun He204e3292014-07-14 17:09:23 -07002746 } else {
2747 camera_metadata_ro_entry_t partialResultEntry;
2748 res = find_camera_metadata_ro_entry(result->result,
2749 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2750 if (res != NAME_NOT_FOUND &&
2751 partialResultEntry.count > 0 &&
2752 partialResultEntry.data.u8[0] ==
2753 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2754 // A partial result. Flag this as such, and collect this
2755 // set of metadata into the in-flight entry.
2756 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002757 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002758 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002759 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002760 ANDROID_QUIRKS_PARTIAL_RESULT);
2761 }
2762 }
2763
Shuzhen Wang4a472662017-02-26 23:29:04 -08002764 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002765 // Send partial capture result
2766 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2767 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002768 }
2769 }
2770
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002772 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002773
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002774 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002775 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002776 if (request.haveResultMetadata) {
2777 SET_ERR("Called multiple times with metadata for frame %d",
2778 frameNumber);
2779 return;
2780 }
Zhijun He204e3292014-07-14 17:09:23 -07002781 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002782 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002783 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002784 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002785 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002786 request.haveResultMetadata = true;
2787 }
2788
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002789 uint32_t numBuffersReturned = result->num_output_buffers;
2790 if (result->input_buffer != NULL) {
2791 if (hasInputBufferInRequest) {
2792 numBuffersReturned += 1;
2793 } else {
2794 ALOGW("%s: Input buffer should be NULL if there is no input"
2795 " buffer sent in the request",
2796 __FUNCTION__);
2797 }
2798 }
2799 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002800 if (request.numBuffersLeft < 0) {
2801 SET_ERR("Too many buffers returned for frame %d",
2802 frameNumber);
2803 return;
2804 }
2805
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002806 camera_metadata_ro_entry_t entry;
2807 res = find_camera_metadata_ro_entry(result->result,
2808 ANDROID_SENSOR_TIMESTAMP, &entry);
2809 if (res == OK && entry.count == 1) {
2810 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002811 }
2812
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002813 // If shutter event isn't received yet, append the output buffers to
2814 // the in-flight request. Otherwise, return the output buffers to
2815 // streams.
2816 if (shutterTimestamp == 0) {
2817 request.pendingOutputBuffers.appendArray(result->output_buffers,
2818 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002819 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002820 returnOutputBuffers(result->output_buffers,
2821 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002822 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002823
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002824 if (result->result != NULL && !isPartialResult) {
2825 if (shutterTimestamp == 0) {
2826 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002827 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002828 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002829 CameraMetadata metadata;
2830 metadata = result->result;
2831 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002832 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2833 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002834 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002835 }
2836
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002837 removeInFlightRequestIfReadyLocked(idx);
2838 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002839
Zhijun Hef0d962a2014-06-30 10:24:11 -07002840 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002841 if (hasInputBufferInRequest) {
2842 Camera3Stream *stream =
2843 Camera3Stream::cast(result->input_buffer->stream);
2844 res = stream->returnInputBuffer(*(result->input_buffer));
2845 // Note: stream may be deallocated at this point, if this buffer was the
2846 // last reference to it.
2847 if (res != OK) {
2848 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2849 " its stream:%s (%d)", __FUNCTION__,
2850 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002851 }
2852 } else {
2853 ALOGW("%s: Input buffer should be NULL if there is no input"
2854 " buffer sent in the request, skipping input buffer return.",
2855 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002856 }
2857 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002858}
2859
2860void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002861 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002862 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002863 {
2864 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002865 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002866 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002867
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002868 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002869 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002870 return;
2871 }
2872
2873 switch (msg->type) {
2874 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002875 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002876 break;
2877 }
2878 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002879 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002880 break;
2881 }
2882 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002883 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002884 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002885 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002886}
2887
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002888void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002889 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890
2891 // Map camera HAL error codes to ICameraDeviceCallback error codes
2892 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002893 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002894 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002895 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002896 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002897 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002898 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002899 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002900 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002902 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002903 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002904 };
2905
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002906 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002907 ((msg.error_code >= 0) &&
2908 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2909 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002911
2912 int streamId = 0;
2913 if (msg.error_stream != NULL) {
2914 Camera3Stream *stream =
2915 Camera3Stream::cast(msg.error_stream);
2916 streamId = stream->getId();
2917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002918 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2919 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002920 streamId, msg.error_code);
2921
2922 CaptureResultExtras resultExtras;
2923 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002924 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002925 // SET_ERR calls notifyError
2926 SET_ERR("Camera HAL reported serious device error");
2927 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002928 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2929 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2930 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931 {
2932 Mutex::Autolock l(mInFlightLock);
2933 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2934 if (idx >= 0) {
2935 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2936 r.requestStatus = msg.error_code;
2937 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002938 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2939 errorCode) {
2940 // In case of missing result check whether the buffers
2941 // returned. If they returned, then remove inflight
2942 // request.
2943 removeInFlightRequestIfReadyLocked(idx);
2944 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002945 } else {
2946 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002947 ALOGE("Camera %s: %s: cannot find in-flight request on "
2948 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002949 resultExtras.frameNumber);
2950 }
2951 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002952 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002953 if (listener != NULL) {
2954 listener->notifyError(errorCode, resultExtras);
2955 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002956 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002957 }
2958 break;
2959 default:
2960 // SET_ERR calls notifyError
2961 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2962 break;
2963 }
2964}
2965
2966void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002967 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002968 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002969
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 // Set timestamp for the request in the in-flight tracking
2971 // and get the request ID to send upstream
2972 {
2973 Mutex::Autolock l(mInFlightLock);
2974 idx = mInFlightMap.indexOfKey(msg.frame_number);
2975 if (idx >= 0) {
2976 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002977
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002978 // Verify ordering of shutter notifications
2979 {
2980 Mutex::Autolock l(mOutputLock);
2981 // TODO: need to track errors for tighter bounds on expected frame number.
2982 if (r.hasInputBuffer) {
2983 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2984 SET_ERR("Shutter notification out-of-order. Expected "
2985 "notification for frame %d, got frame %d",
2986 mNextReprocessShutterFrameNumber, msg.frame_number);
2987 return;
2988 }
2989 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2990 } else {
2991 if (msg.frame_number < mNextShutterFrameNumber) {
2992 SET_ERR("Shutter notification out-of-order. Expected "
2993 "notification for frame %d, got frame %d",
2994 mNextShutterFrameNumber, msg.frame_number);
2995 return;
2996 }
2997 mNextShutterFrameNumber = msg.frame_number + 1;
2998 }
2999 }
3000
Shuzhen Wang4a472662017-02-26 23:29:04 -08003001 r.shutterTimestamp = msg.timestamp;
3002 if (r.hasCallback) {
3003 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003004 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003005 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003006 // Call listener, if any
3007 if (listener != NULL) {
3008 listener->notifyShutter(r.resultExtras, msg.timestamp);
3009 }
3010 // send pending result and buffers
3011 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3012 r.collectedPartialResult, msg.frame_number,
3013 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003014 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003015 returnOutputBuffers(r.pendingOutputBuffers.array(),
3016 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3017 r.pendingOutputBuffers.clear();
3018
3019 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003020 }
3021 }
3022 if (idx < 0) {
3023 SET_ERR("Shutter notification for non-existent frame number %d",
3024 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003025 }
3026}
3027
3028
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003029CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003030 ALOGV("%s", __FUNCTION__);
3031
Igor Murashkin1e479c02013-09-06 16:55:14 -07003032 CameraMetadata retVal;
3033
3034 if (mRequestThread != NULL) {
3035 retVal = mRequestThread->getLatestRequest();
3036 }
3037
Igor Murashkin1e479c02013-09-06 16:55:14 -07003038 return retVal;
3039}
3040
Jianing Weicb0652e2014-03-12 18:29:36 -07003041
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003042void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3043 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3044 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3045}
3046
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003047/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003048 * HalInterface inner class methods
3049 */
3050
3051Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3052 mHal3Device(device) {}
3053
Yifan Hongf79b5542017-04-11 14:44:25 -07003054Camera3Device::HalInterface::HalInterface(
3055 sp<ICameraDeviceSession> &session,
3056 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003057 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07003058 mHidlSession(session),
3059 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003060
3061Camera3Device::HalInterface::HalInterface() :
3062 mHal3Device(nullptr) {}
3063
3064Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003065 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07003066 mHidlSession(other.mHidlSession),
3067 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003068
3069bool Camera3Device::HalInterface::valid() {
3070 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3071}
3072
3073void Camera3Device::HalInterface::clear() {
3074 mHal3Device = nullptr;
3075 mHidlSession.clear();
3076}
3077
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003078bool Camera3Device::HalInterface::supportBatchRequest() {
3079 return mHidlSession != nullptr;
3080}
3081
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003082status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3083 camera3_request_template_t templateId,
3084 /*out*/ camera_metadata_t **requestTemplate) {
3085 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3086 if (!valid()) return INVALID_OPERATION;
3087 status_t res = OK;
3088
3089 if (mHal3Device != nullptr) {
3090 const camera_metadata *r;
3091 r = mHal3Device->ops->construct_default_request_settings(
3092 mHal3Device, templateId);
3093 if (r == nullptr) return BAD_VALUE;
3094 *requestTemplate = clone_camera_metadata(r);
3095 if (requestTemplate == nullptr) {
3096 ALOGE("%s: Unable to clone camera metadata received from HAL",
3097 __FUNCTION__);
3098 return INVALID_OPERATION;
3099 }
3100 } else {
3101 common::V1_0::Status status;
3102 RequestTemplate id;
3103 switch (templateId) {
3104 case CAMERA3_TEMPLATE_PREVIEW:
3105 id = RequestTemplate::PREVIEW;
3106 break;
3107 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3108 id = RequestTemplate::STILL_CAPTURE;
3109 break;
3110 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3111 id = RequestTemplate::VIDEO_RECORD;
3112 break;
3113 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3114 id = RequestTemplate::VIDEO_SNAPSHOT;
3115 break;
3116 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3117 id = RequestTemplate::ZERO_SHUTTER_LAG;
3118 break;
3119 case CAMERA3_TEMPLATE_MANUAL:
3120 id = RequestTemplate::MANUAL;
3121 break;
3122 default:
3123 // Unknown template ID
3124 return BAD_VALUE;
3125 }
3126 mHidlSession->constructDefaultRequestSettings(id,
3127 [&status, &requestTemplate]
3128 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3129 status = s;
3130 if (status == common::V1_0::Status::OK) {
3131 const camera_metadata *r =
3132 reinterpret_cast<const camera_metadata_t*>(request.data());
3133 size_t expectedSize = request.size();
3134 int ret = validate_camera_metadata_structure(r, &expectedSize);
3135 if (ret == OK) {
3136 *requestTemplate = clone_camera_metadata(r);
3137 if (*requestTemplate == nullptr) {
3138 ALOGE("%s: Unable to clone camera metadata received from HAL",
3139 __FUNCTION__);
3140 status = common::V1_0::Status::INTERNAL_ERROR;
3141 }
3142 } else {
3143 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3144 status = common::V1_0::Status::INTERNAL_ERROR;
3145 }
3146 }
3147 });
3148 res = CameraProviderManager::mapToStatusT(status);
3149 }
3150 return res;
3151}
3152
3153status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3154 ATRACE_NAME("CameraHal::configureStreams");
3155 if (!valid()) return INVALID_OPERATION;
3156 status_t res = OK;
3157
3158 if (mHal3Device != nullptr) {
3159 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3160 } else {
3161 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003162 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003163 StreamConfiguration requestedConfiguration;
3164 requestedConfiguration.streams.resize(config->num_streams);
3165 for (size_t i = 0; i < config->num_streams; i++) {
3166 Stream &dst = requestedConfiguration.streams[i];
3167 camera3_stream_t *src = config->streams[i];
3168
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003169 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3170 cam3stream->setBufferFreedListener(this);
3171 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172 StreamType streamType;
3173 switch (src->stream_type) {
3174 case CAMERA3_STREAM_OUTPUT:
3175 streamType = StreamType::OUTPUT;
3176 break;
3177 case CAMERA3_STREAM_INPUT:
3178 streamType = StreamType::INPUT;
3179 break;
3180 default:
3181 ALOGE("%s: Stream %d: Unsupported stream type %d",
3182 __FUNCTION__, streamId, config->streams[i]->stream_type);
3183 return BAD_VALUE;
3184 }
3185 dst.id = streamId;
3186 dst.streamType = streamType;
3187 dst.width = src->width;
3188 dst.height = src->height;
3189 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003190 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003191 dst.dataSpace = mapToHidlDataspace(src->data_space);
3192 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003193
3194 activeStreams.insert(streamId);
3195 // Create Buffer ID map if necessary
3196 if (mBufferIdMaps.count(streamId) == 0) {
3197 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3198 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003199 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003200 // remove BufferIdMap for deleted streams
3201 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3202 int streamId = it->first;
3203 bool active = activeStreams.count(streamId) > 0;
3204 if (!active) {
3205 it = mBufferIdMaps.erase(it);
3206 } else {
3207 ++it;
3208 }
3209 }
3210
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003211 res = mapToStreamConfigurationMode(
3212 (camera3_stream_configuration_mode_t) config->operation_mode,
3213 /*out*/ &requestedConfiguration.operationMode);
3214 if (res != OK) {
3215 return res;
3216 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003217
3218 // Invoke configureStreams
3219
3220 HalStreamConfiguration finalConfiguration;
3221 common::V1_0::Status status;
3222 mHidlSession->configureStreams(requestedConfiguration,
3223 [&status, &finalConfiguration]
3224 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3225 finalConfiguration = halConfiguration;
3226 status = s;
3227 });
3228 if (status != common::V1_0::Status::OK ) {
3229 return CameraProviderManager::mapToStatusT(status);
3230 }
3231
3232 // And convert output stream configuration from HIDL
3233
3234 for (size_t i = 0; i < config->num_streams; i++) {
3235 camera3_stream_t *dst = config->streams[i];
3236 int streamId = Camera3Stream::cast(dst)->getId();
3237
3238 // Start scan at i, with the assumption that the stream order matches
3239 size_t realIdx = i;
3240 bool found = false;
3241 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3242 if (finalConfiguration.streams[realIdx].id == streamId) {
3243 found = true;
3244 break;
3245 }
3246 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3247 }
3248 if (!found) {
3249 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3250 __FUNCTION__, streamId);
3251 return INVALID_OPERATION;
3252 }
3253 HalStream &src = finalConfiguration.streams[realIdx];
3254
3255 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3256 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3257 if (dst->format != overrideFormat) {
3258 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3259 streamId, dst->format);
3260 }
3261 } else {
3262 // Override allowed with IMPLEMENTATION_DEFINED
3263 dst->format = overrideFormat;
3264 }
3265
3266 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3267 if (src.producerUsage != 0) {
3268 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3269 __FUNCTION__, streamId);
3270 return INVALID_OPERATION;
3271 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003272 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003273 } else {
3274 // OUTPUT
3275 if (src.consumerUsage != 0) {
3276 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3277 __FUNCTION__, streamId);
3278 return INVALID_OPERATION;
3279 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003280 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003281 }
3282 dst->max_buffers = src.maxBuffers;
3283 }
3284 }
3285 return res;
3286}
3287
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003288void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3289 /*out*/device::V3_2::CaptureRequest* captureRequest,
3290 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3291
3292 if (captureRequest == nullptr || handlesCreated == nullptr) {
3293 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3294 __FUNCTION__, captureRequest, handlesCreated);
3295 return;
3296 }
3297
3298 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003299
3300 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003301
3302 {
3303 std::lock_guard<std::mutex> lock(mInflightLock);
3304 if (request->input_buffer != nullptr) {
3305 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3306 buffer_handle_t buf = *(request->input_buffer->buffer);
3307 auto pair = getBufferId(buf, streamId);
3308 bool isNewBuffer = pair.first;
3309 uint64_t bufferId = pair.second;
3310 captureRequest->inputBuffer.streamId = streamId;
3311 captureRequest->inputBuffer.bufferId = bufferId;
3312 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3313 captureRequest->inputBuffer.status = BufferStatus::OK;
3314 native_handle_t *acquireFence = nullptr;
3315 if (request->input_buffer->acquire_fence != -1) {
3316 acquireFence = native_handle_create(1,0);
3317 acquireFence->data[0] = request->input_buffer->acquire_fence;
3318 handlesCreated->push_back(acquireFence);
3319 }
3320 captureRequest->inputBuffer.acquireFence = acquireFence;
3321 captureRequest->inputBuffer.releaseFence = nullptr;
3322
3323 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3324 request->input_buffer->buffer,
3325 request->input_buffer->acquire_fence);
3326 } else {
3327 captureRequest->inputBuffer.streamId = -1;
3328 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3329 }
3330
3331 captureRequest->outputBuffers.resize(request->num_output_buffers);
3332 for (size_t i = 0; i < request->num_output_buffers; i++) {
3333 const camera3_stream_buffer_t *src = request->output_buffers + i;
3334 StreamBuffer &dst = captureRequest->outputBuffers[i];
3335 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3336 buffer_handle_t buf = *(src->buffer);
3337 auto pair = getBufferId(buf, streamId);
3338 bool isNewBuffer = pair.first;
3339 dst.streamId = streamId;
3340 dst.bufferId = pair.second;
3341 dst.buffer = isNewBuffer ? buf : nullptr;
3342 dst.status = BufferStatus::OK;
3343 native_handle_t *acquireFence = nullptr;
3344 if (src->acquire_fence != -1) {
3345 acquireFence = native_handle_create(1,0);
3346 acquireFence->data[0] = src->acquire_fence;
3347 handlesCreated->push_back(acquireFence);
3348 }
3349 dst.acquireFence = acquireFence;
3350 dst.releaseFence = nullptr;
3351
3352 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3353 src->buffer, src->acquire_fence);
3354 }
3355 }
3356}
3357
3358status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3359 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3360 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3361 if (!valid()) return INVALID_OPERATION;
3362
3363 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3364 size_t batchSize = requests.size();
3365 captureRequests.resize(batchSize);
3366 std::vector<native_handle_t*> handlesCreated;
3367
3368 for (size_t i = 0; i < batchSize; i++) {
3369 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3370 }
3371
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003372 std::vector<device::V3_2::BufferCache> cachesToRemove;
3373 {
3374 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3375 for (auto& pair : mFreedBuffers) {
3376 // The stream might have been removed since onBufferFreed
3377 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3378 cachesToRemove.push_back({pair.first, pair.second});
3379 }
3380 }
3381 mFreedBuffers.clear();
3382 }
3383
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003384 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3385 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003386
3387 // Write metadata to FMQ.
3388 for (size_t i = 0; i < batchSize; i++) {
3389 camera3_capture_request_t* request = requests[i];
3390 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3391
3392 if (request->settings != nullptr) {
3393 size_t settingsSize = get_camera_metadata_size(request->settings);
3394 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3395 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3396 captureRequest->settings.resize(0);
3397 captureRequest->fmqSettingsSize = settingsSize;
3398 } else {
3399 if (mRequestMetadataQueue != nullptr) {
3400 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3401 }
3402 captureRequest->settings.setToExternal(
3403 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3404 get_camera_metadata_size(request->settings));
3405 captureRequest->fmqSettingsSize = 0u;
3406 }
3407 } else {
3408 // A null request settings maps to a size-0 CameraMetadata
3409 captureRequest->settings.resize(0);
3410 captureRequest->fmqSettingsSize = 0u;
3411 }
3412 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003413 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003414 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3415 status = s;
3416 *numRequestProcessed = n;
3417 });
3418
3419 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3420 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3421 __FUNCTION__, *numRequestProcessed, batchSize);
3422 status = common::V1_0::Status::INTERNAL_ERROR;
3423 }
3424
3425 for (auto& handle : handlesCreated) {
3426 native_handle_delete(handle);
3427 }
3428 return CameraProviderManager::mapToStatusT(status);
3429}
3430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003431status_t Camera3Device::HalInterface::processCaptureRequest(
3432 camera3_capture_request_t *request) {
3433 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003434 if (!valid()) return INVALID_OPERATION;
3435 status_t res = OK;
3436
3437 if (mHal3Device != nullptr) {
3438 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3439 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003440 uint32_t numRequestProcessed = 0;
3441 std::vector<camera3_capture_request_t*> requests(1);
3442 requests[0] = request;
3443 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003444 }
3445 return res;
3446}
3447
3448status_t Camera3Device::HalInterface::flush() {
3449 ATRACE_NAME("CameraHal::flush");
3450 if (!valid()) return INVALID_OPERATION;
3451 status_t res = OK;
3452
3453 if (mHal3Device != nullptr) {
3454 res = mHal3Device->ops->flush(mHal3Device);
3455 } else {
3456 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3457 }
3458 return res;
3459}
3460
3461status_t Camera3Device::HalInterface::dump(int fd) {
3462 ATRACE_NAME("CameraHal::dump");
3463 if (!valid()) return INVALID_OPERATION;
3464 status_t res = OK;
3465
3466 if (mHal3Device != nullptr) {
3467 mHal3Device->ops->dump(mHal3Device, fd);
3468 } else {
3469 // Handled by CameraProviderManager::dump
3470 }
3471 return res;
3472}
3473
3474status_t Camera3Device::HalInterface::close() {
3475 ATRACE_NAME("CameraHal::close()");
3476 if (!valid()) return INVALID_OPERATION;
3477 status_t res = OK;
3478
3479 if (mHal3Device != nullptr) {
3480 mHal3Device->common.close(&mHal3Device->common);
3481 } else {
3482 mHidlSession->close();
3483 }
3484 return res;
3485}
3486
3487status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003488 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003489 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003490 auto pair = std::make_pair(buffer, acquireFence);
3491 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492 return OK;
3493}
3494
3495status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003496 int32_t frameNumber, int32_t streamId,
3497 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003498 std::lock_guard<std::mutex> lock(mInflightLock);
3499
3500 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3501 auto it = mInflightBufferMap.find(key);
3502 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003503 auto pair = it->second;
3504 *buffer = pair.first;
3505 int acquireFence = pair.second;
3506 if (acquireFence > 0) {
3507 ::close(acquireFence);
3508 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003509 mInflightBufferMap.erase(it);
3510 return OK;
3511}
3512
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003513std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3514 const buffer_handle_t& buf, int streamId) {
3515 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3516
3517 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3518 auto it = bIdMap.find(buf);
3519 if (it == bIdMap.end()) {
3520 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003521 ALOGV("stream %d now have %zu buffer caches, buf %p",
3522 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003523 return std::make_pair(true, mNextBufferId - 1);
3524 } else {
3525 return std::make_pair(false, it->second);
3526 }
3527}
3528
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003529void Camera3Device::HalInterface::onBufferFreed(
3530 int streamId, const native_handle_t* handle) {
3531 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3532 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3533 auto mapIt = mBufferIdMaps.find(streamId);
3534 if (mapIt == mBufferIdMaps.end()) {
3535 // streamId might be from a deleted stream here
3536 ALOGI("%s: stream %d has been removed",
3537 __FUNCTION__, streamId);
3538 return;
3539 }
3540 BufferIdMap& bIdMap = mapIt->second;
3541 auto it = bIdMap.find(handle);
3542 if (it == bIdMap.end()) {
3543 ALOGW("%s: cannot find buffer %p in stream %d",
3544 __FUNCTION__, handle, streamId);
3545 return;
3546 } else {
3547 bufferId = it->second;
3548 bIdMap.erase(it);
3549 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3550 __FUNCTION__, streamId, bIdMap.size(), handle);
3551 }
3552 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3553}
3554
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003555/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003556 * RequestThread inner class methods
3557 */
3558
3559Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003560 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 HalInterface* interface,
3562 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003563 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003564 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003565 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003566 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003567 mInterface(interface),
3568 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003569 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003570 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003571 mReconfigured(false),
3572 mDoPause(false),
3573 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003574 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003575 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003576 mCurrentAfTriggerId(0),
3577 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003578 mRepeatingLastFrameNumber(
3579 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003580 mAeLockAvailable(aeLockAvailable),
3581 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003582 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003583}
3584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003585Camera3Device::RequestThread::~RequestThread() {}
3586
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003587void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003588 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003589 Mutex::Autolock l(mRequestLock);
3590 mListener = listener;
3591}
3592
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003593void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003594 Mutex::Autolock l(mRequestLock);
3595 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003596 // Prepare video stream for high speed recording.
3597 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003598}
3599
Jianing Wei90e59c92014-03-12 18:29:36 -07003600status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003601 List<sp<CaptureRequest> > &requests,
3602 /*out*/
3603 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003604 Mutex::Autolock l(mRequestLock);
3605 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3606 ++it) {
3607 mRequestQueue.push_back(*it);
3608 }
3609
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003610 if (lastFrameNumber != NULL) {
3611 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3612 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3613 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3614 *lastFrameNumber);
3615 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003616
Jianing Wei90e59c92014-03-12 18:29:36 -07003617 unpauseForNewRequests();
3618
3619 return OK;
3620}
3621
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003622
3623status_t Camera3Device::RequestThread::queueTrigger(
3624 RequestTrigger trigger[],
3625 size_t count) {
3626
3627 Mutex::Autolock l(mTriggerMutex);
3628 status_t ret;
3629
3630 for (size_t i = 0; i < count; ++i) {
3631 ret = queueTriggerLocked(trigger[i]);
3632
3633 if (ret != OK) {
3634 return ret;
3635 }
3636 }
3637
3638 return OK;
3639}
3640
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003641const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3642 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003643 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003644 if (d != nullptr) return d->mId;
3645 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003646}
3647
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003648status_t Camera3Device::RequestThread::queueTriggerLocked(
3649 RequestTrigger trigger) {
3650
3651 uint32_t tag = trigger.metadataTag;
3652 ssize_t index = mTriggerMap.indexOfKey(tag);
3653
3654 switch (trigger.getTagType()) {
3655 case TYPE_BYTE:
3656 // fall-through
3657 case TYPE_INT32:
3658 break;
3659 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003660 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3661 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003662 return INVALID_OPERATION;
3663 }
3664
3665 /**
3666 * Collect only the latest trigger, since we only have 1 field
3667 * in the request settings per trigger tag, and can't send more than 1
3668 * trigger per request.
3669 */
3670 if (index != NAME_NOT_FOUND) {
3671 mTriggerMap.editValueAt(index) = trigger;
3672 } else {
3673 mTriggerMap.add(tag, trigger);
3674 }
3675
3676 return OK;
3677}
3678
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003679status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003680 const RequestList &requests,
3681 /*out*/
3682 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003683 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003684 if (lastFrameNumber != NULL) {
3685 *lastFrameNumber = mRepeatingLastFrameNumber;
3686 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003687 mRepeatingRequests.clear();
3688 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3689 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003690
3691 unpauseForNewRequests();
3692
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003693 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003694 return OK;
3695}
3696
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003697bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003698 if (mRepeatingRequests.empty()) {
3699 return false;
3700 }
3701 int32_t requestId = requestIn->mResultExtras.requestId;
3702 const RequestList &repeatRequests = mRepeatingRequests;
3703 // All repeating requests are guaranteed to have same id so only check first quest
3704 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3705 return (firstRequest->mResultExtras.requestId == requestId);
3706}
3707
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003708status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003709 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003710 return clearRepeatingRequestsLocked(lastFrameNumber);
3711
3712}
3713
3714status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003715 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003716 if (lastFrameNumber != NULL) {
3717 *lastFrameNumber = mRepeatingLastFrameNumber;
3718 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003719 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003720 return OK;
3721}
3722
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003723status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003724 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003725 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003726 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003727
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003728 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003729
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003730 // Send errors for all requests pending in the request queue, including
3731 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003732 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003733 if (listener != NULL) {
3734 for (RequestList::iterator it = mRequestQueue.begin();
3735 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003736 // Abort the input buffers for reprocess requests.
3737 if ((*it)->mInputStream != NULL) {
3738 camera3_stream_buffer_t inputBuffer;
3739 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3740 if (res != OK) {
3741 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3742 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3743 } else {
3744 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3745 if (res != OK) {
3746 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3747 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3748 }
3749 }
3750 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003751 // Set the frame number this request would have had, if it
3752 // had been submitted; this frame number will not be reused.
3753 // The requestId and burstId fields were set when the request was
3754 // submitted originally (in convertMetadataListToRequestListLocked)
3755 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003756 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003757 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003758 }
3759 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003760 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003761
3762 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003763 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003764 if (lastFrameNumber != NULL) {
3765 *lastFrameNumber = mRepeatingLastFrameNumber;
3766 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003767 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003768 return OK;
3769}
3770
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003771status_t Camera3Device::RequestThread::flush() {
3772 ATRACE_CALL();
3773 Mutex::Autolock l(mFlushLock);
3774
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003775 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3776 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003777 }
3778
3779 return -ENOTSUP;
3780}
3781
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003782void Camera3Device::RequestThread::setPaused(bool paused) {
3783 Mutex::Autolock l(mPauseLock);
3784 mDoPause = paused;
3785 mDoPauseSignal.signal();
3786}
3787
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003788status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3789 int32_t requestId, nsecs_t timeout) {
3790 Mutex::Autolock l(mLatestRequestMutex);
3791 status_t res;
3792 while (mLatestRequestId != requestId) {
3793 nsecs_t startTime = systemTime();
3794
3795 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3796 if (res != OK) return res;
3797
3798 timeout -= (systemTime() - startTime);
3799 }
3800
3801 return OK;
3802}
3803
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003804void Camera3Device::RequestThread::requestExit() {
3805 // Call parent to set up shutdown
3806 Thread::requestExit();
3807 // The exit from any possible waits
3808 mDoPauseSignal.signal();
3809 mRequestSignal.signal();
3810}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003811
Chien-Yu Chend196d612015-06-22 19:49:01 -07003812
3813/**
3814 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3815 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3816 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3817 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3818 * request.
3819 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003820void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003821 request->mAeTriggerCancelOverride.applyAeLock = false;
3822 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003824 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003825 return;
3826 }
3827
3828 camera_metadata_entry_t aePrecaptureTrigger =
3829 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3830 if (aePrecaptureTrigger.count > 0 &&
3831 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3832 // Always override CANCEL to IDLE
3833 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3834 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3835 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3836 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3837 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3838
3839 if (mAeLockAvailable == true) {
3840 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3841 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3842 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3843 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3844 request->mAeTriggerCancelOverride.applyAeLock = true;
3845 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3846 }
3847 }
3848 }
3849}
3850
3851/**
3852 * Override result metadata for cancelling AE precapture trigger applied in
3853 * handleAePrecaptureCancelRequest().
3854 */
3855void Camera3Device::overrideResultForPrecaptureCancel(
3856 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3857 if (aeTriggerCancelOverride.applyAeLock) {
3858 // Only devices <= v3.2 should have this override
3859 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3860 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3861 }
3862
3863 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3864 // Only devices <= v3.2 should have this override
3865 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3866 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3867 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3868 }
3869}
3870
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003871void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003872 bool surfaceAbandoned = false;
3873 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003874 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003875 {
3876 Mutex::Autolock l(mRequestLock);
3877 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3878 // repeating requests.
3879 for (const auto& request : mRepeatingRequests) {
3880 for (const auto& s : request->mOutputStreams) {
3881 if (s->isAbandoned()) {
3882 surfaceAbandoned = true;
3883 clearRepeatingRequestsLocked(&lastFrameNumber);
3884 break;
3885 }
3886 }
3887 if (surfaceAbandoned) {
3888 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003889 }
3890 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003891 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003892 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003893
3894 if (listener != NULL && surfaceAbandoned) {
3895 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003896 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003897}
3898
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003899bool Camera3Device::RequestThread::sendRequestsBatch() {
3900 status_t res;
3901 size_t batchSize = mNextRequests.size();
3902 std::vector<camera3_capture_request_t*> requests(batchSize);
3903 uint32_t numRequestProcessed = 0;
3904 for (size_t i = 0; i < batchSize; i++) {
3905 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3906 }
3907
3908 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3909 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3910
3911 bool triggerRemoveFailed = false;
3912 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3913 for (size_t i = 0; i < numRequestProcessed; i++) {
3914 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3915 nextRequest.submitted = true;
3916
3917
3918 // Update the latest request sent to HAL
3919 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3920 Mutex::Autolock al(mLatestRequestMutex);
3921
3922 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3923 mLatestRequest.acquire(cloned);
3924
3925 sp<Camera3Device> parent = mParent.promote();
3926 if (parent != NULL) {
3927 parent->monitorMetadata(TagMonitor::REQUEST,
3928 nextRequest.halRequest.frame_number,
3929 0, mLatestRequest);
3930 }
3931 }
3932
3933 if (nextRequest.halRequest.settings != NULL) {
3934 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3935 }
3936
3937 if (!triggerRemoveFailed) {
3938 // Remove any previously queued triggers (after unlock)
3939 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3940 if (removeTriggerRes != OK) {
3941 triggerRemoveFailed = true;
3942 triggerFailedRequest = nextRequest;
3943 }
3944 }
3945 }
3946
3947 if (triggerRemoveFailed) {
3948 SET_ERR("RequestThread: Unable to remove triggers "
3949 "(capture request %d, HAL device: %s (%d)",
3950 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3951 cleanUpFailedRequests(/*sendRequestError*/ false);
3952 return false;
3953 }
3954
3955 if (res != OK) {
3956 // Should only get a failure here for malformed requests or device-level
3957 // errors, so consider all errors fatal. Bad metadata failures should
3958 // come through notify.
3959 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3960 mNextRequests[numRequestProcessed].halRequest.frame_number,
3961 strerror(-res), res);
3962 cleanUpFailedRequests(/*sendRequestError*/ false);
3963 return false;
3964 }
3965 return true;
3966}
3967
3968bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3969 status_t res;
3970
3971 for (auto& nextRequest : mNextRequests) {
3972 // Submit request and block until ready for next one
3973 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3974 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3975
3976 if (res != OK) {
3977 // Should only get a failure here for malformed requests or device-level
3978 // errors, so consider all errors fatal. Bad metadata failures should
3979 // come through notify.
3980 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3981 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3982 res);
3983 cleanUpFailedRequests(/*sendRequestError*/ false);
3984 return false;
3985 }
3986
3987 // Mark that the request has be submitted successfully.
3988 nextRequest.submitted = true;
3989
3990 // Update the latest request sent to HAL
3991 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3992 Mutex::Autolock al(mLatestRequestMutex);
3993
3994 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3995 mLatestRequest.acquire(cloned);
3996
3997 sp<Camera3Device> parent = mParent.promote();
3998 if (parent != NULL) {
3999 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4000 0, mLatestRequest);
4001 }
4002 }
4003
4004 if (nextRequest.halRequest.settings != NULL) {
4005 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4006 }
4007
4008 // Remove any previously queued triggers (after unlock)
4009 res = removeTriggers(mPrevRequest);
4010 if (res != OK) {
4011 SET_ERR("RequestThread: Unable to remove triggers "
4012 "(capture request %d, HAL device: %s (%d)",
4013 nextRequest.halRequest.frame_number, strerror(-res), res);
4014 cleanUpFailedRequests(/*sendRequestError*/ false);
4015 return false;
4016 }
4017 }
4018 return true;
4019}
4020
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004021bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004022 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004023 status_t res;
4024
4025 // Handle paused state.
4026 if (waitIfPaused()) {
4027 return true;
4028 }
4029
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004030 // Wait for the next batch of requests.
4031 waitForNextRequestBatch();
4032 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004033 return true;
4034 }
4035
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004036 // Get the latest request ID, if any
4037 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004038 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004039 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004040 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004041 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004042 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004043 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4044 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004045 }
4046
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004047 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004048 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004049 if (res == TIMED_OUT) {
4050 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004051 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004052 // Check if any stream is abandoned.
4053 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004054 return true;
4055 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004056 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004057 return false;
4058 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004059
Zhijun Hecc27e112013-10-03 16:12:43 -07004060 // Inform waitUntilRequestProcessed thread of a new request ID
4061 {
4062 Mutex::Autolock al(mLatestRequestMutex);
4063
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004064 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004065 mLatestRequestSignal.signal();
4066 }
4067
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004068 // Submit a batch of requests to HAL.
4069 // Use flush lock only when submitting multilple requests in a batch.
4070 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4071 // which may take a long time to finish so synchronizing flush() and
4072 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4073 // For now, only synchronize for high speed recording and we should figure something out for
4074 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004075 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004076
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004077 if (useFlushLock) {
4078 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004079 }
4080
Zhijun Hef0645c12016-08-02 00:58:11 -07004081 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004082 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004083
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004084 bool submitRequestSuccess = false;
4085 if (mInterface->supportBatchRequest()) {
4086 submitRequestSuccess = sendRequestsBatch();
4087 } else {
4088 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004089 }
4090
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004091 if (useFlushLock) {
4092 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004093 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004094
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004095 // Unset as current request
4096 {
4097 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004098 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004099 }
4100
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004101 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004102}
4103
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004104status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004105 ATRACE_CALL();
4106
Shuzhen Wang4a472662017-02-26 23:29:04 -08004107 for (size_t i = 0; i < mNextRequests.size(); i++) {
4108 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004109 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4110 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4111 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4112
4113 // Prepare a request to HAL
4114 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4115
4116 // Insert any queued triggers (before metadata is locked)
4117 status_t res = insertTriggers(captureRequest);
4118
4119 if (res < 0) {
4120 SET_ERR("RequestThread: Unable to insert triggers "
4121 "(capture request %d, HAL device: %s (%d)",
4122 halRequest->frame_number, strerror(-res), res);
4123 return INVALID_OPERATION;
4124 }
4125 int triggerCount = res;
4126 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4127 mPrevTriggers = triggerCount;
4128
4129 // If the request is the same as last, or we had triggers last time
4130 if (mPrevRequest != captureRequest || triggersMixedIn) {
4131 /**
4132 * HAL workaround:
4133 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4134 */
4135 res = addDummyTriggerIds(captureRequest);
4136 if (res != OK) {
4137 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4138 "(capture request %d, HAL device: %s (%d)",
4139 halRequest->frame_number, strerror(-res), res);
4140 return INVALID_OPERATION;
4141 }
4142
4143 /**
4144 * The request should be presorted so accesses in HAL
4145 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4146 */
4147 captureRequest->mSettings.sort();
4148 halRequest->settings = captureRequest->mSettings.getAndLock();
4149 mPrevRequest = captureRequest;
4150 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4151
4152 IF_ALOGV() {
4153 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4154 find_camera_metadata_ro_entry(
4155 halRequest->settings,
4156 ANDROID_CONTROL_AF_TRIGGER,
4157 &e
4158 );
4159 if (e.count > 0) {
4160 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4161 __FUNCTION__,
4162 halRequest->frame_number,
4163 e.data.u8[0]);
4164 }
4165 }
4166 } else {
4167 // leave request.settings NULL to indicate 'reuse latest given'
4168 ALOGVV("%s: Request settings are REUSED",
4169 __FUNCTION__);
4170 }
4171
4172 uint32_t totalNumBuffers = 0;
4173
4174 // Fill in buffers
4175 if (captureRequest->mInputStream != NULL) {
4176 halRequest->input_buffer = &captureRequest->mInputBuffer;
4177 totalNumBuffers += 1;
4178 } else {
4179 halRequest->input_buffer = NULL;
4180 }
4181
4182 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4183 captureRequest->mOutputStreams.size());
4184 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004185 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4186 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004187
4188 // Prepare video buffers for high speed recording on the first video request.
4189 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4190 // Only try to prepare video stream on the first video request.
4191 mPrepareVideoStream = false;
4192
4193 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4194 while (res == NOT_ENOUGH_DATA) {
4195 res = outputStream->prepareNextBuffer();
4196 }
4197 if (res != OK) {
4198 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4199 __FUNCTION__, strerror(-res), res);
4200 outputStream->cancelPrepare();
4201 }
4202 }
4203
Shuzhen Wang4a472662017-02-26 23:29:04 -08004204 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4205 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004206 if (res != OK) {
4207 // Can't get output buffer from gralloc queue - this could be due to
4208 // abandoned queue or other consumer misbehavior, so not a fatal
4209 // error
4210 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4211 " %s (%d)", strerror(-res), res);
4212
4213 return TIMED_OUT;
4214 }
4215 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004216
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004217 }
4218 totalNumBuffers += halRequest->num_output_buffers;
4219
4220 // Log request in the in-flight queue
4221 sp<Camera3Device> parent = mParent.promote();
4222 if (parent == NULL) {
4223 // Should not happen, and nowhere to send errors to, so just log it
4224 CLOGE("RequestThread: Parent is gone");
4225 return INVALID_OPERATION;
4226 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004227
4228 // If this request list is for constrained high speed recording (not
4229 // preview), and the current request is not the last one in the batch,
4230 // do not send callback to the app.
4231 bool hasCallback = true;
4232 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4233 hasCallback = false;
4234 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004235 res = parent->registerInFlight(halRequest->frame_number,
4236 totalNumBuffers, captureRequest->mResultExtras,
4237 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004238 captureRequest->mAeTriggerCancelOverride,
4239 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004240 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4241 ", burstId = %" PRId32 ".",
4242 __FUNCTION__,
4243 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4244 captureRequest->mResultExtras.burstId);
4245 if (res != OK) {
4246 SET_ERR("RequestThread: Unable to register new in-flight request:"
4247 " %s (%d)", strerror(-res), res);
4248 return INVALID_OPERATION;
4249 }
4250 }
4251
4252 return OK;
4253}
4254
Igor Murashkin1e479c02013-09-06 16:55:14 -07004255CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4256 Mutex::Autolock al(mLatestRequestMutex);
4257
4258 ALOGV("RequestThread::%s", __FUNCTION__);
4259
4260 return mLatestRequest;
4261}
4262
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004263bool Camera3Device::RequestThread::isStreamPending(
4264 sp<Camera3StreamInterface>& stream) {
4265 Mutex::Autolock l(mRequestLock);
4266
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004267 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004268 if (!nextRequest.submitted) {
4269 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4270 if (stream == s) return true;
4271 }
4272 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004273 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004274 }
4275
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004276 for (const auto& request : mRequestQueue) {
4277 for (const auto& s : request->mOutputStreams) {
4278 if (stream == s) return true;
4279 }
4280 if (stream == request->mInputStream) return true;
4281 }
4282
4283 for (const auto& request : mRepeatingRequests) {
4284 for (const auto& s : request->mOutputStreams) {
4285 if (stream == s) return true;
4286 }
4287 if (stream == request->mInputStream) return true;
4288 }
4289
4290 return false;
4291}
Jianing Weicb0652e2014-03-12 18:29:36 -07004292
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004293void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4294 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004295 return;
4296 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004297
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004298 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004299 // Skip the ones that have been submitted successfully.
4300 if (nextRequest.submitted) {
4301 continue;
4302 }
4303
4304 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4305 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4306 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4307
4308 if (halRequest->settings != NULL) {
4309 captureRequest->mSettings.unlock(halRequest->settings);
4310 }
4311
4312 if (captureRequest->mInputStream != NULL) {
4313 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4314 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4315 }
4316
4317 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4318 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4319 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4320 }
4321
4322 if (sendRequestError) {
4323 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004324 sp<NotificationListener> listener = mListener.promote();
4325 if (listener != NULL) {
4326 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004327 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004328 captureRequest->mResultExtras);
4329 }
4330 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004331
4332 // Remove yet-to-be submitted inflight request from inflightMap
4333 {
4334 sp<Camera3Device> parent = mParent.promote();
4335 if (parent != NULL) {
4336 Mutex::Autolock l(parent->mInFlightLock);
4337 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4338 if (idx >= 0) {
4339 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4340 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4341 parent->removeInFlightMapEntryLocked(idx);
4342 }
4343 }
4344 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004346
4347 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004348 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004349}
4350
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004351void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352 // Optimized a bit for the simple steady-state case (single repeating
4353 // request), to avoid putting that request in the queue temporarily.
4354 Mutex::Autolock l(mRequestLock);
4355
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356 assert(mNextRequests.empty());
4357
4358 NextRequest nextRequest;
4359 nextRequest.captureRequest = waitForNextRequestLocked();
4360 if (nextRequest.captureRequest == nullptr) {
4361 return;
4362 }
4363
4364 nextRequest.halRequest = camera3_capture_request_t();
4365 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004366 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004367
4368 // Wait for additional requests
4369 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4370
4371 for (size_t i = 1; i < batchSize; i++) {
4372 NextRequest additionalRequest;
4373 additionalRequest.captureRequest = waitForNextRequestLocked();
4374 if (additionalRequest.captureRequest == nullptr) {
4375 break;
4376 }
4377
4378 additionalRequest.halRequest = camera3_capture_request_t();
4379 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004380 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381 }
4382
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004383 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004384 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004385 mNextRequests.size(), batchSize);
4386 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004387 }
4388
4389 return;
4390}
4391
4392sp<Camera3Device::CaptureRequest>
4393 Camera3Device::RequestThread::waitForNextRequestLocked() {
4394 status_t res;
4395 sp<CaptureRequest> nextRequest;
4396
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004397 while (mRequestQueue.empty()) {
4398 if (!mRepeatingRequests.empty()) {
4399 // Always atomically enqueue all requests in a repeating request
4400 // list. Guarantees a complete in-sequence set of captures to
4401 // application.
4402 const RequestList &requests = mRepeatingRequests;
4403 RequestList::const_iterator firstRequest =
4404 requests.begin();
4405 nextRequest = *firstRequest;
4406 mRequestQueue.insert(mRequestQueue.end(),
4407 ++firstRequest,
4408 requests.end());
4409 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004410
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004411 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004412
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 break;
4414 }
4415
4416 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4417
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004418 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4419 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004420 Mutex::Autolock pl(mPauseLock);
4421 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004422 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004423 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004424 // Let the tracker know
4425 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4426 if (statusTracker != 0) {
4427 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4428 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004429 }
4430 // Stop waiting for now and let thread management happen
4431 return NULL;
4432 }
4433 }
4434
4435 if (nextRequest == NULL) {
4436 // Don't have a repeating request already in hand, so queue
4437 // must have an entry now.
4438 RequestList::iterator firstRequest =
4439 mRequestQueue.begin();
4440 nextRequest = *firstRequest;
4441 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004442 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4443 sp<NotificationListener> listener = mListener.promote();
4444 if (listener != NULL) {
4445 listener->notifyRequestQueueEmpty();
4446 }
4447 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 }
4449
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004450 // In case we've been unpaused by setPaused clearing mDoPause, need to
4451 // update internal pause state (capture/setRepeatingRequest unpause
4452 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004453 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004454 if (mPaused) {
4455 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4456 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4457 if (statusTracker != 0) {
4458 statusTracker->markComponentActive(mStatusId);
4459 }
4460 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004461 mPaused = false;
4462
4463 // Check if we've reconfigured since last time, and reset the preview
4464 // request if so. Can't use 'NULL request == repeat' across configure calls.
4465 if (mReconfigured) {
4466 mPrevRequest.clear();
4467 mReconfigured = false;
4468 }
4469
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004470 if (nextRequest != NULL) {
4471 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004472 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4473 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004474
4475 // Since RequestThread::clear() removes buffers from the input stream,
4476 // get the right buffer here before unlocking mRequestLock
4477 if (nextRequest->mInputStream != NULL) {
4478 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4479 if (res != OK) {
4480 // Can't get input buffer from gralloc queue - this could be due to
4481 // disconnected queue or other producer misbehavior, so not a fatal
4482 // error
4483 ALOGE("%s: Can't get input buffer, skipping request:"
4484 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004485
4486 sp<NotificationListener> listener = mListener.promote();
4487 if (listener != NULL) {
4488 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004489 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004490 nextRequest->mResultExtras);
4491 }
4492 return NULL;
4493 }
4494 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004495 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004496
4497 handleAePrecaptureCancelRequest(nextRequest);
4498
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004499 return nextRequest;
4500}
4501
4502bool Camera3Device::RequestThread::waitIfPaused() {
4503 status_t res;
4504 Mutex::Autolock l(mPauseLock);
4505 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004506 if (mPaused == false) {
4507 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004508 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4509 // Let the tracker know
4510 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4511 if (statusTracker != 0) {
4512 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4513 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004514 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004515
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004516 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004517 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004518 return true;
4519 }
4520 }
4521 // We don't set mPaused to false here, because waitForNextRequest needs
4522 // to further manage the paused state in case of starvation.
4523 return false;
4524}
4525
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004526void Camera3Device::RequestThread::unpauseForNewRequests() {
4527 // With work to do, mark thread as unpaused.
4528 // If paused by request (setPaused), don't resume, to avoid
4529 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004530 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004531 Mutex::Autolock p(mPauseLock);
4532 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004533 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4534 if (mPaused) {
4535 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4536 if (statusTracker != 0) {
4537 statusTracker->markComponentActive(mStatusId);
4538 }
4539 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004540 mPaused = false;
4541 }
4542}
4543
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004544void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4545 sp<Camera3Device> parent = mParent.promote();
4546 if (parent != NULL) {
4547 va_list args;
4548 va_start(args, fmt);
4549
4550 parent->setErrorStateV(fmt, args);
4551
4552 va_end(args);
4553 }
4554}
4555
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004556status_t Camera3Device::RequestThread::insertTriggers(
4557 const sp<CaptureRequest> &request) {
4558
4559 Mutex::Autolock al(mTriggerMutex);
4560
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004561 sp<Camera3Device> parent = mParent.promote();
4562 if (parent == NULL) {
4563 CLOGE("RequestThread: Parent is gone");
4564 return DEAD_OBJECT;
4565 }
4566
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004567 CameraMetadata &metadata = request->mSettings;
4568 size_t count = mTriggerMap.size();
4569
4570 for (size_t i = 0; i < count; ++i) {
4571 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004572 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004573
4574 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4575 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4576 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004577 if (isAeTrigger) {
4578 request->mResultExtras.precaptureTriggerId = triggerId;
4579 mCurrentPreCaptureTriggerId = triggerId;
4580 } else {
4581 request->mResultExtras.afTriggerId = triggerId;
4582 mCurrentAfTriggerId = triggerId;
4583 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004584 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4585 continue; // Trigger ID tag is deprecated since device HAL 3.2
4586 }
4587 }
4588
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004589 camera_metadata_entry entry = metadata.find(tag);
4590
4591 if (entry.count > 0) {
4592 /**
4593 * Already has an entry for this trigger in the request.
4594 * Rewrite it with our requested trigger value.
4595 */
4596 RequestTrigger oldTrigger = trigger;
4597
4598 oldTrigger.entryValue = entry.data.u8[0];
4599
4600 mTriggerReplacedMap.add(tag, oldTrigger);
4601 } else {
4602 /**
4603 * More typical, no trigger entry, so we just add it
4604 */
4605 mTriggerRemovedMap.add(tag, trigger);
4606 }
4607
4608 status_t res;
4609
4610 switch (trigger.getTagType()) {
4611 case TYPE_BYTE: {
4612 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4613 res = metadata.update(tag,
4614 &entryValue,
4615 /*count*/1);
4616 break;
4617 }
4618 case TYPE_INT32:
4619 res = metadata.update(tag,
4620 &trigger.entryValue,
4621 /*count*/1);
4622 break;
4623 default:
4624 ALOGE("%s: Type not supported: 0x%x",
4625 __FUNCTION__,
4626 trigger.getTagType());
4627 return INVALID_OPERATION;
4628 }
4629
4630 if (res != OK) {
4631 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4632 ", value %d", __FUNCTION__, trigger.getTagName(),
4633 trigger.entryValue);
4634 return res;
4635 }
4636
4637 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4638 trigger.getTagName(),
4639 trigger.entryValue);
4640 }
4641
4642 mTriggerMap.clear();
4643
4644 return count;
4645}
4646
4647status_t Camera3Device::RequestThread::removeTriggers(
4648 const sp<CaptureRequest> &request) {
4649 Mutex::Autolock al(mTriggerMutex);
4650
4651 CameraMetadata &metadata = request->mSettings;
4652
4653 /**
4654 * Replace all old entries with their old values.
4655 */
4656 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4657 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4658
4659 status_t res;
4660
4661 uint32_t tag = trigger.metadataTag;
4662 switch (trigger.getTagType()) {
4663 case TYPE_BYTE: {
4664 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4665 res = metadata.update(tag,
4666 &entryValue,
4667 /*count*/1);
4668 break;
4669 }
4670 case TYPE_INT32:
4671 res = metadata.update(tag,
4672 &trigger.entryValue,
4673 /*count*/1);
4674 break;
4675 default:
4676 ALOGE("%s: Type not supported: 0x%x",
4677 __FUNCTION__,
4678 trigger.getTagType());
4679 return INVALID_OPERATION;
4680 }
4681
4682 if (res != OK) {
4683 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4684 ", trigger value %d", __FUNCTION__,
4685 trigger.getTagName(), trigger.entryValue);
4686 return res;
4687 }
4688 }
4689 mTriggerReplacedMap.clear();
4690
4691 /**
4692 * Remove all new entries.
4693 */
4694 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4695 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4696 status_t res = metadata.erase(trigger.metadataTag);
4697
4698 if (res != OK) {
4699 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4700 ", trigger value %d", __FUNCTION__,
4701 trigger.getTagName(), trigger.entryValue);
4702 return res;
4703 }
4704 }
4705 mTriggerRemovedMap.clear();
4706
4707 return OK;
4708}
4709
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004710status_t Camera3Device::RequestThread::addDummyTriggerIds(
4711 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004712 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004713 static const int32_t dummyTriggerId = 1;
4714 status_t res;
4715
4716 CameraMetadata &metadata = request->mSettings;
4717
4718 // If AF trigger is active, insert a dummy AF trigger ID if none already
4719 // exists
4720 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4721 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4722 if (afTrigger.count > 0 &&
4723 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4724 afId.count == 0) {
4725 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4726 if (res != OK) return res;
4727 }
4728
4729 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4730 // if none already exists
4731 camera_metadata_entry pcTrigger =
4732 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4733 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4734 if (pcTrigger.count > 0 &&
4735 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4736 pcId.count == 0) {
4737 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4738 &dummyTriggerId, 1);
4739 if (res != OK) return res;
4740 }
4741
4742 return OK;
4743}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004744
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004745/**
4746 * PreparerThread inner class methods
4747 */
4748
4749Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004750 Thread(/*canCallJava*/false), mListener(nullptr),
4751 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004752}
4753
4754Camera3Device::PreparerThread::~PreparerThread() {
4755 Thread::requestExitAndWait();
4756 if (mCurrentStream != nullptr) {
4757 mCurrentStream->cancelPrepare();
4758 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4759 mCurrentStream.clear();
4760 }
4761 clear();
4762}
4763
Ruben Brunkc78ac262015-08-13 17:58:46 -07004764status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004765 status_t res;
4766
4767 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004768 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004769
Ruben Brunkc78ac262015-08-13 17:58:46 -07004770 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004771 if (res == OK) {
4772 // No preparation needed, fire listener right off
4773 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004774 if (listener != NULL) {
4775 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776 }
4777 return OK;
4778 } else if (res != NOT_ENOUGH_DATA) {
4779 return res;
4780 }
4781
4782 // Need to prepare, start up thread if necessary
4783 if (!mActive) {
4784 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4785 // isn't running
4786 Thread::requestExitAndWait();
4787 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4788 if (res != OK) {
4789 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004790 if (listener != NULL) {
4791 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004792 }
4793 return res;
4794 }
4795 mCancelNow = false;
4796 mActive = true;
4797 ALOGV("%s: Preparer stream started", __FUNCTION__);
4798 }
4799
4800 // queue up the work
4801 mPendingStreams.push_back(stream);
4802 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4803
4804 return OK;
4805}
4806
4807status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004808 Mutex::Autolock l(mLock);
4809
4810 for (const auto& stream : mPendingStreams) {
4811 stream->cancelPrepare();
4812 }
4813 mPendingStreams.clear();
4814 mCancelNow = true;
4815
4816 return OK;
4817}
4818
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004819void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004820 Mutex::Autolock l(mLock);
4821 mListener = listener;
4822}
4823
4824bool Camera3Device::PreparerThread::threadLoop() {
4825 status_t res;
4826 {
4827 Mutex::Autolock l(mLock);
4828 if (mCurrentStream == nullptr) {
4829 // End thread if done with work
4830 if (mPendingStreams.empty()) {
4831 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4832 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4833 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4834 mActive = false;
4835 return false;
4836 }
4837
4838 // Get next stream to prepare
4839 auto it = mPendingStreams.begin();
4840 mCurrentStream = *it;
4841 mPendingStreams.erase(it);
4842 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4843 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4844 } else if (mCancelNow) {
4845 mCurrentStream->cancelPrepare();
4846 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4847 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4848 mCurrentStream.clear();
4849 mCancelNow = false;
4850 return true;
4851 }
4852 }
4853
4854 res = mCurrentStream->prepareNextBuffer();
4855 if (res == NOT_ENOUGH_DATA) return true;
4856 if (res != OK) {
4857 // Something bad happened; try to recover by cancelling prepare and
4858 // signalling listener anyway
4859 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4860 mCurrentStream->getId(), res, strerror(-res));
4861 mCurrentStream->cancelPrepare();
4862 }
4863
4864 // This stream has finished, notify listener
4865 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004866 sp<NotificationListener> listener = mListener.promote();
4867 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004868 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4869 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004870 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 }
4872
4873 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4874 mCurrentStream.clear();
4875
4876 return true;
4877}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004878
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004879/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004880 * Static callback forwarding methods from HAL to instance
4881 */
4882
4883void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4884 const camera3_capture_result *result) {
4885 Camera3Device *d =
4886 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004887
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004888 d->processCaptureResult(result);
4889}
4890
4891void Camera3Device::sNotify(const camera3_callback_ops *cb,
4892 const camera3_notify_msg *msg) {
4893 Camera3Device *d =
4894 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4895 d->notify(msg);
4896}
4897
4898}; // namespace android