blob: 6f64dc3da60d2702ec45ed50d3f5eac7005547d8 [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"
54#include "device3/Camera3ZslStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070055#include "device3/Camera3DummyStream.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 Talvala9a179412015-06-09 13:15:16 -070066 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070067 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070068 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070069 mUsePartialResult(false),
70 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080071 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070072 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070073 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070074 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070075 mNextReprocessShutterFrameNumber(0),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070076 mListener(NULL)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080077{
78 ATRACE_CALL();
79 camera3_callback_ops::notify = &sNotify;
80 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082}
83
84Camera3Device::~Camera3Device()
85{
86 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080087 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080088 disconnect();
89}
90
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080092 return mId;
93}
94
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080095/**
96 * CameraDeviceBase interface
97 */
98
Yin-Chia Yehe074a932015-01-30 10:29:02 -080099status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700102 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800103 Mutex::Autolock l(mLock);
104
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800106 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700107 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108 return INVALID_OPERATION;
109 }
110
111 /** Open HAL device */
112
113 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800114
115 camera3_device_t *device;
116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117 ATRACE_BEGIN("CameraHal::open");
118 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800119 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800120 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800121
122 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700123 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800124 return res;
125 }
126
127 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700129 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700130 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800132 device->common.version);
133 device->common.close(&device->common);
134 return BAD_VALUE;
135 }
136
137 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800139 if (res != OK) return res;
140
141 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700142 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
143 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700144 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800145 device->common.close(&device->common);
146 return BAD_VALUE;
147 }
148
149 /** Initialize device with callback functions */
150
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800151 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800152 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700153 ATRACE_END();
154
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800155 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700156 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
157 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800158 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800159 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800160 }
161
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800162 /** Everything is good to go */
163
164 mDeviceVersion = device->common.version;
165 mDeviceInfo = info.static_camera_characteristics;
166 mInterface = std::make_unique<HalInterface>(device);
167
168 return initializeCommonLocked();
169}
170
171status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
172 ATRACE_CALL();
173 Mutex::Autolock il(mInterfaceLock);
174 Mutex::Autolock l(mLock);
175
176 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
177 if (mStatus != STATUS_UNINITIALIZED) {
178 CLOGE("Already initialized!");
179 return INVALID_OPERATION;
180 }
181 if (manager == nullptr) return INVALID_OPERATION;
182
183 sp<ICameraDeviceSession> session;
184 ATRACE_BEGIN("CameraHal::openSession");
185 status_t res = manager->openSession(String8::std_string(mId), this,
186 /*out*/ &session);
187 ATRACE_END();
188 if (res != OK) {
189 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
190 return res;
191 }
192
193 res = manager->getCameraCharacteristics(String8::std_string(mId), &mDeviceInfo);
194 if (res != OK) {
195 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
196 session->close();
197 return res;
198 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800199
200 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
201 // for now use 3_4 to keep legacy devices working
202 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800203 mInterface = std::make_unique<HalInterface>(session);
204
205 return initializeCommonLocked();
206}
207
208status_t Camera3Device::initializeCommonLocked() {
209
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700210 /** Start up status tracker thread */
211 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800212 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700213 if (res != OK) {
214 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
215 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800216 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700217 mStatusTracker.clear();
218 return res;
219 }
220
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700221 /** Register in-flight map to the status tracker */
222 mInFlightStatusId = mStatusTracker->addComponent();
223
Zhijun He125684a2015-12-26 15:07:30 -0800224 /** Create buffer manager */
225 mBufferManager = new Camera3BufferManager();
226
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700227 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800228 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
229 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
230 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700231 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
232 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
233 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800234
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700235 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800236 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
237 aeLockAvailable);
238 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700240 SET_ERR_L("Unable to start request queue thread: %s (%d)",
241 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800242 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800243 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800244 return res;
245 }
246
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700247 mPreparerThread = new PreparerThread();
248
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700249 // Determine whether we need to derive sensitivity boost values for older devices.
250 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
251 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800252 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700253 mDerivePostRawSensKey = true;
254 }
255
Ruben Brunk183f0562015-08-12 12:55:02 -0700256 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800257 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700258 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700259 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800261
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800262 // Measure the clock domain offset between camera and video/hw_composer
263 camera_metadata_entry timestampSource =
264 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
265 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
266 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
267 mTimestampOffset = getMonoToBoottimeOffset();
268 }
269
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700270 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700271 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
272 camera_metadata_entry partialResultsCount =
273 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
274 if (partialResultsCount.count > 0) {
275 mNumPartialResults = partialResultsCount.data.i32[0];
276 mUsePartialResult = (mNumPartialResults > 1);
277 }
278 } else {
279 camera_metadata_entry partialResultsQuirk =
280 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
281 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
282 mUsePartialResult = true;
283 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700284 }
285
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700286 camera_metadata_entry configs =
287 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
288 for (uint32_t i = 0; i < configs.count; i += 4) {
289 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
290 configs.data.i32[i + 3] ==
291 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
292 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
293 configs.data.i32[i + 2]));
294 }
295 }
296
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800297 return OK;
298}
299
300status_t Camera3Device::disconnect() {
301 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800303
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700304 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700306 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800307
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 {
309 Mutex::Autolock l(mLock);
310 if (mStatus == STATUS_UNINITIALIZED) return res;
311
312 if (mStatus == STATUS_ACTIVE ||
313 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
314 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700315 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700317 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 } else {
319 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
320 if (res != OK) {
321 SET_ERR_L("Timeout waiting for HAL to drain");
322 // Continue to close device even in case of error
323 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700324 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700327 if (mStatus == STATUS_ERROR) {
328 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700329 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700330
331 if (mStatusTracker != NULL) {
332 mStatusTracker->requestExit();
333 }
334
335 if (mRequestThread != NULL) {
336 mRequestThread->requestExit();
337 }
338
339 mOutputStreams.clear();
340 mInputStream.clear();
341 }
342
343 // Joining done without holding mLock, otherwise deadlocks may ensue
344 // as the threads try to access parent state
345 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
346 // HAL may be in a bad state, so waiting for request thread
347 // (which may be stuck in the HAL processCaptureRequest call)
348 // could be dangerous.
349 mRequestThread->join();
350 }
351
352 if (mStatusTracker != NULL) {
353 mStatusTracker->join();
354 }
355
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800356 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700357 {
358 Mutex::Autolock l(mLock);
359
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800360 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700361 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800362 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800363
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800364 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700365 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800366
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700367 // Call close without internal mutex held, as the HAL close may need to
368 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800369 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700370
371 {
372 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800373 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700374 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700375 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800376
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700377 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700378 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800379}
380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381// For dumping/debugging only -
382// try to acquire a lock a few times, eventually give up to proceed with
383// debug/dump operations
384bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
385 bool gotLock = false;
386 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
387 if (lock.tryLock() == NO_ERROR) {
388 gotLock = true;
389 break;
390 } else {
391 usleep(kDumpSleepDuration);
392 }
393 }
394 return gotLock;
395}
396
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700397Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
398 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
399 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
400 const int STREAM_CONFIGURATION_SIZE = 4;
401 const int STREAM_FORMAT_OFFSET = 0;
402 const int STREAM_WIDTH_OFFSET = 1;
403 const int STREAM_HEIGHT_OFFSET = 2;
404 const int STREAM_IS_INPUT_OFFSET = 3;
405 camera_metadata_ro_entry_t availableStreamConfigs =
406 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
407 if (availableStreamConfigs.count == 0 ||
408 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
409 return Size(0, 0);
410 }
411
412 // Get max jpeg size (area-wise).
413 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
414 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
415 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
416 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
417 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
418 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
419 && format == HAL_PIXEL_FORMAT_BLOB &&
420 (width * height > maxJpegWidth * maxJpegHeight)) {
421 maxJpegWidth = width;
422 maxJpegHeight = height;
423 }
424 }
425 } else {
426 camera_metadata_ro_entry availableJpegSizes =
427 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
428 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
429 return Size(0, 0);
430 }
431
432 // Get max jpeg size (area-wise).
433 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
434 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
435 > (maxJpegWidth * maxJpegHeight)) {
436 maxJpegWidth = availableJpegSizes.data.i32[i];
437 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
438 }
439 }
440 }
441 return Size(maxJpegWidth, maxJpegHeight);
442}
443
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800444nsecs_t Camera3Device::getMonoToBoottimeOffset() {
445 // try three times to get the clock offset, choose the one
446 // with the minimum gap in measurements.
447 const int tries = 3;
448 nsecs_t bestGap, measured;
449 for (int i = 0; i < tries; ++i) {
450 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
451 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
452 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
453 const nsecs_t gap = tmono2 - tmono;
454 if (i == 0 || gap < bestGap) {
455 bestGap = gap;
456 measured = tbase - ((tmono + tmono2) >> 1);
457 }
458 }
459 return measured;
460}
461
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700462/**
463 * Map Android N dataspace definitions back to Android M definitions, for
464 * use with HALv3.3 or older.
465 *
466 * Only map where correspondences exist, and otherwise preserve the value.
467 */
468android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
469 switch (dataSpace) {
470 case HAL_DATASPACE_V0_SRGB_LINEAR:
471 return HAL_DATASPACE_SRGB_LINEAR;
472 case HAL_DATASPACE_V0_SRGB:
473 return HAL_DATASPACE_SRGB;
474 case HAL_DATASPACE_V0_JFIF:
475 return HAL_DATASPACE_JFIF;
476 case HAL_DATASPACE_V0_BT601_625:
477 return HAL_DATASPACE_BT601_625;
478 case HAL_DATASPACE_V0_BT601_525:
479 return HAL_DATASPACE_BT601_525;
480 case HAL_DATASPACE_V0_BT709:
481 return HAL_DATASPACE_BT709;
482 default:
483 return dataSpace;
484 }
485}
486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
488 int frameworkFormat) {
489 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
490}
491
492DataspaceFlags Camera3Device::mapToHidlDataspace(
493 android_dataspace dataSpace) {
494 return dataSpace;
495}
496
497ConsumerUsageFlags Camera3Device::mapToConsumerUsage(
498 uint32_t usage) {
499 return usage;
500}
501
502StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
503 switch (rotation) {
504 case CAMERA3_STREAM_ROTATION_0:
505 return StreamRotation::ROTATION_0;
506 case CAMERA3_STREAM_ROTATION_90:
507 return StreamRotation::ROTATION_90;
508 case CAMERA3_STREAM_ROTATION_180:
509 return StreamRotation::ROTATION_180;
510 case CAMERA3_STREAM_ROTATION_270:
511 return StreamRotation::ROTATION_270;
512 }
513 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
514 return StreamRotation::ROTATION_0;
515}
516
517StreamConfigurationMode Camera3Device::mapToStreamConfigurationMode(
518 camera3_stream_configuration_mode_t operationMode) {
519 switch(operationMode) {
520 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
521 return StreamConfigurationMode::NORMAL_MODE;
522 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
523 return StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
524 case CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START:
525 // Needs to be mapped by vendor extensions
526 break;
527 }
528 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
529 return StreamConfigurationMode::NORMAL_MODE;
530}
531
532camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
533 switch (status) {
534 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
535 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
536 }
537 return CAMERA3_BUFFER_STATUS_ERROR;
538}
539
540int Camera3Device::mapToFrameworkFormat(
541 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
542 return static_cast<uint32_t>(pixelFormat);
543}
544
545uint32_t Camera3Device::mapConsumerToFrameworkUsage(
546 ConsumerUsageFlags usage) {
547 return usage;
548}
549
550uint32_t Camera3Device::mapProducerToFrameworkUsage(
551 ProducerUsageFlags usage) {
552 return usage;
553}
554
Zhijun Hef7da0962014-04-24 13:27:56 -0700555ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700556 // Get max jpeg size (area-wise).
557 Size maxJpegResolution = getMaxJpegResolution();
558 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800559 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
560 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700561 return BAD_VALUE;
562 }
563
Zhijun Hef7da0962014-04-24 13:27:56 -0700564 // Get max jpeg buffer size
565 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700566 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
567 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
569 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700570 return BAD_VALUE;
571 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700572 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800573 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700574
575 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700576 float scaleFactor = ((float) (width * height)) /
577 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800578 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
579 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700580 if (jpegBufferSize > maxJpegBufferSize) {
581 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700582 }
583
584 return jpegBufferSize;
585}
586
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700587ssize_t Camera3Device::getPointCloudBufferSize() const {
588 const int FLOATS_PER_POINT=4;
589 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
590 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
592 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700593 return BAD_VALUE;
594 }
595 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
596 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
597 return maxBytesForPointCloud;
598}
599
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800600ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800601 const int PER_CONFIGURATION_SIZE = 3;
602 const int WIDTH_OFFSET = 0;
603 const int HEIGHT_OFFSET = 1;
604 const int SIZE_OFFSET = 2;
605 camera_metadata_ro_entry rawOpaqueSizes =
606 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800607 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800608 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
610 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800611 return BAD_VALUE;
612 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700613
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800614 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
615 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
616 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
617 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
618 }
619 }
620
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
622 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800623 return BAD_VALUE;
624}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700625
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800626status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
627 ATRACE_CALL();
628 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700629
630 // Try to lock, but continue in case of failure (to avoid blocking in
631 // deadlocks)
632 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
633 bool gotLock = tryLockSpinRightRound(mLock);
634
635 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800636 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
637 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700638 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
640 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700641
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800642 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700643
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800644 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700645 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800646 int n = args.size();
647 for (int i = 0; i < n; i++) {
648 if (args[i] == templatesOption) {
649 dumpTemplates = true;
650 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700651 if (args[i] == monitorOption) {
652 if (i + 1 < n) {
653 String8 monitorTags = String8(args[i + 1]);
654 if (monitorTags == "off") {
655 mTagMonitor.disableMonitoring();
656 } else {
657 mTagMonitor.parseTagsToMonitor(monitorTags);
658 }
659 } else {
660 mTagMonitor.disableMonitoring();
661 }
662 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800663 }
664
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800665 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800667 const char *status =
668 mStatus == STATUS_ERROR ? "ERROR" :
669 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700670 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
671 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 mStatus == STATUS_ACTIVE ? "ACTIVE" :
673 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700676 if (mStatus == STATUS_ERROR) {
677 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
678 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800679 lines.appendFormat(" Stream configuration:\n");
Zhijun He1fa89992015-06-01 15:44:31 -0700680 lines.appendFormat(" Operation mode: %s \n", mIsConstrainedHighSpeedConfiguration ?
Eino-Ville Talvala9a179412015-06-09 13:15:16 -0700681 "CONSTRAINED HIGH SPEED VIDEO" : "NORMAL");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682
683 if (mInputStream != NULL) {
684 write(fd, lines.string(), lines.size());
685 mInputStream->dump(fd, args);
686 } else {
687 lines.appendFormat(" No input stream.\n");
688 write(fd, lines.string(), lines.size());
689 }
690 for (size_t i = 0; i < mOutputStreams.size(); i++) {
691 mOutputStreams[i]->dump(fd,args);
692 }
693
Zhijun He431503c2016-03-07 17:30:16 -0800694 if (mBufferManager != NULL) {
695 lines = String8(" Camera3 Buffer Manager:\n");
696 write(fd, lines.string(), lines.size());
697 mBufferManager->dump(fd, args);
698 }
Zhijun He125684a2015-12-26 15:07:30 -0800699
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700700 lines = String8(" In-flight requests:\n");
701 if (mInFlightMap.size() == 0) {
702 lines.append(" None\n");
703 } else {
704 for (size_t i = 0; i < mInFlightMap.size(); i++) {
705 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700706 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700707 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800708 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700709 r.numBuffersLeft);
710 }
711 }
712 write(fd, lines.string(), lines.size());
713
Igor Murashkin1e479c02013-09-06 16:55:14 -0700714 {
715 lines = String8(" Last request sent:\n");
716 write(fd, lines.string(), lines.size());
717
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700719 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
720 }
721
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 if (dumpTemplates) {
723 const char *templateNames[] = {
724 "TEMPLATE_PREVIEW",
725 "TEMPLATE_STILL_CAPTURE",
726 "TEMPLATE_VIDEO_RECORD",
727 "TEMPLATE_VIDEO_SNAPSHOT",
728 "TEMPLATE_ZERO_SHUTTER_LAG",
729 "TEMPLATE_MANUAL"
730 };
731
732 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800733 camera_metadata_t *templateRequest = nullptr;
734 mInterface->constructDefaultRequestSettings(
735 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800736 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800737 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800738 lines.append(" Not supported\n");
739 write(fd, lines.string(), lines.size());
740 } else {
741 write(fd, lines.string(), lines.size());
742 dump_indented_camera_metadata(templateRequest,
743 fd, /*verbosity*/2, /*indentation*/8);
744 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800745 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800746 }
747 }
748
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700749 mTagMonitor.dumpMonitoredMetadata(fd);
750
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800751 if (mInterface->valid()) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700752 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800754 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800755 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800756
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700757 if (gotLock) mLock.unlock();
758 if (gotInterfaceLock) mInterfaceLock.unlock();
759
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800760 return OK;
761}
762
763const CameraMetadata& Camera3Device::info() const {
764 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800765 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
766 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700767 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800768 mStatus == STATUS_ERROR ?
769 "when in error state" : "before init");
770 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771 return mDeviceInfo;
772}
773
Jianing Wei90e59c92014-03-12 18:29:36 -0700774status_t Camera3Device::checkStatusOkToCaptureLocked() {
775 switch (mStatus) {
776 case STATUS_ERROR:
777 CLOGE("Device has encountered a serious error");
778 return INVALID_OPERATION;
779 case STATUS_UNINITIALIZED:
780 CLOGE("Device not initialized");
781 return INVALID_OPERATION;
782 case STATUS_UNCONFIGURED:
783 case STATUS_CONFIGURED:
784 case STATUS_ACTIVE:
785 // OK
786 break;
787 default:
788 SET_ERR_L("Unexpected status: %d", mStatus);
789 return INVALID_OPERATION;
790 }
791 return OK;
792}
793
794status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang9d066012016-09-30 11:30:20 -0700795 const List<const CameraMetadata> &metadataList, bool repeating,
796 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700797 if (requestList == NULL) {
798 CLOGE("requestList cannot be NULL.");
799 return BAD_VALUE;
800 }
801
Jianing Weicb0652e2014-03-12 18:29:36 -0700802 int32_t burstId = 0;
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 for (List<const CameraMetadata>::const_iterator it = metadataList.begin();
804 it != metadataList.end(); ++it) {
805 sp<CaptureRequest> newRequest = setUpRequestLocked(*it);
806 if (newRequest == 0) {
807 CLOGE("Can't create capture request");
808 return BAD_VALUE;
809 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700810
Shuzhen Wang9d066012016-09-30 11:30:20 -0700811 newRequest->mRepeating = repeating;
812
Jianing Weicb0652e2014-03-12 18:29:36 -0700813 // Setup burst Id and request Id
814 newRequest->mResultExtras.burstId = burstId++;
815 if (it->exists(ANDROID_REQUEST_ID)) {
816 if (it->find(ANDROID_REQUEST_ID).count == 0) {
817 CLOGE("RequestID entry exists; but must not be empty in metadata");
818 return BAD_VALUE;
819 }
820 newRequest->mResultExtras.requestId = it->find(ANDROID_REQUEST_ID).data.i32[0];
821 } else {
822 CLOGE("RequestID does not exist in metadata");
823 return BAD_VALUE;
824 }
825
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700827
828 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700829 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700830
831 // Setup batch size if this is a high speed video recording request.
832 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
833 auto firstRequest = requestList->begin();
834 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
835 if (outputStream->isVideoStream()) {
836 (*firstRequest)->mBatchSize = requestList->size();
837 break;
838 }
839 }
840 }
841
Jianing Wei90e59c92014-03-12 18:29:36 -0700842 return OK;
843}
844
Jianing Weicb0652e2014-03-12 18:29:36 -0700845status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800847
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700848 List<const CameraMetadata> requests;
849 requests.push_back(request);
850 return captureList(requests, /*lastFrameNumber*/NULL);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800851}
852
Jianing Wei90e59c92014-03-12 18:29:36 -0700853status_t Camera3Device::submitRequestsHelper(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700854 const List<const CameraMetadata> &requests, bool repeating,
855 /*out*/
856 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700857 ATRACE_CALL();
858 Mutex::Autolock il(mInterfaceLock);
859 Mutex::Autolock l(mLock);
860
861 status_t res = checkStatusOkToCaptureLocked();
862 if (res != OK) {
863 // error logged by previous call
864 return res;
865 }
866
867 RequestList requestList;
868
Shuzhen Wang9d066012016-09-30 11:30:20 -0700869 res = convertMetadataListToRequestListLocked(requests, repeating,
870 /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700871 if (res != OK) {
872 // error logged by previous call
873 return res;
874 }
875
876 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700877 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700878 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700879 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700880 }
881
882 if (res == OK) {
883 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
884 if (res != OK) {
885 SET_ERR_L("Can't transition to active in %f seconds!",
886 kActiveTimeout/1e9);
887 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800888 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700889 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700890 } else {
891 CLOGE("Cannot queue request. Impossible.");
892 return BAD_VALUE;
893 }
894
895 return res;
896}
897
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800898hardware::Return<void> Camera3Device::processCaptureResult(
899 const device::V3_2::CaptureResult& result) {
900 camera3_capture_result r;
901 status_t res;
902 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800903 if (result.result.size() != 0) {
904 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
905 size_t expected_metadata_size = result.result.size();
906 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
907 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
908 __FUNCTION__, result.frameNumber, strerror(-res), res);
909 return hardware::Void();
910 }
911 } else {
912 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800913 }
914
915 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
916 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
917 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
918 auto& bDst = outputBuffers[i];
919 const StreamBuffer &bSrc = result.outputBuffers[i];
920
921 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
922 if (idx == -1) {
923 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
924 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
925 return hardware::Void();
926 }
927 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
928
929 buffer_handle_t *buffer;
930 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId,
931 &buffer);
932 if (res != OK) {
933 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
934 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
935 return hardware::Void();
936 }
937 bDst.buffer = buffer;
938 bDst.status = mapHidlBufferStatus(bSrc.status);
939 bDst.acquire_fence = -1;
940 if (bSrc.releaseFence == nullptr) {
941 bDst.release_fence = -1;
942 } else if (bSrc.releaseFence->numFds == 1) {
943 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
944 } else {
945 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
946 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
947 return hardware::Void();
948 }
949 }
950 r.num_output_buffers = outputBuffers.size();
951 r.output_buffers = outputBuffers.data();
952
953 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800954 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800955 r.input_buffer = nullptr;
956 } else {
957 if (mInputStream->getId() != result.inputBuffer.streamId) {
958 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
959 result.frameNumber, result.inputBuffer.streamId);
960 return hardware::Void();
961 }
962 inputBuffer.stream = mInputStream->asHalStream();
963 buffer_handle_t *buffer;
964 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
965 &buffer);
966 if (res != OK) {
967 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
968 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
969 return hardware::Void();
970 }
971 inputBuffer.buffer = buffer;
972 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
973 inputBuffer.acquire_fence = -1;
974 if (result.inputBuffer.releaseFence == nullptr) {
975 inputBuffer.release_fence = -1;
976 } else if (result.inputBuffer.releaseFence->numFds == 1) {
977 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
978 } else {
979 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
980 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
981 return hardware::Void();
982 }
983 r.input_buffer = &inputBuffer;
984 }
985
986 r.partial_result = result.partialResult;
987
988 processCaptureResult(&r);
989
990 return hardware::Void();
991}
992
993hardware::Return<void> Camera3Device::notify(
994 const NotifyMsg& msg) {
995 camera3_notify_msg m;
996 switch (msg.type) {
997 case MsgType::ERROR:
998 m.type = CAMERA3_MSG_ERROR;
999 m.message.error.frame_number = msg.msg.error.frameNumber;
1000 if (msg.msg.error.errorStreamId >= 0) {
1001 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
1002 if (idx == -1) {
1003 ALOGE("%s: Frame %d: Invalid error stream id %d",
1004 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1005 return hardware::Void();
1006 }
1007 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1008 } else {
1009 m.message.error.error_stream = nullptr;
1010 }
1011 switch (msg.msg.error.errorCode) {
1012 case ErrorCode::ERROR_DEVICE:
1013 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1014 break;
1015 case ErrorCode::ERROR_REQUEST:
1016 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1017 break;
1018 case ErrorCode::ERROR_RESULT:
1019 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1020 break;
1021 case ErrorCode::ERROR_BUFFER:
1022 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1023 break;
1024 }
1025 break;
1026 case MsgType::SHUTTER:
1027 m.type = CAMERA3_MSG_SHUTTER;
1028 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1029 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1030 break;
1031 }
1032 notify(&m);
1033
1034 return hardware::Void();
1035}
1036
Jianing Weicb0652e2014-03-12 18:29:36 -07001037status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
1038 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001039 ATRACE_CALL();
1040
Jianing Weicb0652e2014-03-12 18:29:36 -07001041 return submitRequestsHelper(requests, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001042}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001043
Jianing Weicb0652e2014-03-12 18:29:36 -07001044status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1045 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001046 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001047
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001048 List<const CameraMetadata> requests;
1049 requests.push_back(request);
1050 return setStreamingRequestList(requests, /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051}
1052
Jianing Weicb0652e2014-03-12 18:29:36 -07001053status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
1054 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001055 ATRACE_CALL();
1056
Jianing Weicb0652e2014-03-12 18:29:36 -07001057 return submitRequestsHelper(requests, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001058}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001059
1060sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
1061 const CameraMetadata &request) {
1062 status_t res;
1063
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001064 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001065 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001066 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001067 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001068 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001070 } else if (mStatus == STATUS_UNCONFIGURED) {
1071 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001072 CLOGE("No streams configured");
1073 return NULL;
1074 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001075 }
1076
1077 sp<CaptureRequest> newRequest = createCaptureRequest(request);
1078 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001079}
1080
Jianing Weicb0652e2014-03-12 18:29:36 -07001081status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001082 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001083 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001084 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001085
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001086 switch (mStatus) {
1087 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001088 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001089 return INVALID_OPERATION;
1090 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001091 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001092 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001093 case STATUS_UNCONFIGURED:
1094 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001095 case STATUS_ACTIVE:
1096 // OK
1097 break;
1098 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001099 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100 return INVALID_OPERATION;
1101 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001102 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001103
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001104 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105}
1106
1107status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1108 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001109 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001110
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001111 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001112}
1113
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001114status_t Camera3Device::createInputStream(
1115 uint32_t width, uint32_t height, int format, int *id) {
1116 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001117 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001118 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001119 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1120 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001121
1122 status_t res;
1123 bool wasActive = false;
1124
1125 switch (mStatus) {
1126 case STATUS_ERROR:
1127 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1128 return INVALID_OPERATION;
1129 case STATUS_UNINITIALIZED:
1130 ALOGE("%s: Device not initialized", __FUNCTION__);
1131 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001132 case STATUS_UNCONFIGURED:
1133 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001134 // OK
1135 break;
1136 case STATUS_ACTIVE:
1137 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001138 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001139 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001140 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001141 return res;
1142 }
1143 wasActive = true;
1144 break;
1145 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001146 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001147 return INVALID_OPERATION;
1148 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001149 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001150
1151 if (mInputStream != 0) {
1152 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1153 return INVALID_OPERATION;
1154 }
1155
1156 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1157 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001158 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001159
1160 mInputStream = newStream;
1161
1162 *id = mNextStreamId++;
1163
1164 // Continue captures if active at start
1165 if (wasActive) {
1166 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1167 res = configureStreamsLocked();
1168 if (res != OK) {
1169 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1170 __FUNCTION__, mNextStreamId, strerror(-res), res);
1171 return res;
1172 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001174 }
1175
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001176 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001177 return OK;
1178}
1179
Igor Murashkin2fba5842013-04-22 14:03:54 -07001180
1181status_t Camera3Device::createZslStream(
1182 uint32_t width, uint32_t height,
1183 int depth,
1184 /*out*/
1185 int *id,
1186 sp<Camera3ZslStream>* zslStream) {
1187 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001188 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001189 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001190 ALOGV("Camera %s: Creating ZSL stream %d: %d x %d, depth %d",
1191 mId.string(), mNextStreamId, width, height, depth);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001192
1193 status_t res;
1194 bool wasActive = false;
1195
1196 switch (mStatus) {
1197 case STATUS_ERROR:
1198 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1199 return INVALID_OPERATION;
1200 case STATUS_UNINITIALIZED:
1201 ALOGE("%s: Device not initialized", __FUNCTION__);
1202 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001203 case STATUS_UNCONFIGURED:
1204 case STATUS_CONFIGURED:
Igor Murashkin2fba5842013-04-22 14:03:54 -07001205 // OK
1206 break;
1207 case STATUS_ACTIVE:
1208 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001209 res = internalPauseAndWaitLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001210 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin2fba5842013-04-22 14:03:54 -07001212 return res;
1213 }
1214 wasActive = true;
1215 break;
1216 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 SET_ERR_L("Unexpected status: %d", mStatus);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001218 return INVALID_OPERATION;
1219 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001221
1222 if (mInputStream != 0) {
1223 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1224 return INVALID_OPERATION;
1225 }
1226
1227 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
1228 width, height, depth);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001229 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001230
1231 res = mOutputStreams.add(mNextStreamId, newStream);
1232 if (res < 0) {
1233 ALOGE("%s: Can't add new stream to set: %s (%d)",
1234 __FUNCTION__, strerror(-res), res);
1235 return res;
1236 }
1237 mInputStream = newStream;
1238
Yuvraj Pasie5e3d082014-04-15 18:37:45 +05301239 mNeedConfig = true;
1240
Igor Murashkin2fba5842013-04-22 14:03:54 -07001241 *id = mNextStreamId++;
1242 *zslStream = newStream;
1243
1244 // Continue captures if active at start
1245 if (wasActive) {
1246 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1247 res = configureStreamsLocked();
1248 if (res != OK) {
1249 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1250 __FUNCTION__, mNextStreamId, strerror(-res), res);
1251 return res;
1252 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 internalResumeLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001254 }
1255
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001256 ALOGV("Camera %s: Created ZSL stream", mId.string());
Igor Murashkin2fba5842013-04-22 14:03:54 -07001257 return OK;
1258}
1259
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001260status_t Camera3Device::createStream(sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -08001261 uint32_t width, uint32_t height, int format, android_dataspace dataSpace,
Zhijun He5d677d12016-05-29 16:52:39 -07001262 camera3_stream_rotation_t rotation, int *id, int streamSetId, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001266 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
1267 " consumer usage 0x%x", mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Zhijun He5d677d12016-05-29 16:52:39 -07001268 consumerUsage);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001269
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 status_t res;
1271 bool wasActive = false;
1272
1273 switch (mStatus) {
1274 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001275 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return INVALID_OPERATION;
1277 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001278 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 case STATUS_UNCONFIGURED:
1281 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 // OK
1283 break;
1284 case STATUS_ACTIVE:
1285 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001289 return res;
1290 }
1291 wasActive = true;
1292 break;
1293 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001294 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001295 return INVALID_OPERATION;
1296 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001297 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298
1299 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001300 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001301 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001302 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001303 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1304 }
Zhijun He5d677d12016-05-29 16:52:39 -07001305
1306 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1307 // which requires a consumer surface to be available.
1308 if (consumer == nullptr && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
1309 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1310 return BAD_VALUE;
1311 }
1312
1313 if (consumer == nullptr && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
1314 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1315 return BAD_VALUE;
1316 }
1317
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001318 // Use legacy dataspace values for older HALs
1319 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1320 dataSpace = mapToLegacyDataspace(dataSpace);
1321 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001322 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001323 ssize_t blobBufferSize;
1324 if (dataSpace != HAL_DATASPACE_DEPTH) {
1325 blobBufferSize = getJpegBufferSize(width, height);
1326 if (blobBufferSize <= 0) {
1327 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1328 return BAD_VALUE;
1329 }
1330 } else {
1331 blobBufferSize = getPointCloudBufferSize();
1332 if (blobBufferSize <= 0) {
1333 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1334 return BAD_VALUE;
1335 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001336 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001338 width, height, blobBufferSize, format, dataSpace, rotation,
1339 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001340 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1341 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1342 if (rawOpaqueBufferSize <= 0) {
1343 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1344 return BAD_VALUE;
1345 }
1346 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001347 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1348 mTimestampOffset, streamSetId);
Zhijun He5d677d12016-05-29 16:52:39 -07001349 } else if (consumer == nullptr) {
1350 newStream = new Camera3OutputStream(mNextStreamId,
1351 width, height, format, consumerUsage, dataSpace, rotation,
1352 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 } else {
1354 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001355 width, height, format, dataSpace, rotation,
1356 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001358 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359
Zhijun He125684a2015-12-26 15:07:30 -08001360 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001361 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1362 * requires buffers to be statically allocated for internal static buffer registration, while
1363 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1364 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001365 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001366 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001367 newStream->setBufferManager(mBufferManager);
1368 }
1369
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 res = mOutputStreams.add(mNextStreamId, newStream);
1371 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001372 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373 return res;
1374 }
1375
1376 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001377 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378
1379 // Continue captures if active at start
1380 if (wasActive) {
1381 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1382 res = configureStreamsLocked();
1383 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001384 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1385 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 return res;
1387 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001390 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001392}
1393
1394status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1395 ATRACE_CALL();
1396 (void)outputId; (void)id;
1397
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001398 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001399 return INVALID_OPERATION;
1400}
1401
1402
1403status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001404 uint32_t *width, uint32_t *height,
1405 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001406 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001407 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001409
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 switch (mStatus) {
1411 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return INVALID_OPERATION;
1414 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001415 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001417 case STATUS_UNCONFIGURED:
1418 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 case STATUS_ACTIVE:
1420 // OK
1421 break;
1422 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001423 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 return INVALID_OPERATION;
1425 }
1426
1427 ssize_t idx = mOutputStreams.indexOfKey(id);
1428 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001429 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 return idx;
1431 }
1432
1433 if (width) *width = mOutputStreams[idx]->getWidth();
1434 if (height) *height = mOutputStreams[idx]->getHeight();
1435 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001436 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001438}
1439
1440status_t Camera3Device::setStreamTransform(int id,
1441 int transform) {
1442 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001443 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001444 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001445
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 switch (mStatus) {
1447 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001448 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 return INVALID_OPERATION;
1450 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001451 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001453 case STATUS_UNCONFIGURED:
1454 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 case STATUS_ACTIVE:
1456 // OK
1457 break;
1458 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 return INVALID_OPERATION;
1461 }
1462
1463 ssize_t idx = mOutputStreams.indexOfKey(id);
1464 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001465 CLOGE("Stream %d does not exist",
1466 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 return BAD_VALUE;
1468 }
1469
1470 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471}
1472
1473status_t Camera3Device::deleteStream(int id) {
1474 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001475 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 Mutex::Autolock l(mLock);
1477 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001479 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 // CameraDevice semantics require device to already be idle before
1482 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001483 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001484 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001485 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 }
1487
Igor Murashkin2fba5842013-04-22 14:03:54 -07001488 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001489 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 if (mInputStream != NULL && id == mInputStream->getId()) {
1491 deletedStream = mInputStream;
1492 mInputStream.clear();
1493 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001494 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 return BAD_VALUE;
1497 }
Zhijun He5f446352014-01-22 09:49:33 -08001498 }
1499
1500 // Delete output stream or the output part of a bi-directional stream.
1501 if (outputStreamIdx != NAME_NOT_FOUND) {
1502 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 mOutputStreams.removeItem(id);
1504 }
1505
1506 // Free up the stream endpoint so that it can be used by some other stream
1507 res = deletedStream->disconnect();
1508 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 // fall through since we want to still list the stream as deleted.
1511 }
1512 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001513 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514
1515 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516}
1517
1518status_t Camera3Device::deleteReprocessStream(int id) {
1519 ATRACE_CALL();
1520 (void)id;
1521
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001522 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523 return INVALID_OPERATION;
1524}
1525
Zhijun He1fa89992015-06-01 15:44:31 -07001526status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001527 ATRACE_CALL();
1528 ALOGV("%s: E", __FUNCTION__);
1529
1530 Mutex::Autolock il(mInterfaceLock);
1531 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001532
1533 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) {
1534 mNeedConfig = true;
1535 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
1536 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001537
1538 return configureStreamsLocked();
1539}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001541status_t Camera3Device::getInputBufferProducer(
1542 sp<IGraphicBufferProducer> *producer) {
1543 Mutex::Autolock il(mInterfaceLock);
1544 Mutex::Autolock l(mLock);
1545
1546 if (producer == NULL) {
1547 return BAD_VALUE;
1548 } else if (mInputStream == NULL) {
1549 return INVALID_OPERATION;
1550 }
1551
1552 return mInputStream->getInputBufferProducer(producer);
1553}
1554
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555status_t Camera3Device::createDefaultRequest(int templateId,
1556 CameraMetadata *request) {
1557 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001558 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001559
1560 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1561 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1562 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1563 return BAD_VALUE;
1564 }
1565
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001566 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 Mutex::Autolock l(mLock);
1568
1569 switch (mStatus) {
1570 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 case STATUS_UNCONFIGURED:
1577 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 case STATUS_ACTIVE:
1579 // OK
1580 break;
1581 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001582 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return INVALID_OPERATION;
1584 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001585
Zhijun Hea1530f12014-09-14 12:44:20 -07001586 if (!mRequestTemplateCache[templateId].isEmpty()) {
1587 *request = mRequestTemplateCache[templateId];
1588 return OK;
1589 }
1590
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001591 camera_metadata_t *rawRequest;
1592 status_t res = mInterface->constructDefaultRequestSettings(
1593 (camera3_request_template_t) templateId, &rawRequest);
1594 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001595 ALOGI("%s: template %d is not supported on this camera device",
1596 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001597 return res;
1598 } else if (res != OK) {
1599 CLOGE("Unable to construct request template %d: %s (%d)",
1600 templateId, strerror(-res), res);
1601 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001602 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001603
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001604 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001605
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001606 // Derive some new keys for backward compatibility
1607 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1608 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1609 int32_t defaultBoost[1] = {100};
1610 mRequestTemplateCache[templateId].update(
1611 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1612 defaultBoost, 1);
1613 }
1614
1615 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616 return OK;
1617}
1618
1619status_t Camera3Device::waitUntilDrained() {
1620 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001622 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001623
Zhijun He69a37482014-03-23 18:44:49 -07001624 return waitUntilDrainedLocked();
1625}
1626
1627status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628 switch (mStatus) {
1629 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 ALOGV("%s: Already idle", __FUNCTION__);
1632 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 case STATUS_CONFIGURED:
1634 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001635 case STATUS_ERROR:
1636 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001638 break;
1639 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001640 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 return INVALID_OPERATION;
1642 }
1643
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001644 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001646 if (res != OK) {
1647 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1648 res);
1649 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 return res;
1651}
1652
Ruben Brunk183f0562015-08-12 12:55:02 -07001653
1654void Camera3Device::internalUpdateStatusLocked(Status status) {
1655 mStatus = status;
1656 mRecentStatusUpdates.add(mStatus);
1657 mStatusChanged.broadcast();
1658}
1659
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001660// Pause to reconfigure
1661status_t Camera3Device::internalPauseAndWaitLocked() {
1662 mRequestThread->setPaused(true);
1663 mPauseStateNotify = true;
1664
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001665 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001666 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1667 if (res != OK) {
1668 SET_ERR_L("Can't idle device in %f seconds!",
1669 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001670 }
1671
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 return res;
1673}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675// Resume after internalPauseAndWaitLocked
1676status_t Camera3Device::internalResumeLocked() {
1677 status_t res;
1678
1679 mRequestThread->setPaused(false);
1680
1681 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1682 if (res != OK) {
1683 SET_ERR_L("Can't transition to active in %f seconds!",
1684 kActiveTimeout/1e9);
1685 }
1686 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001687 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001688}
1689
Ruben Brunk183f0562015-08-12 12:55:02 -07001690status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001692
1693 size_t startIndex = 0;
1694 if (mStatusWaiters == 0) {
1695 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1696 // this status list
1697 mRecentStatusUpdates.clear();
1698 } else {
1699 // If other threads are waiting on updates to this status list, set the position of the
1700 // first element that this list will check rather than clearing the list.
1701 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001702 }
1703
Ruben Brunk183f0562015-08-12 12:55:02 -07001704 mStatusWaiters++;
1705
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 bool stateSeen = false;
1707 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001708 if (active == (mStatus == STATUS_ACTIVE)) {
1709 // Desired state is current
1710 break;
1711 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001712
1713 res = mStatusChanged.waitRelative(mLock, timeout);
1714 if (res != OK) break;
1715
Ruben Brunk183f0562015-08-12 12:55:02 -07001716 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1717 // transitions.
1718 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1719 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1720 __FUNCTION__);
1721
1722 // Encountered desired state since we began waiting
1723 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001724 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1725 stateSeen = true;
1726 break;
1727 }
1728 }
1729 } while (!stateSeen);
1730
Ruben Brunk183f0562015-08-12 12:55:02 -07001731 mStatusWaiters--;
1732
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001733 return res;
1734}
1735
1736
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001737status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001738 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001739 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001741 if (listener != NULL && mListener != NULL) {
1742 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1743 }
1744 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001745 mRequestThread->setNotificationListener(listener);
1746 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001747
1748 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749}
1750
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001751bool Camera3Device::willNotify3A() {
1752 return false;
1753}
1754
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001755status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001756 status_t res;
1757 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001758
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001759 while (mResultQueue.empty()) {
1760 res = mResultSignal.waitRelative(mOutputLock, timeout);
1761 if (res == TIMED_OUT) {
1762 return res;
1763 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001764 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1765 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001766 return res;
1767 }
1768 }
1769 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770}
1771
Jianing Weicb0652e2014-03-12 18:29:36 -07001772status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001773 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001774 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001775
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001776 if (mResultQueue.empty()) {
1777 return NOT_ENOUGH_DATA;
1778 }
1779
Jianing Weicb0652e2014-03-12 18:29:36 -07001780 if (frame == NULL) {
1781 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1782 return BAD_VALUE;
1783 }
1784
1785 CaptureResult &result = *(mResultQueue.begin());
1786 frame->mResultExtras = result.mResultExtras;
1787 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001788 mResultQueue.erase(mResultQueue.begin());
1789
1790 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001791}
1792
1793status_t Camera3Device::triggerAutofocus(uint32_t id) {
1794 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001796
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001797 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1798 // Mix-in this trigger into the next request and only the next request.
1799 RequestTrigger trigger[] = {
1800 {
1801 ANDROID_CONTROL_AF_TRIGGER,
1802 ANDROID_CONTROL_AF_TRIGGER_START
1803 },
1804 {
1805 ANDROID_CONTROL_AF_TRIGGER_ID,
1806 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001807 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001808 };
1809
1810 return mRequestThread->queueTrigger(trigger,
1811 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001812}
1813
1814status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1815 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001816 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001817
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001818 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1819 // Mix-in this trigger into the next request and only the next request.
1820 RequestTrigger trigger[] = {
1821 {
1822 ANDROID_CONTROL_AF_TRIGGER,
1823 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1824 },
1825 {
1826 ANDROID_CONTROL_AF_TRIGGER_ID,
1827 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001828 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001829 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001830
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001831 return mRequestThread->queueTrigger(trigger,
1832 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001833}
1834
1835status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1836 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001837 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001838
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001839 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1840 // Mix-in this trigger into the next request and only the next request.
1841 RequestTrigger trigger[] = {
1842 {
1843 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1844 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1845 },
1846 {
1847 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1848 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001849 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001850 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001851
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001852 return mRequestThread->queueTrigger(trigger,
1853 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001854}
1855
1856status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1857 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1858 ATRACE_CALL();
1859 (void)reprocessStreamId; (void)buffer; (void)listener;
1860
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001861 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001862 return INVALID_OPERATION;
1863}
1864
Jianing Weicb0652e2014-03-12 18:29:36 -07001865status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001866 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001867 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001868 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001869
Zhijun He7ef20392014-04-21 16:04:17 -07001870 {
1871 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001872 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001873 }
1874
Zhijun He491e3412013-12-27 10:57:44 -08001875 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001876 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001877 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001878 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001879 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001880 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001881 }
1882
1883 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001884}
1885
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001886status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001887 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1888}
1889
1890status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001891 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001892 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001893 Mutex::Autolock il(mInterfaceLock);
1894 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001895
1896 sp<Camera3StreamInterface> stream;
1897 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1898 if (outputStreamIdx == NAME_NOT_FOUND) {
1899 CLOGE("Stream %d does not exist", streamId);
1900 return BAD_VALUE;
1901 }
1902
1903 stream = mOutputStreams.editValueAt(outputStreamIdx);
1904
1905 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001906 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001907 return BAD_VALUE;
1908 }
1909
1910 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001911 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001912 return BAD_VALUE;
1913 }
1914
Ruben Brunkc78ac262015-08-13 17:58:46 -07001915 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001916}
1917
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001918status_t Camera3Device::tearDown(int streamId) {
1919 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001920 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001921 Mutex::Autolock il(mInterfaceLock);
1922 Mutex::Autolock l(mLock);
1923
1924 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1925 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001926 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001927 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001928 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001929 return NO_INIT;
1930 }
1931
1932 sp<Camera3StreamInterface> stream;
1933 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1934 if (outputStreamIdx == NAME_NOT_FOUND) {
1935 CLOGE("Stream %d does not exist", streamId);
1936 return BAD_VALUE;
1937 }
1938
1939 stream = mOutputStreams.editValueAt(outputStreamIdx);
1940
1941 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1942 CLOGE("Stream %d is a target of a in-progress request", streamId);
1943 return BAD_VALUE;
1944 }
1945
1946 return stream->tearDown();
1947}
1948
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001949status_t Camera3Device::addBufferListenerForStream(int streamId,
1950 wp<Camera3StreamBufferListener> listener) {
1951 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001952 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001953 Mutex::Autolock il(mInterfaceLock);
1954 Mutex::Autolock l(mLock);
1955
1956 sp<Camera3StreamInterface> stream;
1957 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1958 if (outputStreamIdx == NAME_NOT_FOUND) {
1959 CLOGE("Stream %d does not exist", streamId);
1960 return BAD_VALUE;
1961 }
1962
1963 stream = mOutputStreams.editValueAt(outputStreamIdx);
1964 stream->addBufferListener(listener);
1965
1966 return OK;
1967}
1968
Zhijun He204e3292014-07-14 17:09:23 -07001969uint32_t Camera3Device::getDeviceVersion() {
1970 ATRACE_CALL();
1971 Mutex::Autolock il(mInterfaceLock);
1972 return mDeviceVersion;
1973}
1974
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001975/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001976 * Methods called by subclasses
1977 */
1978
1979void Camera3Device::notifyStatus(bool idle) {
1980 {
1981 // Need mLock to safely update state and synchronize to current
1982 // state of methods in flight.
1983 Mutex::Autolock l(mLock);
1984 // We can get various system-idle notices from the status tracker
1985 // while starting up. Only care about them if we've actually sent
1986 // in some requests recently.
1987 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1988 return;
1989 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001990 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001991 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001992 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001993
1994 // Skip notifying listener if we're doing some user-transparent
1995 // state changes
1996 if (mPauseStateNotify) return;
1997 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001998
1999 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002000 {
2001 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002002 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002003 }
2004 if (idle && listener != NULL) {
2005 listener->notifyIdle();
2006 }
2007}
2008
Zhijun He5d677d12016-05-29 16:52:39 -07002009status_t Camera3Device::setConsumerSurface(int streamId, sp<Surface> consumer) {
2010 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002011 ALOGV("%s: Camera %s: set consumer surface for stream %d", __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002012 Mutex::Autolock il(mInterfaceLock);
2013 Mutex::Autolock l(mLock);
2014
2015 if (consumer == nullptr) {
2016 CLOGE("Null consumer is passed!");
2017 return BAD_VALUE;
2018 }
2019
2020 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2021 if (idx == NAME_NOT_FOUND) {
2022 CLOGE("Stream %d is unknown", streamId);
2023 return idx;
2024 }
2025 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2026 status_t res = stream->setConsumer(consumer);
2027 if (res != OK) {
2028 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2029 return res;
2030 }
2031
2032 if (!stream->isConfiguring()) {
2033 CLOGE("Stream %d was already fully configured.", streamId);
2034 return INVALID_OPERATION;
2035 }
2036
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002037 res = stream->finishConfiguration();
Zhijun He5d677d12016-05-29 16:52:39 -07002038 if (res != OK) {
2039 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2040 stream->getId(), strerror(-res), res);
2041 return res;
2042 }
2043
2044 return OK;
2045}
2046
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002047/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 * Camera3Device private methods
2049 */
2050
2051sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
2052 const CameraMetadata &request) {
2053 ATRACE_CALL();
2054 status_t res;
2055
2056 sp<CaptureRequest> newRequest = new CaptureRequest;
2057 newRequest->mSettings = request;
2058
2059 camera_metadata_entry_t inputStreams =
2060 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2061 if (inputStreams.count > 0) {
2062 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002063 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002064 CLOGE("Request references unknown input stream %d",
2065 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066 return NULL;
2067 }
2068 // Lazy completion of stream configuration (allocation/registration)
2069 // on first use
2070 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002071 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002073 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002075 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076 return NULL;
2077 }
2078 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002079 // Check if stream is being prepared
2080 if (mInputStream->isPreparing()) {
2081 CLOGE("Request references an input stream that's being prepared!");
2082 return NULL;
2083 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084
2085 newRequest->mInputStream = mInputStream;
2086 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2087 }
2088
2089 camera_metadata_entry_t streams =
2090 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2091 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002092 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093 return NULL;
2094 }
2095
2096 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002097 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002099 CLOGE("Request references unknown stream %d",
2100 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002101 return NULL;
2102 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002103 sp<Camera3OutputStreamInterface> stream =
2104 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105
Zhijun He5d677d12016-05-29 16:52:39 -07002106 // It is illegal to include a deferred consumer output stream into a request
2107 if (stream->isConsumerConfigurationDeferred()) {
2108 CLOGE("Stream %d hasn't finished configuration yet due to deferred consumer",
2109 stream->getId());
2110 return NULL;
2111 }
2112
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 // Lazy completion of stream configuration (allocation/registration)
2114 // on first use
2115 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002116 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002118 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2119 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120 return NULL;
2121 }
2122 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002123 // Check if stream is being prepared
2124 if (stream->isPreparing()) {
2125 CLOGE("Request references an output stream that's being prepared!");
2126 return NULL;
2127 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128
2129 newRequest->mOutputStreams.push(stream);
2130 }
2131 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002132 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133
2134 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002135}
2136
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002137bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2138 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2139 Size size = mSupportedOpaqueInputSizes[i];
2140 if (size.width == width && size.height == height) {
2141 return true;
2142 }
2143 }
2144
2145 return false;
2146}
2147
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002148void Camera3Device::cancelStreamsConfigurationLocked() {
2149 int res = OK;
2150 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2151 res = mInputStream->cancelConfiguration();
2152 if (res != OK) {
2153 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2154 mInputStream->getId(), strerror(-res), res);
2155 }
2156 }
2157
2158 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2159 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2160 if (outputStream->isConfiguring()) {
2161 res = outputStream->cancelConfiguration();
2162 if (res != OK) {
2163 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2164 outputStream->getId(), strerror(-res), res);
2165 }
2166 }
2167 }
2168
2169 // Return state to that at start of call, so that future configures
2170 // properly clean things up
2171 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2172 mNeedConfig = true;
2173}
2174
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175status_t Camera3Device::configureStreamsLocked() {
2176 ATRACE_CALL();
2177 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002178
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002179 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002180 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181 return INVALID_OPERATION;
2182 }
2183
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002184 if (!mNeedConfig) {
2185 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2186 return OK;
2187 }
2188
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002189 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2190 // adding a dummy stream instead.
2191 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2192 if (mOutputStreams.size() == 0) {
2193 addDummyStreamLocked();
2194 } else {
2195 tryRemoveDummyStreamLocked();
2196 }
2197
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002199 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200
2201 camera3_stream_configuration config;
Zhijun He1fa89992015-06-01 15:44:31 -07002202 config.operation_mode = mIsConstrainedHighSpeedConfiguration ?
2203 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE :
2204 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2206
2207 Vector<camera3_stream_t*> streams;
2208 streams.setCapacity(config.num_streams);
2209
2210 if (mInputStream != NULL) {
2211 camera3_stream_t *inputStream;
2212 inputStream = mInputStream->startConfiguration();
2213 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002214 CLOGE("Can't start input stream configuration");
2215 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002216 return INVALID_OPERATION;
2217 }
2218 streams.add(inputStream);
2219 }
2220
2221 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002222
2223 // Don't configure bidi streams twice, nor add them twice to the list
2224 if (mOutputStreams[i].get() ==
2225 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2226
2227 config.num_streams--;
2228 continue;
2229 }
2230
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 camera3_stream_t *outputStream;
2232 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2233 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002234 CLOGE("Can't start output stream configuration");
2235 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002236 return INVALID_OPERATION;
2237 }
2238 streams.add(outputStream);
2239 }
2240
2241 config.streams = streams.editArray();
2242
2243 // Do the HAL configuration; will potentially touch stream
2244 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002245
2246 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002248 if (res == BAD_VALUE) {
2249 // HAL rejected this set of streams as unsupported, clean up config
2250 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002251 CLOGE("Set of requested inputs/outputs not supported by HAL");
2252 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002253 return BAD_VALUE;
2254 } else if (res != OK) {
2255 // Some other kind of error from configure_streams - this is not
2256 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002257 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2258 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259 return res;
2260 }
2261
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002262 // Finish all stream configuration immediately.
2263 // TODO: Try to relax this later back to lazy completion, which should be
2264 // faster
2265
Igor Murashkin073f8572013-05-02 14:59:28 -07002266 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002267 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002268 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002269 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002270 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002271 cancelStreamsConfigurationLocked();
2272 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002273 }
2274 }
2275
2276 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002277 sp<Camera3OutputStreamInterface> outputStream =
2278 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002279 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002280 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002281 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002282 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002283 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002284 cancelStreamsConfigurationLocked();
2285 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002286 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002287 }
2288 }
2289
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290 // Request thread needs to know to avoid using repeat-last-settings protocol
2291 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002292 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293
Zhijun He90f7c372016-08-16 16:19:43 -07002294 char value[PROPERTY_VALUE_MAX];
2295 property_get("camera.fifo.disable", value, "0");
2296 int32_t disableFifo = atoi(value);
2297 if (disableFifo != 1) {
2298 // Boost priority of request thread to SCHED_FIFO.
2299 pid_t requestThreadTid = mRequestThread->getTid();
2300 res = requestPriority(getpid(), requestThreadTid,
2301 kRequestThreadPriority, /*asynchronous*/ false);
2302 if (res != OK) {
2303 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2304 strerror(-res), res);
2305 } else {
2306 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2307 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002308 }
2309
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002310 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002312 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313
Ruben Brunk183f0562015-08-12 12:55:02 -07002314 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2315 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002316
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002317 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002318
Zhijun He0a210512014-07-24 13:45:15 -07002319 // tear down the deleted streams after configure streams.
2320 mDeletedStreams.clear();
2321
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002322 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002323}
2324
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002325status_t Camera3Device::addDummyStreamLocked() {
2326 ATRACE_CALL();
2327 status_t res;
2328
2329 if (mDummyStreamId != NO_STREAM) {
2330 // Should never be adding a second dummy stream when one is already
2331 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002332 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2333 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002334 return INVALID_OPERATION;
2335 }
2336
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002337 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002338
2339 sp<Camera3OutputStreamInterface> dummyStream =
2340 new Camera3DummyStream(mNextStreamId);
2341
2342 res = mOutputStreams.add(mNextStreamId, dummyStream);
2343 if (res < 0) {
2344 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2345 return res;
2346 }
2347
2348 mDummyStreamId = mNextStreamId;
2349 mNextStreamId++;
2350
2351 return OK;
2352}
2353
2354status_t Camera3Device::tryRemoveDummyStreamLocked() {
2355 ATRACE_CALL();
2356 status_t res;
2357
2358 if (mDummyStreamId == NO_STREAM) return OK;
2359 if (mOutputStreams.size() == 1) return OK;
2360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002361 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002362
2363 // Ok, have a dummy stream and there's at least one other output stream,
2364 // so remove the dummy
2365
2366 sp<Camera3StreamInterface> deletedStream;
2367 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2368 if (outputStreamIdx == NAME_NOT_FOUND) {
2369 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2370 return INVALID_OPERATION;
2371 }
2372
2373 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2374 mOutputStreams.removeItemsAt(outputStreamIdx);
2375
2376 // Free up the stream endpoint so that it can be used by some other stream
2377 res = deletedStream->disconnect();
2378 if (res != OK) {
2379 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2380 // fall through since we want to still list the stream as deleted.
2381 }
2382 mDeletedStreams.add(deletedStream);
2383 mDummyStreamId = NO_STREAM;
2384
2385 return res;
2386}
2387
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002388void Camera3Device::setErrorState(const char *fmt, ...) {
2389 Mutex::Autolock l(mLock);
2390 va_list args;
2391 va_start(args, fmt);
2392
2393 setErrorStateLockedV(fmt, args);
2394
2395 va_end(args);
2396}
2397
2398void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2399 Mutex::Autolock l(mLock);
2400 setErrorStateLockedV(fmt, args);
2401}
2402
2403void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2404 va_list args;
2405 va_start(args, fmt);
2406
2407 setErrorStateLockedV(fmt, args);
2408
2409 va_end(args);
2410}
2411
2412void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002413 // Print out all error messages to log
2414 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002415 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002416
2417 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002418 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002419
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002420 mErrorCause = errorCause;
2421
2422 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002423 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002424
2425 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002426 sp<NotificationListener> listener = mListener.promote();
2427 if (listener != NULL) {
2428 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002429 CaptureResultExtras());
2430 }
2431
2432 // Save stack trace. View by dumping it later.
2433 CameraTraces::saveTrace();
2434 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002435}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436
2437/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002438 * In-flight request management
2439 */
2440
Jianing Weicb0652e2014-03-12 18:29:36 -07002441status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002442 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2443 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002444 ATRACE_CALL();
2445 Mutex::Autolock l(mInFlightLock);
2446
2447 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002448 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2449 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002450 if (res < 0) return res;
2451
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002452 if (mInFlightMap.size() == 1) {
2453 mStatusTracker->markComponentActive(mInFlightStatusId);
2454 }
2455
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002456 return OK;
2457}
2458
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002459void Camera3Device::returnOutputBuffers(
2460 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2461 nsecs_t timestamp) {
2462 for (size_t i = 0; i < numBuffers; i++)
2463 {
2464 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2465 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2466 // Note: stream may be deallocated at this point, if this buffer was
2467 // the last reference to it.
2468 if (res != OK) {
2469 ALOGE("Can't return buffer to its stream: %s (%d)",
2470 strerror(-res), res);
2471 }
2472 }
2473}
2474
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002475void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2476 mInFlightMap.removeItemsAt(idx, 1);
2477
2478 // Indicate idle inFlightMap to the status tracker
2479 if (mInFlightMap.size() == 0) {
2480 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2481 }
2482}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002483
2484void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2485
2486 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2487 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2488
2489 nsecs_t sensorTimestamp = request.sensorTimestamp;
2490 nsecs_t shutterTimestamp = request.shutterTimestamp;
2491
2492 // Check if it's okay to remove the request from InFlightMap:
2493 // In the case of a successful request:
2494 // all input and output buffers, all result metadata, shutter callback
2495 // arrived.
2496 // In the case of a unsuccessful request:
2497 // all input and output buffers arrived.
2498 if (request.numBuffersLeft == 0 &&
2499 (request.requestStatus != OK ||
2500 (request.haveResultMetadata && shutterTimestamp != 0))) {
2501 ATRACE_ASYNC_END("frame capture", frameNumber);
2502
2503 // Sanity check - if sensor timestamp matches shutter timestamp
2504 if (request.requestStatus == OK &&
2505 sensorTimestamp != shutterTimestamp) {
2506 SET_ERR("sensor timestamp (%" PRId64
2507 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2508 sensorTimestamp, frameNumber, shutterTimestamp);
2509 }
2510
2511 // for an unsuccessful request, it may have pending output buffers to
2512 // return.
2513 assert(request.requestStatus != OK ||
2514 request.pendingOutputBuffers.size() == 0);
2515 returnOutputBuffers(request.pendingOutputBuffers.array(),
2516 request.pendingOutputBuffers.size(), 0);
2517
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002518 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002519 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2520 }
2521
2522 // Sanity check - if we have too many in-flight frames, something has
2523 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002524 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002525 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002526 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2527 kInFlightWarnLimitHighSpeed) {
2528 CLOGE("In-flight list too large for high speed configuration: %zu",
2529 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002530 }
2531}
2532
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002533void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2534 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2535 if (result == nullptr) return;
2536
2537 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2538 (int32_t*)&frameNumber, 1) != OK) {
2539 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2540 return;
2541 }
2542
2543 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2544 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2545 return;
2546 }
2547
2548 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2549
2550 // Valid result, insert into queue
2551 List<CaptureResult>::iterator queuedResult =
2552 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2553 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2554 ", burstId = %" PRId32, __FUNCTION__,
2555 queuedResult->mResultExtras.requestId,
2556 queuedResult->mResultExtras.frameNumber,
2557 queuedResult->mResultExtras.burstId);
2558
2559 mResultSignal.signal();
2560}
2561
2562
2563void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2564 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2565 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2566 Mutex::Autolock l(mOutputLock);
2567
2568 CaptureResult captureResult;
2569 captureResult.mResultExtras = resultExtras;
2570 captureResult.mMetadata = partialResult;
2571
2572 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2573}
2574
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002575
2576void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2577 CaptureResultExtras &resultExtras,
2578 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002579 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002580 bool reprocess,
2581 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002582 if (pendingMetadata.isEmpty())
2583 return;
2584
2585 Mutex::Autolock l(mOutputLock);
2586
2587 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002588 if (reprocess) {
2589 if (frameNumber < mNextReprocessResultFrameNumber) {
2590 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002591 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002592 frameNumber, mNextReprocessResultFrameNumber);
2593 return;
2594 }
2595 mNextReprocessResultFrameNumber = frameNumber + 1;
2596 } else {
2597 if (frameNumber < mNextResultFrameNumber) {
2598 SET_ERR("Out-of-order capture result metadata submitted! "
2599 "(got frame number %d, expecting %d)",
2600 frameNumber, mNextResultFrameNumber);
2601 return;
2602 }
2603 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002604 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002605
2606 CaptureResult captureResult;
2607 captureResult.mResultExtras = resultExtras;
2608 captureResult.mMetadata = pendingMetadata;
2609
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002610 // Append any previous partials to form a complete result
2611 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2612 captureResult.mMetadata.append(collectedPartialResult);
2613 }
2614
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002615 // Derive some new keys for backward compaibility
2616 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2617 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2618 int32_t defaultBoost[1] = {100};
2619 captureResult.mMetadata.update(
2620 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2621 defaultBoost, 1);
2622 }
2623
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002624 captureResult.mMetadata.sort();
2625
2626 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002627 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2628 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002629 SET_ERR("No timestamp provided by HAL for frame %d!",
2630 frameNumber);
2631 return;
2632 }
2633
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002634 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2635 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2636
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002637 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002638}
2639
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002640/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641 * Camera HAL device callback methods
2642 */
2643
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002644void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002645 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002646
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002647 status_t res;
2648
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002649 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002650 if (result->result == NULL && result->num_output_buffers == 0 &&
2651 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002652 SET_ERR("No result data provided by HAL for frame %d",
2653 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002654 return;
2655 }
Zhijun He204e3292014-07-14 17:09:23 -07002656
2657 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2658 // partial_result to 1 when metadata is included in this result.
2659 if (!mUsePartialResult &&
2660 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2661 result->result != NULL &&
2662 result->partial_result != 1) {
2663 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2664 " if partial result is not supported",
2665 frameNumber, result->partial_result);
2666 return;
2667 }
2668
2669 bool isPartialResult = false;
2670 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002671 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002672 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002673
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002674 // Get shutter timestamp and resultExtras from list of in-flight requests,
2675 // where it was added by the shutter notification for this frame. If the
2676 // shutter timestamp isn't received yet, append the output buffers to the
2677 // in-flight request and they will be returned when the shutter timestamp
2678 // arrives. Update the in-flight status and remove the in-flight entry if
2679 // all result data and shutter timestamp have been received.
2680 nsecs_t shutterTimestamp = 0;
2681
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002682 {
2683 Mutex::Autolock l(mInFlightLock);
2684 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2685 if (idx == NAME_NOT_FOUND) {
2686 SET_ERR("Unknown frame number for capture result: %d",
2687 frameNumber);
2688 return;
2689 }
2690 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002691 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2692 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2693 ", partialResultCount = %d",
2694 __FUNCTION__, request.resultExtras.requestId,
2695 request.resultExtras.frameNumber, request.resultExtras.burstId,
2696 result->partial_result);
2697 // Always update the partial count to the latest one if it's not 0
2698 // (buffers only). When framework aggregates adjacent partial results
2699 // into one, the latest partial count will be used.
2700 if (result->partial_result != 0)
2701 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002702
2703 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002704 if (mUsePartialResult && result->result != NULL) {
2705 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2706 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2707 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2708 " the range of [1, %d] when metadata is included in the result",
2709 frameNumber, result->partial_result, mNumPartialResults);
2710 return;
2711 }
2712 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002713 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002714 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002715 }
Zhijun He204e3292014-07-14 17:09:23 -07002716 } else {
2717 camera_metadata_ro_entry_t partialResultEntry;
2718 res = find_camera_metadata_ro_entry(result->result,
2719 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2720 if (res != NAME_NOT_FOUND &&
2721 partialResultEntry.count > 0 &&
2722 partialResultEntry.data.u8[0] ==
2723 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2724 // A partial result. Flag this as such, and collect this
2725 // set of metadata into the in-flight entry.
2726 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002727 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002728 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002729 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002730 ANDROID_QUIRKS_PARTIAL_RESULT);
2731 }
2732 }
2733
2734 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002735 // Send partial capture result
2736 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2737 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002738 }
2739 }
2740
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002741 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002742 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002743
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002744 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002745 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002746 if (request.haveResultMetadata) {
2747 SET_ERR("Called multiple times with metadata for frame %d",
2748 frameNumber);
2749 return;
2750 }
Zhijun He204e3292014-07-14 17:09:23 -07002751 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002752 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002753 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002754 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002755 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002756 request.haveResultMetadata = true;
2757 }
2758
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002759 uint32_t numBuffersReturned = result->num_output_buffers;
2760 if (result->input_buffer != NULL) {
2761 if (hasInputBufferInRequest) {
2762 numBuffersReturned += 1;
2763 } else {
2764 ALOGW("%s: Input buffer should be NULL if there is no input"
2765 " buffer sent in the request",
2766 __FUNCTION__);
2767 }
2768 }
2769 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002770 if (request.numBuffersLeft < 0) {
2771 SET_ERR("Too many buffers returned for frame %d",
2772 frameNumber);
2773 return;
2774 }
2775
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002776 camera_metadata_ro_entry_t entry;
2777 res = find_camera_metadata_ro_entry(result->result,
2778 ANDROID_SENSOR_TIMESTAMP, &entry);
2779 if (res == OK && entry.count == 1) {
2780 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002781 }
2782
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002783 // If shutter event isn't received yet, append the output buffers to
2784 // the in-flight request. Otherwise, return the output buffers to
2785 // streams.
2786 if (shutterTimestamp == 0) {
2787 request.pendingOutputBuffers.appendArray(result->output_buffers,
2788 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002789 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790 returnOutputBuffers(result->output_buffers,
2791 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002792 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002793
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002794 if (result->result != NULL && !isPartialResult) {
2795 if (shutterTimestamp == 0) {
2796 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002797 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002798 } else {
2799 CameraMetadata metadata;
2800 metadata = result->result;
2801 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002802 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2803 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002804 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002805 }
2806
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002807 removeInFlightRequestIfReadyLocked(idx);
2808 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002809
Zhijun Hef0d962a2014-06-30 10:24:11 -07002810 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002811 if (hasInputBufferInRequest) {
2812 Camera3Stream *stream =
2813 Camera3Stream::cast(result->input_buffer->stream);
2814 res = stream->returnInputBuffer(*(result->input_buffer));
2815 // Note: stream may be deallocated at this point, if this buffer was the
2816 // last reference to it.
2817 if (res != OK) {
2818 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2819 " its stream:%s (%d)", __FUNCTION__,
2820 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002821 }
2822 } else {
2823 ALOGW("%s: Input buffer should be NULL if there is no input"
2824 " buffer sent in the request, skipping input buffer return.",
2825 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002826 }
2827 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002828}
2829
2830void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002831 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002832 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002833 {
2834 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002835 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002836 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002837
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002838 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002839 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002840 return;
2841 }
2842
2843 switch (msg->type) {
2844 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002845 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002846 break;
2847 }
2848 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002849 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002850 break;
2851 }
2852 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002853 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002854 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002855 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002856}
2857
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002859 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002860
2861 // Map camera HAL error codes to ICameraDeviceCallback error codes
2862 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002863 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002864 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002865 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002866 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002867 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002869 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002870 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002871 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002872 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002873 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002874 };
2875
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002876 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002877 ((msg.error_code >= 0) &&
2878 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2879 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002880 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002881
2882 int streamId = 0;
2883 if (msg.error_stream != NULL) {
2884 Camera3Stream *stream =
2885 Camera3Stream::cast(msg.error_stream);
2886 streamId = stream->getId();
2887 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002888 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2889 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890 streamId, msg.error_code);
2891
2892 CaptureResultExtras resultExtras;
2893 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002894 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002895 // SET_ERR calls notifyError
2896 SET_ERR("Camera HAL reported serious device error");
2897 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002898 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2899 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2900 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002901 {
2902 Mutex::Autolock l(mInFlightLock);
2903 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2904 if (idx >= 0) {
2905 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2906 r.requestStatus = msg.error_code;
2907 resultExtras = r.resultExtras;
2908 } else {
2909 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002910 ALOGE("Camera %s: %s: cannot find in-flight request on "
2911 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002912 resultExtras.frameNumber);
2913 }
2914 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002915 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002916 if (listener != NULL) {
2917 listener->notifyError(errorCode, resultExtras);
2918 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002920 }
2921 break;
2922 default:
2923 // SET_ERR calls notifyError
2924 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2925 break;
2926 }
2927}
2928
2929void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002930 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002932
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002933 // Set timestamp for the request in the in-flight tracking
2934 // and get the request ID to send upstream
2935 {
2936 Mutex::Autolock l(mInFlightLock);
2937 idx = mInFlightMap.indexOfKey(msg.frame_number);
2938 if (idx >= 0) {
2939 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002940
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002941 // Verify ordering of shutter notifications
2942 {
2943 Mutex::Autolock l(mOutputLock);
2944 // TODO: need to track errors for tighter bounds on expected frame number.
2945 if (r.hasInputBuffer) {
2946 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2947 SET_ERR("Shutter notification out-of-order. Expected "
2948 "notification for frame %d, got frame %d",
2949 mNextReprocessShutterFrameNumber, msg.frame_number);
2950 return;
2951 }
2952 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2953 } else {
2954 if (msg.frame_number < mNextShutterFrameNumber) {
2955 SET_ERR("Shutter notification out-of-order. Expected "
2956 "notification for frame %d, got frame %d",
2957 mNextShutterFrameNumber, msg.frame_number);
2958 return;
2959 }
2960 mNextShutterFrameNumber = msg.frame_number + 1;
2961 }
2962 }
2963
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002964 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
2965 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002966 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
2967 // Call listener, if any
2968 if (listener != NULL) {
2969 listener->notifyShutter(r.resultExtras, msg.timestamp);
2970 }
2971
2972 r.shutterTimestamp = msg.timestamp;
2973
2974 // send pending result and buffers
2975 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002976 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002977 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002978 returnOutputBuffers(r.pendingOutputBuffers.array(),
2979 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2980 r.pendingOutputBuffers.clear();
2981
2982 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002983 }
2984 }
2985 if (idx < 0) {
2986 SET_ERR("Shutter notification for non-existent frame number %d",
2987 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002988 }
2989}
2990
2991
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002992CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002993 ALOGV("%s", __FUNCTION__);
2994
Igor Murashkin1e479c02013-09-06 16:55:14 -07002995 CameraMetadata retVal;
2996
2997 if (mRequestThread != NULL) {
2998 retVal = mRequestThread->getLatestRequest();
2999 }
3000
Igor Murashkin1e479c02013-09-06 16:55:14 -07003001 return retVal;
3002}
3003
Jianing Weicb0652e2014-03-12 18:29:36 -07003004
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003005void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3006 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3007 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3008}
3009
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003010/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003011 * HalInterface inner class methods
3012 */
3013
3014Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3015 mHal3Device(device) {}
3016
3017Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3018 mHal3Device(nullptr),
3019 mHidlSession(session) {}
3020
3021Camera3Device::HalInterface::HalInterface() :
3022 mHal3Device(nullptr) {}
3023
3024Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3025 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3026
3027bool Camera3Device::HalInterface::valid() {
3028 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3029}
3030
3031void Camera3Device::HalInterface::clear() {
3032 mHal3Device = nullptr;
3033 mHidlSession.clear();
3034}
3035
3036status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3037 camera3_request_template_t templateId,
3038 /*out*/ camera_metadata_t **requestTemplate) {
3039 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3040 if (!valid()) return INVALID_OPERATION;
3041 status_t res = OK;
3042
3043 if (mHal3Device != nullptr) {
3044 const camera_metadata *r;
3045 r = mHal3Device->ops->construct_default_request_settings(
3046 mHal3Device, templateId);
3047 if (r == nullptr) return BAD_VALUE;
3048 *requestTemplate = clone_camera_metadata(r);
3049 if (requestTemplate == nullptr) {
3050 ALOGE("%s: Unable to clone camera metadata received from HAL",
3051 __FUNCTION__);
3052 return INVALID_OPERATION;
3053 }
3054 } else {
3055 common::V1_0::Status status;
3056 RequestTemplate id;
3057 switch (templateId) {
3058 case CAMERA3_TEMPLATE_PREVIEW:
3059 id = RequestTemplate::PREVIEW;
3060 break;
3061 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3062 id = RequestTemplate::STILL_CAPTURE;
3063 break;
3064 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3065 id = RequestTemplate::VIDEO_RECORD;
3066 break;
3067 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3068 id = RequestTemplate::VIDEO_SNAPSHOT;
3069 break;
3070 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3071 id = RequestTemplate::ZERO_SHUTTER_LAG;
3072 break;
3073 case CAMERA3_TEMPLATE_MANUAL:
3074 id = RequestTemplate::MANUAL;
3075 break;
3076 default:
3077 // Unknown template ID
3078 return BAD_VALUE;
3079 }
3080 mHidlSession->constructDefaultRequestSettings(id,
3081 [&status, &requestTemplate]
3082 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3083 status = s;
3084 if (status == common::V1_0::Status::OK) {
3085 const camera_metadata *r =
3086 reinterpret_cast<const camera_metadata_t*>(request.data());
3087 size_t expectedSize = request.size();
3088 int ret = validate_camera_metadata_structure(r, &expectedSize);
3089 if (ret == OK) {
3090 *requestTemplate = clone_camera_metadata(r);
3091 if (*requestTemplate == nullptr) {
3092 ALOGE("%s: Unable to clone camera metadata received from HAL",
3093 __FUNCTION__);
3094 status = common::V1_0::Status::INTERNAL_ERROR;
3095 }
3096 } else {
3097 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3098 status = common::V1_0::Status::INTERNAL_ERROR;
3099 }
3100 }
3101 });
3102 res = CameraProviderManager::mapToStatusT(status);
3103 }
3104 return res;
3105}
3106
3107status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3108 ATRACE_NAME("CameraHal::configureStreams");
3109 if (!valid()) return INVALID_OPERATION;
3110 status_t res = OK;
3111
3112 if (mHal3Device != nullptr) {
3113 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3114 } else {
3115 // Convert stream config to HIDL
3116
3117 StreamConfiguration requestedConfiguration;
3118 requestedConfiguration.streams.resize(config->num_streams);
3119 for (size_t i = 0; i < config->num_streams; i++) {
3120 Stream &dst = requestedConfiguration.streams[i];
3121 camera3_stream_t *src = config->streams[i];
3122
3123 int streamId = Camera3Stream::cast(src)->getId();
3124 StreamType streamType;
3125 switch (src->stream_type) {
3126 case CAMERA3_STREAM_OUTPUT:
3127 streamType = StreamType::OUTPUT;
3128 break;
3129 case CAMERA3_STREAM_INPUT:
3130 streamType = StreamType::INPUT;
3131 break;
3132 default:
3133 ALOGE("%s: Stream %d: Unsupported stream type %d",
3134 __FUNCTION__, streamId, config->streams[i]->stream_type);
3135 return BAD_VALUE;
3136 }
3137 dst.id = streamId;
3138 dst.streamType = streamType;
3139 dst.width = src->width;
3140 dst.height = src->height;
3141 dst.format = mapToPixelFormat(src->format);
3142 dst.usage = mapToConsumerUsage(src->usage);
3143 dst.dataSpace = mapToHidlDataspace(src->data_space);
3144 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3145 }
3146 requestedConfiguration.operationMode = mapToStreamConfigurationMode(
3147 (camera3_stream_configuration_mode_t) config->operation_mode);
3148
3149 // Invoke configureStreams
3150
3151 HalStreamConfiguration finalConfiguration;
3152 common::V1_0::Status status;
3153 mHidlSession->configureStreams(requestedConfiguration,
3154 [&status, &finalConfiguration]
3155 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3156 finalConfiguration = halConfiguration;
3157 status = s;
3158 });
3159 if (status != common::V1_0::Status::OK ) {
3160 return CameraProviderManager::mapToStatusT(status);
3161 }
3162
3163 // And convert output stream configuration from HIDL
3164
3165 for (size_t i = 0; i < config->num_streams; i++) {
3166 camera3_stream_t *dst = config->streams[i];
3167 int streamId = Camera3Stream::cast(dst)->getId();
3168
3169 // Start scan at i, with the assumption that the stream order matches
3170 size_t realIdx = i;
3171 bool found = false;
3172 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3173 if (finalConfiguration.streams[realIdx].id == streamId) {
3174 found = true;
3175 break;
3176 }
3177 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3178 }
3179 if (!found) {
3180 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3181 __FUNCTION__, streamId);
3182 return INVALID_OPERATION;
3183 }
3184 HalStream &src = finalConfiguration.streams[realIdx];
3185
3186 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3187 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3188 if (dst->format != overrideFormat) {
3189 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3190 streamId, dst->format);
3191 }
3192 } else {
3193 // Override allowed with IMPLEMENTATION_DEFINED
3194 dst->format = overrideFormat;
3195 }
3196
3197 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3198 if (src.producerUsage != 0) {
3199 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3200 __FUNCTION__, streamId);
3201 return INVALID_OPERATION;
3202 }
3203 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3204 } else {
3205 // OUTPUT
3206 if (src.consumerUsage != 0) {
3207 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3208 __FUNCTION__, streamId);
3209 return INVALID_OPERATION;
3210 }
3211 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3212 }
3213 dst->max_buffers = src.maxBuffers;
3214 }
3215 }
3216 return res;
3217}
3218
3219status_t Camera3Device::HalInterface::processCaptureRequest(
3220 camera3_capture_request_t *request) {
3221 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003222 if (!valid()) return INVALID_OPERATION;
3223 status_t res = OK;
3224
3225 if (mHal3Device != nullptr) {
3226 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3227 } else {
3228 device::V3_2::CaptureRequest captureRequest;
3229 captureRequest.frameNumber = request->frame_number;
3230 std::vector<native_handle_t*> handlesCreated;
3231 // A null request settings maps to a size-0 CameraMetadata
3232 if (request->settings != nullptr) {
3233 captureRequest.settings.setToExternal(
3234 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3235 get_camera_metadata_size(request->settings));
3236 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003237
3238 {
3239 std::lock_guard<std::mutex> lock(mInflightLock);
3240 if (request->input_buffer != nullptr) {
3241 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3242 captureRequest.inputBuffer.streamId = streamId;
3243 captureRequest.inputBuffer.buffer = *(request->input_buffer->buffer);
3244 captureRequest.inputBuffer.status = BufferStatus::OK;
3245 native_handle_t *acquireFence = nullptr;
3246 if (request->input_buffer->acquire_fence != -1) {
3247 acquireFence = native_handle_create(1,0);
3248 acquireFence->data[0] = request->input_buffer->acquire_fence;
3249 handlesCreated.push_back(acquireFence);
3250 }
3251 captureRequest.inputBuffer.acquireFence = acquireFence;
3252 captureRequest.inputBuffer.releaseFence = nullptr;
3253
3254 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3255 request->input_buffer->buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003256 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003257
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003258 captureRequest.outputBuffers.resize(request->num_output_buffers);
3259 for (size_t i = 0; i < request->num_output_buffers; i++) {
3260 const camera3_stream_buffer_t *src = request->output_buffers + i;
3261 StreamBuffer &dst = captureRequest.outputBuffers[i];
3262 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3263 dst.streamId = streamId;
3264 dst.buffer = *(src->buffer);
3265 dst.status = BufferStatus::OK;
3266 native_handle_t *acquireFence = nullptr;
3267 if (src->acquire_fence != -1) {
3268 acquireFence = native_handle_create(1,0);
3269 acquireFence->data[0] = src->acquire_fence;
3270 handlesCreated.push_back(acquireFence);
3271 }
3272 dst.acquireFence = acquireFence;
3273 dst.releaseFence = nullptr;
3274
3275 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3276 src->buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003277 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003278 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003279 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3280
3281 for (auto& handle : handlesCreated) {
3282 native_handle_delete(handle);
3283 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003284 res = CameraProviderManager::mapToStatusT(status);
3285 }
3286 return res;
3287}
3288
3289status_t Camera3Device::HalInterface::flush() {
3290 ATRACE_NAME("CameraHal::flush");
3291 if (!valid()) return INVALID_OPERATION;
3292 status_t res = OK;
3293
3294 if (mHal3Device != nullptr) {
3295 res = mHal3Device->ops->flush(mHal3Device);
3296 } else {
3297 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3298 }
3299 return res;
3300}
3301
3302status_t Camera3Device::HalInterface::dump(int fd) {
3303 ATRACE_NAME("CameraHal::dump");
3304 if (!valid()) return INVALID_OPERATION;
3305 status_t res = OK;
3306
3307 if (mHal3Device != nullptr) {
3308 mHal3Device->ops->dump(mHal3Device, fd);
3309 } else {
3310 // Handled by CameraProviderManager::dump
3311 }
3312 return res;
3313}
3314
3315status_t Camera3Device::HalInterface::close() {
3316 ATRACE_NAME("CameraHal::close()");
3317 if (!valid()) return INVALID_OPERATION;
3318 status_t res = OK;
3319
3320 if (mHal3Device != nullptr) {
3321 mHal3Device->common.close(&mHal3Device->common);
3322 } else {
3323 mHidlSession->close();
3324 }
3325 return res;
3326}
3327
3328status_t Camera3Device::HalInterface::pushInflightBufferLocked(
3329 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
3330 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3331 mInflightBufferMap[key] = buffer;
3332 return OK;
3333}
3334
3335status_t Camera3Device::HalInterface::popInflightBuffer(
3336 int32_t frameNumber, int32_t streamId, /*out*/ buffer_handle_t **buffer) {
3337 std::lock_guard<std::mutex> lock(mInflightLock);
3338
3339 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3340 auto it = mInflightBufferMap.find(key);
3341 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
3342 *buffer = it->second;
3343 mInflightBufferMap.erase(it);
3344 return OK;
3345}
3346
3347/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003348 * RequestThread inner class methods
3349 */
3350
3351Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003352 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003353 HalInterface* interface,
3354 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003355 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003356 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003357 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003358 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003359 mInterface(interface),
3360 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003361 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003362 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003363 mReconfigured(false),
3364 mDoPause(false),
3365 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003366 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003367 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003368 mCurrentAfTriggerId(0),
3369 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003370 mRepeatingLastFrameNumber(
3371 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003372 mAeLockAvailable(aeLockAvailable),
3373 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003374 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003375}
3376
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003377Camera3Device::RequestThread::~RequestThread() {}
3378
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003379void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003380 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003381 Mutex::Autolock l(mRequestLock);
3382 mListener = listener;
3383}
3384
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003385void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003386 Mutex::Autolock l(mRequestLock);
3387 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003388 // Prepare video stream for high speed recording.
3389 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003390}
3391
Jianing Wei90e59c92014-03-12 18:29:36 -07003392status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003393 List<sp<CaptureRequest> > &requests,
3394 /*out*/
3395 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003396 Mutex::Autolock l(mRequestLock);
3397 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3398 ++it) {
3399 mRequestQueue.push_back(*it);
3400 }
3401
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003402 if (lastFrameNumber != NULL) {
3403 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3404 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3405 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3406 *lastFrameNumber);
3407 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003408
Jianing Wei90e59c92014-03-12 18:29:36 -07003409 unpauseForNewRequests();
3410
3411 return OK;
3412}
3413
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003414
3415status_t Camera3Device::RequestThread::queueTrigger(
3416 RequestTrigger trigger[],
3417 size_t count) {
3418
3419 Mutex::Autolock l(mTriggerMutex);
3420 status_t ret;
3421
3422 for (size_t i = 0; i < count; ++i) {
3423 ret = queueTriggerLocked(trigger[i]);
3424
3425 if (ret != OK) {
3426 return ret;
3427 }
3428 }
3429
3430 return OK;
3431}
3432
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003433const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3434 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003435 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003436 if (d != nullptr) return d->mId;
3437 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003438}
3439
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003440status_t Camera3Device::RequestThread::queueTriggerLocked(
3441 RequestTrigger trigger) {
3442
3443 uint32_t tag = trigger.metadataTag;
3444 ssize_t index = mTriggerMap.indexOfKey(tag);
3445
3446 switch (trigger.getTagType()) {
3447 case TYPE_BYTE:
3448 // fall-through
3449 case TYPE_INT32:
3450 break;
3451 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003452 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3453 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003454 return INVALID_OPERATION;
3455 }
3456
3457 /**
3458 * Collect only the latest trigger, since we only have 1 field
3459 * in the request settings per trigger tag, and can't send more than 1
3460 * trigger per request.
3461 */
3462 if (index != NAME_NOT_FOUND) {
3463 mTriggerMap.editValueAt(index) = trigger;
3464 } else {
3465 mTriggerMap.add(tag, trigger);
3466 }
3467
3468 return OK;
3469}
3470
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003471status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003472 const RequestList &requests,
3473 /*out*/
3474 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003475 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003476 if (lastFrameNumber != NULL) {
3477 *lastFrameNumber = mRepeatingLastFrameNumber;
3478 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003479 mRepeatingRequests.clear();
3480 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3481 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003482
3483 unpauseForNewRequests();
3484
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003485 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003486 return OK;
3487}
3488
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003489bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003490 if (mRepeatingRequests.empty()) {
3491 return false;
3492 }
3493 int32_t requestId = requestIn->mResultExtras.requestId;
3494 const RequestList &repeatRequests = mRepeatingRequests;
3495 // All repeating requests are guaranteed to have same id so only check first quest
3496 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3497 return (firstRequest->mResultExtras.requestId == requestId);
3498}
3499
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003500status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003501 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003502 return clearRepeatingRequestsLocked(lastFrameNumber);
3503
3504}
3505
3506status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003507 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003508 if (lastFrameNumber != NULL) {
3509 *lastFrameNumber = mRepeatingLastFrameNumber;
3510 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003511 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003512 return OK;
3513}
3514
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003515status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003516 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003517 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003518 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003519
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003520 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003521
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003522 // Send errors for all requests pending in the request queue, including
3523 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003524 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003525 if (listener != NULL) {
3526 for (RequestList::iterator it = mRequestQueue.begin();
3527 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003528 // Abort the input buffers for reprocess requests.
3529 if ((*it)->mInputStream != NULL) {
3530 camera3_stream_buffer_t inputBuffer;
3531 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3532 if (res != OK) {
3533 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3534 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3535 } else {
3536 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3537 if (res != OK) {
3538 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3539 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3540 }
3541 }
3542 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003543 // Set the frame number this request would have had, if it
3544 // had been submitted; this frame number will not be reused.
3545 // The requestId and burstId fields were set when the request was
3546 // submitted originally (in convertMetadataListToRequestListLocked)
3547 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003548 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003549 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003550 }
3551 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003552 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003553
3554 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003555 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003556 if (lastFrameNumber != NULL) {
3557 *lastFrameNumber = mRepeatingLastFrameNumber;
3558 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003559 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003560 return OK;
3561}
3562
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003563status_t Camera3Device::RequestThread::flush() {
3564 ATRACE_CALL();
3565 Mutex::Autolock l(mFlushLock);
3566
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003567 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3568 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003569 }
3570
3571 return -ENOTSUP;
3572}
3573
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003574void Camera3Device::RequestThread::setPaused(bool paused) {
3575 Mutex::Autolock l(mPauseLock);
3576 mDoPause = paused;
3577 mDoPauseSignal.signal();
3578}
3579
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003580status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3581 int32_t requestId, nsecs_t timeout) {
3582 Mutex::Autolock l(mLatestRequestMutex);
3583 status_t res;
3584 while (mLatestRequestId != requestId) {
3585 nsecs_t startTime = systemTime();
3586
3587 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3588 if (res != OK) return res;
3589
3590 timeout -= (systemTime() - startTime);
3591 }
3592
3593 return OK;
3594}
3595
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003596void Camera3Device::RequestThread::requestExit() {
3597 // Call parent to set up shutdown
3598 Thread::requestExit();
3599 // The exit from any possible waits
3600 mDoPauseSignal.signal();
3601 mRequestSignal.signal();
3602}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003603
Chien-Yu Chend196d612015-06-22 19:49:01 -07003604
3605/**
3606 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3607 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3608 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3609 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3610 * request.
3611 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003612void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003613 request->mAeTriggerCancelOverride.applyAeLock = false;
3614 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3615
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003616 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003617 return;
3618 }
3619
3620 camera_metadata_entry_t aePrecaptureTrigger =
3621 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3622 if (aePrecaptureTrigger.count > 0 &&
3623 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3624 // Always override CANCEL to IDLE
3625 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3626 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3627 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3628 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3629 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3630
3631 if (mAeLockAvailable == true) {
3632 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3633 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3634 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3635 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3636 request->mAeTriggerCancelOverride.applyAeLock = true;
3637 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3638 }
3639 }
3640 }
3641}
3642
3643/**
3644 * Override result metadata for cancelling AE precapture trigger applied in
3645 * handleAePrecaptureCancelRequest().
3646 */
3647void Camera3Device::overrideResultForPrecaptureCancel(
3648 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3649 if (aeTriggerCancelOverride.applyAeLock) {
3650 // Only devices <= v3.2 should have this override
3651 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3652 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3653 }
3654
3655 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3656 // Only devices <= v3.2 should have this override
3657 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3658 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3659 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3660 }
3661}
3662
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003663void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003664 bool surfaceAbandoned = false;
3665 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003666 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003667 {
3668 Mutex::Autolock l(mRequestLock);
3669 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3670 // repeating requests.
3671 for (const auto& request : mRepeatingRequests) {
3672 for (const auto& s : request->mOutputStreams) {
3673 if (s->isAbandoned()) {
3674 surfaceAbandoned = true;
3675 clearRepeatingRequestsLocked(&lastFrameNumber);
3676 break;
3677 }
3678 }
3679 if (surfaceAbandoned) {
3680 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003681 }
3682 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003683 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003684 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003685
3686 if (listener != NULL && surfaceAbandoned) {
3687 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003688 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003689}
3690
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003691bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003692 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003693 status_t res;
3694
3695 // Handle paused state.
3696 if (waitIfPaused()) {
3697 return true;
3698 }
3699
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003700 // Wait for the next batch of requests.
3701 waitForNextRequestBatch();
3702 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003703 return true;
3704 }
3705
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003706 // Get the latest request ID, if any
3707 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003708 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003709 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003710 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003712 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003713 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3714 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003715 }
3716
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003717 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003718 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003719 if (res == TIMED_OUT) {
3720 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003721 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003722 // Check if any stream is abandoned.
3723 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003724 return true;
3725 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003726 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003727 return false;
3728 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003729
Zhijun Hecc27e112013-10-03 16:12:43 -07003730 // Inform waitUntilRequestProcessed thread of a new request ID
3731 {
3732 Mutex::Autolock al(mLatestRequestMutex);
3733
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003734 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003735 mLatestRequestSignal.signal();
3736 }
3737
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003738 // Submit a batch of requests to HAL.
3739 // Use flush lock only when submitting multilple requests in a batch.
3740 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3741 // which may take a long time to finish so synchronizing flush() and
3742 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3743 // For now, only synchronize for high speed recording and we should figure something out for
3744 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003745 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003746
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003747 if (useFlushLock) {
3748 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003749 }
3750
Zhijun Hef0645c12016-08-02 00:58:11 -07003751 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003752 mNextRequests.size());
3753 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003754 // Submit request and block until ready for next one
3755 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003756 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003757
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003758 if (res != OK) {
3759 // Should only get a failure here for malformed requests or device-level
3760 // errors, so consider all errors fatal. Bad metadata failures should
3761 // come through notify.
3762 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3763 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3764 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003765 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003766 if (useFlushLock) {
3767 mFlushLock.unlock();
3768 }
3769 return false;
3770 }
3771
3772 // Mark that the request has be submitted successfully.
3773 nextRequest.submitted = true;
3774
3775 // Update the latest request sent to HAL
3776 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3777 Mutex::Autolock al(mLatestRequestMutex);
3778
3779 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3780 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003781
3782 sp<Camera3Device> parent = mParent.promote();
3783 if (parent != NULL) {
3784 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3785 0, mLatestRequest);
3786 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003787 }
3788
3789 if (nextRequest.halRequest.settings != NULL) {
3790 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3791 }
3792
3793 // Remove any previously queued triggers (after unlock)
3794 res = removeTriggers(mPrevRequest);
3795 if (res != OK) {
3796 SET_ERR("RequestThread: Unable to remove triggers "
3797 "(capture request %d, HAL device: %s (%d)",
3798 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003799 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003800 if (useFlushLock) {
3801 mFlushLock.unlock();
3802 }
3803 return false;
3804 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003805 }
3806
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003807 if (useFlushLock) {
3808 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003809 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003810
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003811 // Unset as current request
3812 {
3813 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003814 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003815 }
3816
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003817 return true;
3818}
3819
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003820status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003821 ATRACE_CALL();
3822
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003823 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003824 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3825 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3826 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3827
3828 // Prepare a request to HAL
3829 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3830
3831 // Insert any queued triggers (before metadata is locked)
3832 status_t res = insertTriggers(captureRequest);
3833
3834 if (res < 0) {
3835 SET_ERR("RequestThread: Unable to insert triggers "
3836 "(capture request %d, HAL device: %s (%d)",
3837 halRequest->frame_number, strerror(-res), res);
3838 return INVALID_OPERATION;
3839 }
3840 int triggerCount = res;
3841 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3842 mPrevTriggers = triggerCount;
3843
3844 // If the request is the same as last, or we had triggers last time
3845 if (mPrevRequest != captureRequest || triggersMixedIn) {
3846 /**
3847 * HAL workaround:
3848 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3849 */
3850 res = addDummyTriggerIds(captureRequest);
3851 if (res != OK) {
3852 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3853 "(capture request %d, HAL device: %s (%d)",
3854 halRequest->frame_number, strerror(-res), res);
3855 return INVALID_OPERATION;
3856 }
3857
3858 /**
3859 * The request should be presorted so accesses in HAL
3860 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3861 */
3862 captureRequest->mSettings.sort();
3863 halRequest->settings = captureRequest->mSettings.getAndLock();
3864 mPrevRequest = captureRequest;
3865 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3866
3867 IF_ALOGV() {
3868 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3869 find_camera_metadata_ro_entry(
3870 halRequest->settings,
3871 ANDROID_CONTROL_AF_TRIGGER,
3872 &e
3873 );
3874 if (e.count > 0) {
3875 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3876 __FUNCTION__,
3877 halRequest->frame_number,
3878 e.data.u8[0]);
3879 }
3880 }
3881 } else {
3882 // leave request.settings NULL to indicate 'reuse latest given'
3883 ALOGVV("%s: Request settings are REUSED",
3884 __FUNCTION__);
3885 }
3886
3887 uint32_t totalNumBuffers = 0;
3888
3889 // Fill in buffers
3890 if (captureRequest->mInputStream != NULL) {
3891 halRequest->input_buffer = &captureRequest->mInputBuffer;
3892 totalNumBuffers += 1;
3893 } else {
3894 halRequest->input_buffer = NULL;
3895 }
3896
3897 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3898 captureRequest->mOutputStreams.size());
3899 halRequest->output_buffers = outputBuffers->array();
3900 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003901 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
3902
3903 // Prepare video buffers for high speed recording on the first video request.
3904 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3905 // Only try to prepare video stream on the first video request.
3906 mPrepareVideoStream = false;
3907
3908 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3909 while (res == NOT_ENOUGH_DATA) {
3910 res = outputStream->prepareNextBuffer();
3911 }
3912 if (res != OK) {
3913 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3914 __FUNCTION__, strerror(-res), res);
3915 outputStream->cancelPrepare();
3916 }
3917 }
3918
3919 res = outputStream->getBuffer(&outputBuffers->editItemAt(i));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003920 if (res != OK) {
3921 // Can't get output buffer from gralloc queue - this could be due to
3922 // abandoned queue or other consumer misbehavior, so not a fatal
3923 // error
3924 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3925 " %s (%d)", strerror(-res), res);
3926
3927 return TIMED_OUT;
3928 }
3929 halRequest->num_output_buffers++;
3930 }
3931 totalNumBuffers += halRequest->num_output_buffers;
3932
3933 // Log request in the in-flight queue
3934 sp<Camera3Device> parent = mParent.promote();
3935 if (parent == NULL) {
3936 // Should not happen, and nowhere to send errors to, so just log it
3937 CLOGE("RequestThread: Parent is gone");
3938 return INVALID_OPERATION;
3939 }
3940 res = parent->registerInFlight(halRequest->frame_number,
3941 totalNumBuffers, captureRequest->mResultExtras,
3942 /*hasInput*/halRequest->input_buffer != NULL,
3943 captureRequest->mAeTriggerCancelOverride);
3944 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3945 ", burstId = %" PRId32 ".",
3946 __FUNCTION__,
3947 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3948 captureRequest->mResultExtras.burstId);
3949 if (res != OK) {
3950 SET_ERR("RequestThread: Unable to register new in-flight request:"
3951 " %s (%d)", strerror(-res), res);
3952 return INVALID_OPERATION;
3953 }
3954 }
3955
3956 return OK;
3957}
3958
Igor Murashkin1e479c02013-09-06 16:55:14 -07003959CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
3960 Mutex::Autolock al(mLatestRequestMutex);
3961
3962 ALOGV("RequestThread::%s", __FUNCTION__);
3963
3964 return mLatestRequest;
3965}
3966
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003967bool Camera3Device::RequestThread::isStreamPending(
3968 sp<Camera3StreamInterface>& stream) {
3969 Mutex::Autolock l(mRequestLock);
3970
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003971 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003972 if (!nextRequest.submitted) {
3973 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3974 if (stream == s) return true;
3975 }
3976 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003977 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003978 }
3979
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003980 for (const auto& request : mRequestQueue) {
3981 for (const auto& s : request->mOutputStreams) {
3982 if (stream == s) return true;
3983 }
3984 if (stream == request->mInputStream) return true;
3985 }
3986
3987 for (const auto& request : mRepeatingRequests) {
3988 for (const auto& s : request->mOutputStreams) {
3989 if (stream == s) return true;
3990 }
3991 if (stream == request->mInputStream) return true;
3992 }
3993
3994 return false;
3995}
Jianing Weicb0652e2014-03-12 18:29:36 -07003996
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003997void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
3998 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003999 return;
4000 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004001
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004002 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004003 // Skip the ones that have been submitted successfully.
4004 if (nextRequest.submitted) {
4005 continue;
4006 }
4007
4008 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4009 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4010 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4011
4012 if (halRequest->settings != NULL) {
4013 captureRequest->mSettings.unlock(halRequest->settings);
4014 }
4015
4016 if (captureRequest->mInputStream != NULL) {
4017 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4018 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4019 }
4020
4021 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4022 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4023 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4024 }
4025
4026 if (sendRequestError) {
4027 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004028 sp<NotificationListener> listener = mListener.promote();
4029 if (listener != NULL) {
4030 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004031 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004032 captureRequest->mResultExtras);
4033 }
4034 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004035
4036 // Remove yet-to-be submitted inflight request from inflightMap
4037 {
4038 sp<Camera3Device> parent = mParent.promote();
4039 if (parent != NULL) {
4040 Mutex::Autolock l(parent->mInFlightLock);
4041 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4042 if (idx >= 0) {
4043 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4044 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4045 parent->removeInFlightMapEntryLocked(idx);
4046 }
4047 }
4048 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004049 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004050
4051 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004052 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004053}
4054
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004055void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004056 // Optimized a bit for the simple steady-state case (single repeating
4057 // request), to avoid putting that request in the queue temporarily.
4058 Mutex::Autolock l(mRequestLock);
4059
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004060 assert(mNextRequests.empty());
4061
4062 NextRequest nextRequest;
4063 nextRequest.captureRequest = waitForNextRequestLocked();
4064 if (nextRequest.captureRequest == nullptr) {
4065 return;
4066 }
4067
4068 nextRequest.halRequest = camera3_capture_request_t();
4069 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004070 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004071
4072 // Wait for additional requests
4073 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4074
4075 for (size_t i = 1; i < batchSize; i++) {
4076 NextRequest additionalRequest;
4077 additionalRequest.captureRequest = waitForNextRequestLocked();
4078 if (additionalRequest.captureRequest == nullptr) {
4079 break;
4080 }
4081
4082 additionalRequest.halRequest = camera3_capture_request_t();
4083 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004084 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004085 }
4086
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004087 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004088 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004089 mNextRequests.size(), batchSize);
4090 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004091 }
4092
4093 return;
4094}
4095
4096sp<Camera3Device::CaptureRequest>
4097 Camera3Device::RequestThread::waitForNextRequestLocked() {
4098 status_t res;
4099 sp<CaptureRequest> nextRequest;
4100
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004101 while (mRequestQueue.empty()) {
4102 if (!mRepeatingRequests.empty()) {
4103 // Always atomically enqueue all requests in a repeating request
4104 // list. Guarantees a complete in-sequence set of captures to
4105 // application.
4106 const RequestList &requests = mRepeatingRequests;
4107 RequestList::const_iterator firstRequest =
4108 requests.begin();
4109 nextRequest = *firstRequest;
4110 mRequestQueue.insert(mRequestQueue.end(),
4111 ++firstRequest,
4112 requests.end());
4113 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004114
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004115 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004116
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004117 break;
4118 }
4119
4120 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4121
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004122 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4123 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004124 Mutex::Autolock pl(mPauseLock);
4125 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004126 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004127 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004128 // Let the tracker know
4129 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4130 if (statusTracker != 0) {
4131 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4132 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004133 }
4134 // Stop waiting for now and let thread management happen
4135 return NULL;
4136 }
4137 }
4138
4139 if (nextRequest == NULL) {
4140 // Don't have a repeating request already in hand, so queue
4141 // must have an entry now.
4142 RequestList::iterator firstRequest =
4143 mRequestQueue.begin();
4144 nextRequest = *firstRequest;
4145 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004146 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4147 sp<NotificationListener> listener = mListener.promote();
4148 if (listener != NULL) {
4149 listener->notifyRequestQueueEmpty();
4150 }
4151 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152 }
4153
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004154 // In case we've been unpaused by setPaused clearing mDoPause, need to
4155 // update internal pause state (capture/setRepeatingRequest unpause
4156 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004158 if (mPaused) {
4159 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4160 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4161 if (statusTracker != 0) {
4162 statusTracker->markComponentActive(mStatusId);
4163 }
4164 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004165 mPaused = false;
4166
4167 // Check if we've reconfigured since last time, and reset the preview
4168 // request if so. Can't use 'NULL request == repeat' across configure calls.
4169 if (mReconfigured) {
4170 mPrevRequest.clear();
4171 mReconfigured = false;
4172 }
4173
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004174 if (nextRequest != NULL) {
4175 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004176 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4177 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004178
4179 // Since RequestThread::clear() removes buffers from the input stream,
4180 // get the right buffer here before unlocking mRequestLock
4181 if (nextRequest->mInputStream != NULL) {
4182 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4183 if (res != OK) {
4184 // Can't get input buffer from gralloc queue - this could be due to
4185 // disconnected queue or other producer misbehavior, so not a fatal
4186 // error
4187 ALOGE("%s: Can't get input buffer, skipping request:"
4188 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004189
4190 sp<NotificationListener> listener = mListener.promote();
4191 if (listener != NULL) {
4192 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004193 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004194 nextRequest->mResultExtras);
4195 }
4196 return NULL;
4197 }
4198 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004199 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004200
4201 handleAePrecaptureCancelRequest(nextRequest);
4202
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004203 return nextRequest;
4204}
4205
4206bool Camera3Device::RequestThread::waitIfPaused() {
4207 status_t res;
4208 Mutex::Autolock l(mPauseLock);
4209 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004210 if (mPaused == false) {
4211 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004212 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4213 // Let the tracker know
4214 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4215 if (statusTracker != 0) {
4216 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4217 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004218 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004219
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004221 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004222 return true;
4223 }
4224 }
4225 // We don't set mPaused to false here, because waitForNextRequest needs
4226 // to further manage the paused state in case of starvation.
4227 return false;
4228}
4229
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004230void Camera3Device::RequestThread::unpauseForNewRequests() {
4231 // With work to do, mark thread as unpaused.
4232 // If paused by request (setPaused), don't resume, to avoid
4233 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004234 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004235 Mutex::Autolock p(mPauseLock);
4236 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004237 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4238 if (mPaused) {
4239 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4240 if (statusTracker != 0) {
4241 statusTracker->markComponentActive(mStatusId);
4242 }
4243 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004244 mPaused = false;
4245 }
4246}
4247
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004248void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4249 sp<Camera3Device> parent = mParent.promote();
4250 if (parent != NULL) {
4251 va_list args;
4252 va_start(args, fmt);
4253
4254 parent->setErrorStateV(fmt, args);
4255
4256 va_end(args);
4257 }
4258}
4259
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004260status_t Camera3Device::RequestThread::insertTriggers(
4261 const sp<CaptureRequest> &request) {
4262
4263 Mutex::Autolock al(mTriggerMutex);
4264
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004265 sp<Camera3Device> parent = mParent.promote();
4266 if (parent == NULL) {
4267 CLOGE("RequestThread: Parent is gone");
4268 return DEAD_OBJECT;
4269 }
4270
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004271 CameraMetadata &metadata = request->mSettings;
4272 size_t count = mTriggerMap.size();
4273
4274 for (size_t i = 0; i < count; ++i) {
4275 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004276 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004277
4278 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4279 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4280 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004281 if (isAeTrigger) {
4282 request->mResultExtras.precaptureTriggerId = triggerId;
4283 mCurrentPreCaptureTriggerId = triggerId;
4284 } else {
4285 request->mResultExtras.afTriggerId = triggerId;
4286 mCurrentAfTriggerId = triggerId;
4287 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004288 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4289 continue; // Trigger ID tag is deprecated since device HAL 3.2
4290 }
4291 }
4292
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004293 camera_metadata_entry entry = metadata.find(tag);
4294
4295 if (entry.count > 0) {
4296 /**
4297 * Already has an entry for this trigger in the request.
4298 * Rewrite it with our requested trigger value.
4299 */
4300 RequestTrigger oldTrigger = trigger;
4301
4302 oldTrigger.entryValue = entry.data.u8[0];
4303
4304 mTriggerReplacedMap.add(tag, oldTrigger);
4305 } else {
4306 /**
4307 * More typical, no trigger entry, so we just add it
4308 */
4309 mTriggerRemovedMap.add(tag, trigger);
4310 }
4311
4312 status_t res;
4313
4314 switch (trigger.getTagType()) {
4315 case TYPE_BYTE: {
4316 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4317 res = metadata.update(tag,
4318 &entryValue,
4319 /*count*/1);
4320 break;
4321 }
4322 case TYPE_INT32:
4323 res = metadata.update(tag,
4324 &trigger.entryValue,
4325 /*count*/1);
4326 break;
4327 default:
4328 ALOGE("%s: Type not supported: 0x%x",
4329 __FUNCTION__,
4330 trigger.getTagType());
4331 return INVALID_OPERATION;
4332 }
4333
4334 if (res != OK) {
4335 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4336 ", value %d", __FUNCTION__, trigger.getTagName(),
4337 trigger.entryValue);
4338 return res;
4339 }
4340
4341 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4342 trigger.getTagName(),
4343 trigger.entryValue);
4344 }
4345
4346 mTriggerMap.clear();
4347
4348 return count;
4349}
4350
4351status_t Camera3Device::RequestThread::removeTriggers(
4352 const sp<CaptureRequest> &request) {
4353 Mutex::Autolock al(mTriggerMutex);
4354
4355 CameraMetadata &metadata = request->mSettings;
4356
4357 /**
4358 * Replace all old entries with their old values.
4359 */
4360 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4361 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4362
4363 status_t res;
4364
4365 uint32_t tag = trigger.metadataTag;
4366 switch (trigger.getTagType()) {
4367 case TYPE_BYTE: {
4368 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4369 res = metadata.update(tag,
4370 &entryValue,
4371 /*count*/1);
4372 break;
4373 }
4374 case TYPE_INT32:
4375 res = metadata.update(tag,
4376 &trigger.entryValue,
4377 /*count*/1);
4378 break;
4379 default:
4380 ALOGE("%s: Type not supported: 0x%x",
4381 __FUNCTION__,
4382 trigger.getTagType());
4383 return INVALID_OPERATION;
4384 }
4385
4386 if (res != OK) {
4387 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4388 ", trigger value %d", __FUNCTION__,
4389 trigger.getTagName(), trigger.entryValue);
4390 return res;
4391 }
4392 }
4393 mTriggerReplacedMap.clear();
4394
4395 /**
4396 * Remove all new entries.
4397 */
4398 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4399 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4400 status_t res = metadata.erase(trigger.metadataTag);
4401
4402 if (res != OK) {
4403 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4404 ", trigger value %d", __FUNCTION__,
4405 trigger.getTagName(), trigger.entryValue);
4406 return res;
4407 }
4408 }
4409 mTriggerRemovedMap.clear();
4410
4411 return OK;
4412}
4413
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004414status_t Camera3Device::RequestThread::addDummyTriggerIds(
4415 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004416 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004417 static const int32_t dummyTriggerId = 1;
4418 status_t res;
4419
4420 CameraMetadata &metadata = request->mSettings;
4421
4422 // If AF trigger is active, insert a dummy AF trigger ID if none already
4423 // exists
4424 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4425 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4426 if (afTrigger.count > 0 &&
4427 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4428 afId.count == 0) {
4429 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4430 if (res != OK) return res;
4431 }
4432
4433 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4434 // if none already exists
4435 camera_metadata_entry pcTrigger =
4436 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4437 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4438 if (pcTrigger.count > 0 &&
4439 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4440 pcId.count == 0) {
4441 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4442 &dummyTriggerId, 1);
4443 if (res != OK) return res;
4444 }
4445
4446 return OK;
4447}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004448
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004449/**
4450 * PreparerThread inner class methods
4451 */
4452
4453Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004454 Thread(/*canCallJava*/false), mListener(nullptr),
4455 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004456}
4457
4458Camera3Device::PreparerThread::~PreparerThread() {
4459 Thread::requestExitAndWait();
4460 if (mCurrentStream != nullptr) {
4461 mCurrentStream->cancelPrepare();
4462 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4463 mCurrentStream.clear();
4464 }
4465 clear();
4466}
4467
Ruben Brunkc78ac262015-08-13 17:58:46 -07004468status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004469 status_t res;
4470
4471 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004472 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004473
Ruben Brunkc78ac262015-08-13 17:58:46 -07004474 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004475 if (res == OK) {
4476 // No preparation needed, fire listener right off
4477 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004478 if (listener != NULL) {
4479 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004480 }
4481 return OK;
4482 } else if (res != NOT_ENOUGH_DATA) {
4483 return res;
4484 }
4485
4486 // Need to prepare, start up thread if necessary
4487 if (!mActive) {
4488 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4489 // isn't running
4490 Thread::requestExitAndWait();
4491 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4492 if (res != OK) {
4493 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004494 if (listener != NULL) {
4495 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004496 }
4497 return res;
4498 }
4499 mCancelNow = false;
4500 mActive = true;
4501 ALOGV("%s: Preparer stream started", __FUNCTION__);
4502 }
4503
4504 // queue up the work
4505 mPendingStreams.push_back(stream);
4506 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4507
4508 return OK;
4509}
4510
4511status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004512 Mutex::Autolock l(mLock);
4513
4514 for (const auto& stream : mPendingStreams) {
4515 stream->cancelPrepare();
4516 }
4517 mPendingStreams.clear();
4518 mCancelNow = true;
4519
4520 return OK;
4521}
4522
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004523void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004524 Mutex::Autolock l(mLock);
4525 mListener = listener;
4526}
4527
4528bool Camera3Device::PreparerThread::threadLoop() {
4529 status_t res;
4530 {
4531 Mutex::Autolock l(mLock);
4532 if (mCurrentStream == nullptr) {
4533 // End thread if done with work
4534 if (mPendingStreams.empty()) {
4535 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4536 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4537 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4538 mActive = false;
4539 return false;
4540 }
4541
4542 // Get next stream to prepare
4543 auto it = mPendingStreams.begin();
4544 mCurrentStream = *it;
4545 mPendingStreams.erase(it);
4546 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4547 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4548 } else if (mCancelNow) {
4549 mCurrentStream->cancelPrepare();
4550 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4551 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4552 mCurrentStream.clear();
4553 mCancelNow = false;
4554 return true;
4555 }
4556 }
4557
4558 res = mCurrentStream->prepareNextBuffer();
4559 if (res == NOT_ENOUGH_DATA) return true;
4560 if (res != OK) {
4561 // Something bad happened; try to recover by cancelling prepare and
4562 // signalling listener anyway
4563 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4564 mCurrentStream->getId(), res, strerror(-res));
4565 mCurrentStream->cancelPrepare();
4566 }
4567
4568 // This stream has finished, notify listener
4569 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004570 sp<NotificationListener> listener = mListener.promote();
4571 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004572 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4573 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004574 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004575 }
4576
4577 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4578 mCurrentStream.clear();
4579
4580 return true;
4581}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004582
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004583/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004584 * Static callback forwarding methods from HAL to instance
4585 */
4586
4587void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4588 const camera3_capture_result *result) {
4589 Camera3Device *d =
4590 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004591
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004592 d->processCaptureResult(result);
4593}
4594
4595void Camera3Device::sNotify(const camera3_callback_ops *cb,
4596 const camera3_notify_msg *msg) {
4597 Camera3Device *d =
4598 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4599 d->notify(msg);
4600}
4601
4602}; // namespace android