blob: f20556d61ae21dcc555d043b5a8dfcd420630d19 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville 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 Talvalad00111e2017-01-31 11:59:12 -0800752 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 Wang0129d522016-10-30 22:43:41 -0700795 const List<const CameraMetadata> &metadataList,
796 const std::list<const SurfaceMap> &surfaceMaps,
797 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700798 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 if (requestList == NULL) {
800 CLOGE("requestList cannot be NULL.");
801 return BAD_VALUE;
802 }
803
Jianing Weicb0652e2014-03-12 18:29:36 -0700804 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700805 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
806 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
807 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
808 ++metadataIt, ++surfaceMapIt) {
809 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 if (newRequest == 0) {
811 CLOGE("Can't create capture request");
812 return BAD_VALUE;
813 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700814
Shuzhen Wang9d066012016-09-30 11:30:20 -0700815 newRequest->mRepeating = repeating;
816
Jianing Weicb0652e2014-03-12 18:29:36 -0700817 // Setup burst Id and request Id
818 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700819 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
820 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700821 CLOGE("RequestID entry exists; but must not be empty in metadata");
822 return BAD_VALUE;
823 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700824 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700825 } else {
826 CLOGE("RequestID does not exist in metadata");
827 return BAD_VALUE;
828 }
829
Jianing Wei90e59c92014-03-12 18:29:36 -0700830 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700831
832 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700833 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
835 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
836 return BAD_VALUE;
837 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700838
839 // Setup batch size if this is a high speed video recording request.
840 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
841 auto firstRequest = requestList->begin();
842 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
843 if (outputStream->isVideoStream()) {
844 (*firstRequest)->mBatchSize = requestList->size();
845 break;
846 }
847 }
848 }
849
Jianing Wei90e59c92014-03-12 18:29:36 -0700850 return OK;
851}
852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700856 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700857 std::list<const SurfaceMap> surfaceMaps;
858 convertToRequestList(requests, surfaceMaps, request);
859
860 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
861}
862
863void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
864 std::list<const SurfaceMap>& surfaceMaps,
865 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700866 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700867
868 SurfaceMap surfaceMap;
869 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
870 // With no surface list passed in, stream and surface will have 1-to-1
871 // mapping. So the surface index is 0 for each stream in the surfaceMap.
872 for (size_t i = 0; i < streams.count; i++) {
873 surfaceMap[streams.data.i32[i]].push_back(0);
874 }
875 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800876}
877
Jianing Wei90e59c92014-03-12 18:29:36 -0700878status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 const List<const CameraMetadata> &requests,
880 const std::list<const SurfaceMap> &surfaceMaps,
881 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700882 /*out*/
883 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 ATRACE_CALL();
885 Mutex::Autolock il(mInterfaceLock);
886 Mutex::Autolock l(mLock);
887
888 status_t res = checkStatusOkToCaptureLocked();
889 if (res != OK) {
890 // error logged by previous call
891 return res;
892 }
893
894 RequestList requestList;
895
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
897 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 if (res != OK) {
899 // error logged by previous call
900 return res;
901 }
902
903 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700904 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700905 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700906 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700907 }
908
909 if (res == OK) {
910 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
911 if (res != OK) {
912 SET_ERR_L("Can't transition to active in %f seconds!",
913 kActiveTimeout/1e9);
914 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800915 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700916 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700917 } else {
918 CLOGE("Cannot queue request. Impossible.");
919 return BAD_VALUE;
920 }
921
922 return res;
923}
924
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800925hardware::Return<void> Camera3Device::processCaptureResult(
926 const device::V3_2::CaptureResult& result) {
927 camera3_capture_result r;
928 status_t res;
929 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800930 if (result.result.size() != 0) {
931 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
932 size_t expected_metadata_size = result.result.size();
933 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
934 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
935 __FUNCTION__, result.frameNumber, strerror(-res), res);
936 return hardware::Void();
937 }
938 } else {
939 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 }
941
942 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
943 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
944 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
945 auto& bDst = outputBuffers[i];
946 const StreamBuffer &bSrc = result.outputBuffers[i];
947
948 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
949 if (idx == -1) {
950 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
951 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
952 return hardware::Void();
953 }
954 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
955
956 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800957 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800958 if (res != OK) {
959 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
960 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
961 return hardware::Void();
962 }
963 bDst.buffer = buffer;
964 bDst.status = mapHidlBufferStatus(bSrc.status);
965 bDst.acquire_fence = -1;
966 if (bSrc.releaseFence == nullptr) {
967 bDst.release_fence = -1;
968 } else if (bSrc.releaseFence->numFds == 1) {
969 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
970 } else {
971 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
972 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
973 return hardware::Void();
974 }
975 }
976 r.num_output_buffers = outputBuffers.size();
977 r.output_buffers = outputBuffers.data();
978
979 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800980 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 r.input_buffer = nullptr;
982 } else {
983 if (mInputStream->getId() != result.inputBuffer.streamId) {
984 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
985 result.frameNumber, result.inputBuffer.streamId);
986 return hardware::Void();
987 }
988 inputBuffer.stream = mInputStream->asHalStream();
989 buffer_handle_t *buffer;
990 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
991 &buffer);
992 if (res != OK) {
993 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
994 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
995 return hardware::Void();
996 }
997 inputBuffer.buffer = buffer;
998 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
999 inputBuffer.acquire_fence = -1;
1000 if (result.inputBuffer.releaseFence == nullptr) {
1001 inputBuffer.release_fence = -1;
1002 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1003 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1004 } else {
1005 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1006 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
1007 return hardware::Void();
1008 }
1009 r.input_buffer = &inputBuffer;
1010 }
1011
1012 r.partial_result = result.partialResult;
1013
1014 processCaptureResult(&r);
1015
1016 return hardware::Void();
1017}
1018
1019hardware::Return<void> Camera3Device::notify(
1020 const NotifyMsg& msg) {
1021 camera3_notify_msg m;
1022 switch (msg.type) {
1023 case MsgType::ERROR:
1024 m.type = CAMERA3_MSG_ERROR;
1025 m.message.error.frame_number = msg.msg.error.frameNumber;
1026 if (msg.msg.error.errorStreamId >= 0) {
1027 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
1028 if (idx == -1) {
1029 ALOGE("%s: Frame %d: Invalid error stream id %d",
1030 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1031 return hardware::Void();
1032 }
1033 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1034 } else {
1035 m.message.error.error_stream = nullptr;
1036 }
1037 switch (msg.msg.error.errorCode) {
1038 case ErrorCode::ERROR_DEVICE:
1039 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1040 break;
1041 case ErrorCode::ERROR_REQUEST:
1042 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1043 break;
1044 case ErrorCode::ERROR_RESULT:
1045 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1046 break;
1047 case ErrorCode::ERROR_BUFFER:
1048 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1049 break;
1050 }
1051 break;
1052 case MsgType::SHUTTER:
1053 m.type = CAMERA3_MSG_SHUTTER;
1054 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1055 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1056 break;
1057 }
1058 notify(&m);
1059
1060 return hardware::Void();
1061}
1062
Jianing Weicb0652e2014-03-12 18:29:36 -07001063status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001064 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001065 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001066 ATRACE_CALL();
1067
Shuzhen Wang0129d522016-10-30 22:43:41 -07001068 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001069}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001070
Jianing Weicb0652e2014-03-12 18:29:36 -07001071status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1072 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001073 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001074
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001075 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001076 std::list<const SurfaceMap> surfaceMaps;
1077 convertToRequestList(requests, surfaceMaps, request);
1078
1079 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1080 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001081}
1082
Jianing Weicb0652e2014-03-12 18:29:36 -07001083status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001084 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001085 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001086 ATRACE_CALL();
1087
Shuzhen Wang0129d522016-10-30 22:43:41 -07001088 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001089}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090
1091sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001092 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 status_t res;
1094
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001095 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001097 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001098 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001099 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001101 } else if (mStatus == STATUS_UNCONFIGURED) {
1102 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001103 CLOGE("No streams configured");
1104 return NULL;
1105 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001106 }
1107
Shuzhen Wang0129d522016-10-30 22:43:41 -07001108 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001109 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001110}
1111
Jianing Weicb0652e2014-03-12 18:29:36 -07001112status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001113 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001114 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001116
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 switch (mStatus) {
1118 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001119 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001120 return INVALID_OPERATION;
1121 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001122 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001123 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001124 case STATUS_UNCONFIGURED:
1125 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 case STATUS_ACTIVE:
1127 // OK
1128 break;
1129 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001130 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001131 return INVALID_OPERATION;
1132 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001133 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001134
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001135 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001136}
1137
1138status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1139 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001140 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001141
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001142 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001143}
1144
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001145status_t Camera3Device::createInputStream(
1146 uint32_t width, uint32_t height, int format, int *id) {
1147 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001148 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001149 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001150 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1151 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001152
1153 status_t res;
1154 bool wasActive = false;
1155
1156 switch (mStatus) {
1157 case STATUS_ERROR:
1158 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1159 return INVALID_OPERATION;
1160 case STATUS_UNINITIALIZED:
1161 ALOGE("%s: Device not initialized", __FUNCTION__);
1162 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 case STATUS_UNCONFIGURED:
1164 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001165 // OK
1166 break;
1167 case STATUS_ACTIVE:
1168 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001169 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001170 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001171 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001172 return res;
1173 }
1174 wasActive = true;
1175 break;
1176 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001177 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001178 return INVALID_OPERATION;
1179 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001180 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001181
1182 if (mInputStream != 0) {
1183 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1184 return INVALID_OPERATION;
1185 }
1186
1187 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1188 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001190
1191 mInputStream = newStream;
1192
1193 *id = mNextStreamId++;
1194
1195 // Continue captures if active at start
1196 if (wasActive) {
1197 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1198 res = configureStreamsLocked();
1199 if (res != OK) {
1200 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1201 __FUNCTION__, mNextStreamId, strerror(-res), res);
1202 return res;
1203 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001205 }
1206
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001207 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001208 return OK;
1209}
1210
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001211status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 uint32_t width, uint32_t height, int format,
1213 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001214 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001215 ATRACE_CALL();
1216
1217 if (consumer == nullptr) {
1218 ALOGE("%s: consumer must not be null", __FUNCTION__);
1219 return BAD_VALUE;
1220 }
1221
1222 std::vector<sp<Surface>> consumers;
1223 consumers.push_back(consumer);
1224
1225 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001226 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001227}
1228
1229status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1230 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1231 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001232 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001236 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001237 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1238 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001239
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 status_t res;
1241 bool wasActive = false;
1242
1243 switch (mStatus) {
1244 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001245 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 return INVALID_OPERATION;
1247 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001248 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 case STATUS_UNCONFIGURED:
1251 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 // OK
1253 break;
1254 case STATUS_ACTIVE:
1255 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001256 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return res;
1260 }
1261 wasActive = true;
1262 break;
1263 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001264 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return INVALID_OPERATION;
1266 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268
1269 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001270 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001271 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001272 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001273 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1274 }
Zhijun He5d677d12016-05-29 16:52:39 -07001275
Shuzhen Wang0129d522016-10-30 22:43:41 -07001276 if (consumers.size() == 0 && !hasDeferredConsumer) {
1277 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1278 return BAD_VALUE;
1279 }
Zhijun He5d677d12016-05-29 16:52:39 -07001280 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1281 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001282 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001283 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1284 return BAD_VALUE;
1285 }
1286
Shuzhen Wang0129d522016-10-30 22:43:41 -07001287 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001288 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1289 return BAD_VALUE;
1290 }
1291
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001292 // Use legacy dataspace values for older HALs
1293 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1294 dataSpace = mapToLegacyDataspace(dataSpace);
1295 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001297 ssize_t blobBufferSize;
1298 if (dataSpace != HAL_DATASPACE_DEPTH) {
1299 blobBufferSize = getJpegBufferSize(width, height);
1300 if (blobBufferSize <= 0) {
1301 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1302 return BAD_VALUE;
1303 }
1304 } else {
1305 blobBufferSize = getPointCloudBufferSize();
1306 if (blobBufferSize <= 0) {
1307 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1308 return BAD_VALUE;
1309 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001310 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001311 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001312 width, height, blobBufferSize, format, dataSpace, rotation,
1313 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001314 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1315 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1316 if (rawOpaqueBufferSize <= 0) {
1317 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1318 return BAD_VALUE;
1319 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001320 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001321 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1322 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001323 } else if (isShared) {
1324 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1325 width, height, format, consumerUsage, dataSpace, rotation,
1326 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001327 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001328 newStream = new Camera3OutputStream(mNextStreamId,
1329 width, height, format, consumerUsage, dataSpace, rotation,
1330 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001332 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001333 width, height, format, dataSpace, rotation,
1334 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001336 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337
Zhijun He125684a2015-12-26 15:07:30 -08001338 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001339 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1340 * requires buffers to be statically allocated for internal static buffer registration, while
1341 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1342 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001343 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001344 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001345 newStream->setBufferManager(mBufferManager);
1346 }
1347
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 res = mOutputStreams.add(mNextStreamId, newStream);
1349 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001350 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 return res;
1352 }
1353
1354 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001355 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356
1357 // Continue captures if active at start
1358 if (wasActive) {
1359 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1360 res = configureStreamsLocked();
1361 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001362 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1363 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return res;
1365 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001366 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001370}
1371
1372status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1373 ATRACE_CALL();
1374 (void)outputId; (void)id;
1375
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001376 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377 return INVALID_OPERATION;
1378}
1379
1380
1381status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001382 uint32_t *width, uint32_t *height,
1383 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001384 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001385 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001387
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001388 switch (mStatus) {
1389 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001390 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 return INVALID_OPERATION;
1392 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001393 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001395 case STATUS_UNCONFIGURED:
1396 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 case STATUS_ACTIVE:
1398 // OK
1399 break;
1400 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001401 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return INVALID_OPERATION;
1403 }
1404
1405 ssize_t idx = mOutputStreams.indexOfKey(id);
1406 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001407 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 return idx;
1409 }
1410
1411 if (width) *width = mOutputStreams[idx]->getWidth();
1412 if (height) *height = mOutputStreams[idx]->getHeight();
1413 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001414 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001416}
1417
1418status_t Camera3Device::setStreamTransform(int id,
1419 int transform) {
1420 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001422 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 switch (mStatus) {
1425 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001426 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001427 return INVALID_OPERATION;
1428 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001429 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001431 case STATUS_UNCONFIGURED:
1432 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 case STATUS_ACTIVE:
1434 // OK
1435 break;
1436 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001437 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 return INVALID_OPERATION;
1439 }
1440
1441 ssize_t idx = mOutputStreams.indexOfKey(id);
1442 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 CLOGE("Stream %d does not exist",
1444 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445 return BAD_VALUE;
1446 }
1447
1448 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001449}
1450
1451status_t Camera3Device::deleteStream(int id) {
1452 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001453 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 Mutex::Autolock l(mLock);
1455 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001456
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001457 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 // CameraDevice semantics require device to already be idle before
1460 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001462 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001463 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 }
1465
Igor Murashkin2fba5842013-04-22 14:03:54 -07001466 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001467 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 if (mInputStream != NULL && id == mInputStream->getId()) {
1469 deletedStream = mInputStream;
1470 mInputStream.clear();
1471 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001472 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001473 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return BAD_VALUE;
1475 }
Zhijun He5f446352014-01-22 09:49:33 -08001476 }
1477
1478 // Delete output stream or the output part of a bi-directional stream.
1479 if (outputStreamIdx != NAME_NOT_FOUND) {
1480 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 mOutputStreams.removeItem(id);
1482 }
1483
1484 // Free up the stream endpoint so that it can be used by some other stream
1485 res = deletedStream->disconnect();
1486 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 // fall through since we want to still list the stream as deleted.
1489 }
1490 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001491 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492
1493 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494}
1495
1496status_t Camera3Device::deleteReprocessStream(int id) {
1497 ATRACE_CALL();
1498 (void)id;
1499
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001501 return INVALID_OPERATION;
1502}
1503
Zhijun He1fa89992015-06-01 15:44:31 -07001504status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001505 ATRACE_CALL();
1506 ALOGV("%s: E", __FUNCTION__);
1507
1508 Mutex::Autolock il(mInterfaceLock);
1509 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001510
1511 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) {
1512 mNeedConfig = true;
1513 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
1514 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001515
1516 return configureStreamsLocked();
1517}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001518
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001519status_t Camera3Device::getInputBufferProducer(
1520 sp<IGraphicBufferProducer> *producer) {
1521 Mutex::Autolock il(mInterfaceLock);
1522 Mutex::Autolock l(mLock);
1523
1524 if (producer == NULL) {
1525 return BAD_VALUE;
1526 } else if (mInputStream == NULL) {
1527 return INVALID_OPERATION;
1528 }
1529
1530 return mInputStream->getInputBufferProducer(producer);
1531}
1532
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533status_t Camera3Device::createDefaultRequest(int templateId,
1534 CameraMetadata *request) {
1535 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001536 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001537
1538 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1539 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1540 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1541 return BAD_VALUE;
1542 }
1543
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 Mutex::Autolock l(mLock);
1546
1547 switch (mStatus) {
1548 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001552 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001554 case STATUS_UNCONFIGURED:
1555 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 case STATUS_ACTIVE:
1557 // OK
1558 break;
1559 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
1562 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001563
Zhijun Hea1530f12014-09-14 12:44:20 -07001564 if (!mRequestTemplateCache[templateId].isEmpty()) {
1565 *request = mRequestTemplateCache[templateId];
1566 return OK;
1567 }
1568
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001569 camera_metadata_t *rawRequest;
1570 status_t res = mInterface->constructDefaultRequestSettings(
1571 (camera3_request_template_t) templateId, &rawRequest);
1572 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001573 ALOGI("%s: template %d is not supported on this camera device",
1574 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001575 return res;
1576 } else if (res != OK) {
1577 CLOGE("Unable to construct request template %d: %s (%d)",
1578 templateId, strerror(-res), res);
1579 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001580 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001582 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001583
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001584 // Derive some new keys for backward compatibility
1585 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1586 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1587 int32_t defaultBoost[1] = {100};
1588 mRequestTemplateCache[templateId].update(
1589 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1590 defaultBoost, 1);
1591 }
1592
1593 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594 return OK;
1595}
1596
1597status_t Camera3Device::waitUntilDrained() {
1598 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001599 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001601
Zhijun He69a37482014-03-23 18:44:49 -07001602 return waitUntilDrainedLocked();
1603}
1604
1605status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 switch (mStatus) {
1607 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 ALOGV("%s: Already idle", __FUNCTION__);
1610 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001611 case STATUS_CONFIGURED:
1612 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001613 case STATUS_ERROR:
1614 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001615 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 break;
1617 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001618 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001619 return INVALID_OPERATION;
1620 }
1621
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001622 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001623 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001624 if (res != OK) {
1625 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1626 res);
1627 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 return res;
1629}
1630
Ruben Brunk183f0562015-08-12 12:55:02 -07001631
1632void Camera3Device::internalUpdateStatusLocked(Status status) {
1633 mStatus = status;
1634 mRecentStatusUpdates.add(mStatus);
1635 mStatusChanged.broadcast();
1636}
1637
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638// Pause to reconfigure
1639status_t Camera3Device::internalPauseAndWaitLocked() {
1640 mRequestThread->setPaused(true);
1641 mPauseStateNotify = true;
1642
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001643 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1645 if (res != OK) {
1646 SET_ERR_L("Can't idle device in %f seconds!",
1647 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001648 }
1649
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 return res;
1651}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001652
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001653// Resume after internalPauseAndWaitLocked
1654status_t Camera3Device::internalResumeLocked() {
1655 status_t res;
1656
1657 mRequestThread->setPaused(false);
1658
1659 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1660 if (res != OK) {
1661 SET_ERR_L("Can't transition to active in %f seconds!",
1662 kActiveTimeout/1e9);
1663 }
1664 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001665 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001666}
1667
Ruben Brunk183f0562015-08-12 12:55:02 -07001668status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001669 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001670
1671 size_t startIndex = 0;
1672 if (mStatusWaiters == 0) {
1673 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1674 // this status list
1675 mRecentStatusUpdates.clear();
1676 } else {
1677 // If other threads are waiting on updates to this status list, set the position of the
1678 // first element that this list will check rather than clearing the list.
1679 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001680 }
1681
Ruben Brunk183f0562015-08-12 12:55:02 -07001682 mStatusWaiters++;
1683
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 bool stateSeen = false;
1685 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001686 if (active == (mStatus == STATUS_ACTIVE)) {
1687 // Desired state is current
1688 break;
1689 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001690
1691 res = mStatusChanged.waitRelative(mLock, timeout);
1692 if (res != OK) break;
1693
Ruben Brunk183f0562015-08-12 12:55:02 -07001694 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1695 // transitions.
1696 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1697 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1698 __FUNCTION__);
1699
1700 // Encountered desired state since we began waiting
1701 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001702 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1703 stateSeen = true;
1704 break;
1705 }
1706 }
1707 } while (!stateSeen);
1708
Ruben Brunk183f0562015-08-12 12:55:02 -07001709 mStatusWaiters--;
1710
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001711 return res;
1712}
1713
1714
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001715status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001717 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001719 if (listener != NULL && mListener != NULL) {
1720 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1721 }
1722 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001723 mRequestThread->setNotificationListener(listener);
1724 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001725
1726 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727}
1728
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001729bool Camera3Device::willNotify3A() {
1730 return false;
1731}
1732
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001734 status_t res;
1735 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001736
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001737 while (mResultQueue.empty()) {
1738 res = mResultSignal.waitRelative(mOutputLock, timeout);
1739 if (res == TIMED_OUT) {
1740 return res;
1741 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001742 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1743 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001744 return res;
1745 }
1746 }
1747 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748}
1749
Jianing Weicb0652e2014-03-12 18:29:36 -07001750status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001752 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001754 if (mResultQueue.empty()) {
1755 return NOT_ENOUGH_DATA;
1756 }
1757
Jianing Weicb0652e2014-03-12 18:29:36 -07001758 if (frame == NULL) {
1759 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1760 return BAD_VALUE;
1761 }
1762
1763 CaptureResult &result = *(mResultQueue.begin());
1764 frame->mResultExtras = result.mResultExtras;
1765 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001766 mResultQueue.erase(mResultQueue.begin());
1767
1768 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769}
1770
1771status_t Camera3Device::triggerAutofocus(uint32_t id) {
1772 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001774
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001775 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1776 // Mix-in this trigger into the next request and only the next request.
1777 RequestTrigger trigger[] = {
1778 {
1779 ANDROID_CONTROL_AF_TRIGGER,
1780 ANDROID_CONTROL_AF_TRIGGER_START
1781 },
1782 {
1783 ANDROID_CONTROL_AF_TRIGGER_ID,
1784 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001785 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001786 };
1787
1788 return mRequestThread->queueTrigger(trigger,
1789 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790}
1791
1792status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1793 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001794 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001795
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001796 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1797 // Mix-in this trigger into the next request and only the next request.
1798 RequestTrigger trigger[] = {
1799 {
1800 ANDROID_CONTROL_AF_TRIGGER,
1801 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1802 },
1803 {
1804 ANDROID_CONTROL_AF_TRIGGER_ID,
1805 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001806 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001807 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001808
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001809 return mRequestThread->queueTrigger(trigger,
1810 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811}
1812
1813status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1814 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001816
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001817 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1818 // Mix-in this trigger into the next request and only the next request.
1819 RequestTrigger trigger[] = {
1820 {
1821 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1822 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1823 },
1824 {
1825 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1826 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001827 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001828 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001830 return mRequestThread->queueTrigger(trigger,
1831 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001832}
1833
1834status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1835 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1836 ATRACE_CALL();
1837 (void)reprocessStreamId; (void)buffer; (void)listener;
1838
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001839 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001840 return INVALID_OPERATION;
1841}
1842
Jianing Weicb0652e2014-03-12 18:29:36 -07001843status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001844 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001845 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001847
Zhijun He7ef20392014-04-21 16:04:17 -07001848 {
1849 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001850 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001851 }
1852
Zhijun He491e3412013-12-27 10:57:44 -08001853 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001854 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001855 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001856 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001857 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001858 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001859 }
1860
1861 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001862}
1863
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001864status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001865 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1866}
1867
1868status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001869 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001870 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001871 Mutex::Autolock il(mInterfaceLock);
1872 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001873
1874 sp<Camera3StreamInterface> stream;
1875 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1876 if (outputStreamIdx == NAME_NOT_FOUND) {
1877 CLOGE("Stream %d does not exist", streamId);
1878 return BAD_VALUE;
1879 }
1880
1881 stream = mOutputStreams.editValueAt(outputStreamIdx);
1882
1883 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001884 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001885 return BAD_VALUE;
1886 }
1887
1888 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001889 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890 return BAD_VALUE;
1891 }
1892
Ruben Brunkc78ac262015-08-13 17:58:46 -07001893 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001894}
1895
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001896status_t Camera3Device::tearDown(int streamId) {
1897 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001898 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001899 Mutex::Autolock il(mInterfaceLock);
1900 Mutex::Autolock l(mLock);
1901
1902 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1903 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001904 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001905 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001906 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001907 return NO_INIT;
1908 }
1909
1910 sp<Camera3StreamInterface> stream;
1911 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1912 if (outputStreamIdx == NAME_NOT_FOUND) {
1913 CLOGE("Stream %d does not exist", streamId);
1914 return BAD_VALUE;
1915 }
1916
1917 stream = mOutputStreams.editValueAt(outputStreamIdx);
1918
1919 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1920 CLOGE("Stream %d is a target of a in-progress request", streamId);
1921 return BAD_VALUE;
1922 }
1923
1924 return stream->tearDown();
1925}
1926
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001927status_t Camera3Device::addBufferListenerForStream(int streamId,
1928 wp<Camera3StreamBufferListener> listener) {
1929 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001930 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001931 Mutex::Autolock il(mInterfaceLock);
1932 Mutex::Autolock l(mLock);
1933
1934 sp<Camera3StreamInterface> stream;
1935 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1936 if (outputStreamIdx == NAME_NOT_FOUND) {
1937 CLOGE("Stream %d does not exist", streamId);
1938 return BAD_VALUE;
1939 }
1940
1941 stream = mOutputStreams.editValueAt(outputStreamIdx);
1942 stream->addBufferListener(listener);
1943
1944 return OK;
1945}
1946
Zhijun He204e3292014-07-14 17:09:23 -07001947uint32_t Camera3Device::getDeviceVersion() {
1948 ATRACE_CALL();
1949 Mutex::Autolock il(mInterfaceLock);
1950 return mDeviceVersion;
1951}
1952
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001953/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001954 * Methods called by subclasses
1955 */
1956
1957void Camera3Device::notifyStatus(bool idle) {
1958 {
1959 // Need mLock to safely update state and synchronize to current
1960 // state of methods in flight.
1961 Mutex::Autolock l(mLock);
1962 // We can get various system-idle notices from the status tracker
1963 // while starting up. Only care about them if we've actually sent
1964 // in some requests recently.
1965 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1966 return;
1967 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001968 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001969 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001970 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001971
1972 // Skip notifying listener if we're doing some user-transparent
1973 // state changes
1974 if (mPauseStateNotify) return;
1975 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001976
1977 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001978 {
1979 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001980 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001981 }
1982 if (idle && listener != NULL) {
1983 listener->notifyIdle();
1984 }
1985}
1986
Shuzhen Wang758c2152017-01-10 18:26:18 -08001987status_t Camera3Device::setConsumerSurfaces(int streamId,
1988 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001989 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001990 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1991 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001992 Mutex::Autolock il(mInterfaceLock);
1993 Mutex::Autolock l(mLock);
1994
Shuzhen Wang758c2152017-01-10 18:26:18 -08001995 if (consumers.size() == 0) {
1996 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001997 return BAD_VALUE;
1998 }
1999
2000 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2001 if (idx == NAME_NOT_FOUND) {
2002 CLOGE("Stream %d is unknown", streamId);
2003 return idx;
2004 }
2005 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002006 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002007 if (res != OK) {
2008 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2009 return res;
2010 }
2011
Shuzhen Wang0129d522016-10-30 22:43:41 -07002012 if (stream->isConsumerConfigurationDeferred()) {
2013 if (!stream->isConfiguring()) {
2014 CLOGE("Stream %d was already fully configured.", streamId);
2015 return INVALID_OPERATION;
2016 }
Zhijun He5d677d12016-05-29 16:52:39 -07002017
Shuzhen Wang0129d522016-10-30 22:43:41 -07002018 res = stream->finishConfiguration();
2019 if (res != OK) {
2020 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2021 stream->getId(), strerror(-res), res);
2022 return res;
2023 }
Zhijun He5d677d12016-05-29 16:52:39 -07002024 }
2025
2026 return OK;
2027}
2028
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002029/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002030 * Camera3Device private methods
2031 */
2032
2033sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002034 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035 ATRACE_CALL();
2036 status_t res;
2037
2038 sp<CaptureRequest> newRequest = new CaptureRequest;
2039 newRequest->mSettings = request;
2040
2041 camera_metadata_entry_t inputStreams =
2042 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2043 if (inputStreams.count > 0) {
2044 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002045 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002046 CLOGE("Request references unknown input stream %d",
2047 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 return NULL;
2049 }
2050 // Lazy completion of stream configuration (allocation/registration)
2051 // on first use
2052 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002053 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002054 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002055 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002057 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058 return NULL;
2059 }
2060 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002061 // Check if stream is being prepared
2062 if (mInputStream->isPreparing()) {
2063 CLOGE("Request references an input stream that's being prepared!");
2064 return NULL;
2065 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066
2067 newRequest->mInputStream = mInputStream;
2068 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2069 }
2070
2071 camera_metadata_entry_t streams =
2072 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2073 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002074 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 return NULL;
2076 }
2077
2078 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002079 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002081 CLOGE("Request references unknown stream %d",
2082 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 return NULL;
2084 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002085 sp<Camera3OutputStreamInterface> stream =
2086 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087
Zhijun He5d677d12016-05-29 16:52:39 -07002088 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002089 auto iter = surfaceMap.find(streams.data.i32[i]);
2090 if (iter != surfaceMap.end()) {
2091 const std::vector<size_t>& surfaces = iter->second;
2092 for (const auto& surface : surfaces) {
2093 if (stream->isConsumerConfigurationDeferred(surface)) {
2094 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2095 "due to deferred consumer", stream->getId(), surface);
2096 return NULL;
2097 }
2098 }
2099 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002100 }
2101
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 // Lazy completion of stream configuration (allocation/registration)
2103 // on first use
2104 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002105 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002106 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002107 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2108 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 return NULL;
2110 }
2111 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002112 // Check if stream is being prepared
2113 if (stream->isPreparing()) {
2114 CLOGE("Request references an output stream that's being prepared!");
2115 return NULL;
2116 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117
2118 newRequest->mOutputStreams.push(stream);
2119 }
2120 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002121 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122
2123 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002124}
2125
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002126bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2127 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2128 Size size = mSupportedOpaqueInputSizes[i];
2129 if (size.width == width && size.height == height) {
2130 return true;
2131 }
2132 }
2133
2134 return false;
2135}
2136
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002137void Camera3Device::cancelStreamsConfigurationLocked() {
2138 int res = OK;
2139 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2140 res = mInputStream->cancelConfiguration();
2141 if (res != OK) {
2142 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2143 mInputStream->getId(), strerror(-res), res);
2144 }
2145 }
2146
2147 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2148 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2149 if (outputStream->isConfiguring()) {
2150 res = outputStream->cancelConfiguration();
2151 if (res != OK) {
2152 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2153 outputStream->getId(), strerror(-res), res);
2154 }
2155 }
2156 }
2157
2158 // Return state to that at start of call, so that future configures
2159 // properly clean things up
2160 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2161 mNeedConfig = true;
2162}
2163
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164status_t Camera3Device::configureStreamsLocked() {
2165 ATRACE_CALL();
2166 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002167
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002168 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002169 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170 return INVALID_OPERATION;
2171 }
2172
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002173 if (!mNeedConfig) {
2174 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2175 return OK;
2176 }
2177
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002178 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2179 // adding a dummy stream instead.
2180 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2181 if (mOutputStreams.size() == 0) {
2182 addDummyStreamLocked();
2183 } else {
2184 tryRemoveDummyStreamLocked();
2185 }
2186
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002187 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002188 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002189
2190 camera3_stream_configuration config;
Zhijun He1fa89992015-06-01 15:44:31 -07002191 config.operation_mode = mIsConstrainedHighSpeedConfiguration ?
2192 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE :
2193 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2195
2196 Vector<camera3_stream_t*> streams;
2197 streams.setCapacity(config.num_streams);
2198
2199 if (mInputStream != NULL) {
2200 camera3_stream_t *inputStream;
2201 inputStream = mInputStream->startConfiguration();
2202 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002203 CLOGE("Can't start input stream configuration");
2204 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 return INVALID_OPERATION;
2206 }
2207 streams.add(inputStream);
2208 }
2209
2210 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002211
2212 // Don't configure bidi streams twice, nor add them twice to the list
2213 if (mOutputStreams[i].get() ==
2214 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2215
2216 config.num_streams--;
2217 continue;
2218 }
2219
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002220 camera3_stream_t *outputStream;
2221 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2222 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002223 CLOGE("Can't start output stream configuration");
2224 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225 return INVALID_OPERATION;
2226 }
2227 streams.add(outputStream);
2228 }
2229
2230 config.streams = streams.editArray();
2231
2232 // Do the HAL configuration; will potentially touch stream
2233 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002234
2235 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002236
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002237 if (res == BAD_VALUE) {
2238 // HAL rejected this set of streams as unsupported, clean up config
2239 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002240 CLOGE("Set of requested inputs/outputs not supported by HAL");
2241 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002242 return BAD_VALUE;
2243 } else if (res != OK) {
2244 // Some other kind of error from configure_streams - this is not
2245 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002246 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2247 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002248 return res;
2249 }
2250
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002251 // Finish all stream configuration immediately.
2252 // TODO: Try to relax this later back to lazy completion, which should be
2253 // faster
2254
Igor Murashkin073f8572013-05-02 14:59:28 -07002255 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002256 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002257 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002258 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002259 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002260 cancelStreamsConfigurationLocked();
2261 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002262 }
2263 }
2264
2265 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002266 sp<Camera3OutputStreamInterface> outputStream =
2267 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002268 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002269 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002270 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002271 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002272 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002273 cancelStreamsConfigurationLocked();
2274 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002275 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002276 }
2277 }
2278
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 // Request thread needs to know to avoid using repeat-last-settings protocol
2280 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002281 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002282
Zhijun He90f7c372016-08-16 16:19:43 -07002283 char value[PROPERTY_VALUE_MAX];
2284 property_get("camera.fifo.disable", value, "0");
2285 int32_t disableFifo = atoi(value);
2286 if (disableFifo != 1) {
2287 // Boost priority of request thread to SCHED_FIFO.
2288 pid_t requestThreadTid = mRequestThread->getTid();
2289 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002290 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002291 if (res != OK) {
2292 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2293 strerror(-res), res);
2294 } else {
2295 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2296 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002297 }
2298
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002299 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002301 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302
Ruben Brunk183f0562015-08-12 12:55:02 -07002303 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2304 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002305
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002306 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002307
Zhijun He0a210512014-07-24 13:45:15 -07002308 // tear down the deleted streams after configure streams.
2309 mDeletedStreams.clear();
2310
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002312}
2313
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002314status_t Camera3Device::addDummyStreamLocked() {
2315 ATRACE_CALL();
2316 status_t res;
2317
2318 if (mDummyStreamId != NO_STREAM) {
2319 // Should never be adding a second dummy stream when one is already
2320 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002321 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2322 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002323 return INVALID_OPERATION;
2324 }
2325
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002326 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002327
2328 sp<Camera3OutputStreamInterface> dummyStream =
2329 new Camera3DummyStream(mNextStreamId);
2330
2331 res = mOutputStreams.add(mNextStreamId, dummyStream);
2332 if (res < 0) {
2333 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2334 return res;
2335 }
2336
2337 mDummyStreamId = mNextStreamId;
2338 mNextStreamId++;
2339
2340 return OK;
2341}
2342
2343status_t Camera3Device::tryRemoveDummyStreamLocked() {
2344 ATRACE_CALL();
2345 status_t res;
2346
2347 if (mDummyStreamId == NO_STREAM) return OK;
2348 if (mOutputStreams.size() == 1) return OK;
2349
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002350 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002351
2352 // Ok, have a dummy stream and there's at least one other output stream,
2353 // so remove the dummy
2354
2355 sp<Camera3StreamInterface> deletedStream;
2356 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2357 if (outputStreamIdx == NAME_NOT_FOUND) {
2358 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2359 return INVALID_OPERATION;
2360 }
2361
2362 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2363 mOutputStreams.removeItemsAt(outputStreamIdx);
2364
2365 // Free up the stream endpoint so that it can be used by some other stream
2366 res = deletedStream->disconnect();
2367 if (res != OK) {
2368 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2369 // fall through since we want to still list the stream as deleted.
2370 }
2371 mDeletedStreams.add(deletedStream);
2372 mDummyStreamId = NO_STREAM;
2373
2374 return res;
2375}
2376
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002377void Camera3Device::setErrorState(const char *fmt, ...) {
2378 Mutex::Autolock l(mLock);
2379 va_list args;
2380 va_start(args, fmt);
2381
2382 setErrorStateLockedV(fmt, args);
2383
2384 va_end(args);
2385}
2386
2387void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2388 Mutex::Autolock l(mLock);
2389 setErrorStateLockedV(fmt, args);
2390}
2391
2392void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2393 va_list args;
2394 va_start(args, fmt);
2395
2396 setErrorStateLockedV(fmt, args);
2397
2398 va_end(args);
2399}
2400
2401void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002402 // Print out all error messages to log
2403 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002404 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002405
2406 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002407 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002408
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002409 mErrorCause = errorCause;
2410
2411 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002412 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002413
2414 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002415 sp<NotificationListener> listener = mListener.promote();
2416 if (listener != NULL) {
2417 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002418 CaptureResultExtras());
2419 }
2420
2421 // Save stack trace. View by dumping it later.
2422 CameraTraces::saveTrace();
2423 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002424}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425
2426/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002427 * In-flight request management
2428 */
2429
Jianing Weicb0652e2014-03-12 18:29:36 -07002430status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002431 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2432 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002433 ATRACE_CALL();
2434 Mutex::Autolock l(mInFlightLock);
2435
2436 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002437 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2438 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002439 if (res < 0) return res;
2440
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002441 if (mInFlightMap.size() == 1) {
2442 mStatusTracker->markComponentActive(mInFlightStatusId);
2443 }
2444
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002445 return OK;
2446}
2447
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002448void Camera3Device::returnOutputBuffers(
2449 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2450 nsecs_t timestamp) {
2451 for (size_t i = 0; i < numBuffers; i++)
2452 {
2453 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2454 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2455 // Note: stream may be deallocated at this point, if this buffer was
2456 // the last reference to it.
2457 if (res != OK) {
2458 ALOGE("Can't return buffer to its stream: %s (%d)",
2459 strerror(-res), res);
2460 }
2461 }
2462}
2463
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002464void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2465 mInFlightMap.removeItemsAt(idx, 1);
2466
2467 // Indicate idle inFlightMap to the status tracker
2468 if (mInFlightMap.size() == 0) {
2469 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2470 }
2471}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002472
2473void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2474
2475 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2476 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2477
2478 nsecs_t sensorTimestamp = request.sensorTimestamp;
2479 nsecs_t shutterTimestamp = request.shutterTimestamp;
2480
2481 // Check if it's okay to remove the request from InFlightMap:
2482 // In the case of a successful request:
2483 // all input and output buffers, all result metadata, shutter callback
2484 // arrived.
2485 // In the case of a unsuccessful request:
2486 // all input and output buffers arrived.
2487 if (request.numBuffersLeft == 0 &&
2488 (request.requestStatus != OK ||
2489 (request.haveResultMetadata && shutterTimestamp != 0))) {
2490 ATRACE_ASYNC_END("frame capture", frameNumber);
2491
2492 // Sanity check - if sensor timestamp matches shutter timestamp
2493 if (request.requestStatus == OK &&
2494 sensorTimestamp != shutterTimestamp) {
2495 SET_ERR("sensor timestamp (%" PRId64
2496 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2497 sensorTimestamp, frameNumber, shutterTimestamp);
2498 }
2499
2500 // for an unsuccessful request, it may have pending output buffers to
2501 // return.
2502 assert(request.requestStatus != OK ||
2503 request.pendingOutputBuffers.size() == 0);
2504 returnOutputBuffers(request.pendingOutputBuffers.array(),
2505 request.pendingOutputBuffers.size(), 0);
2506
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002507 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002508 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2509 }
2510
2511 // Sanity check - if we have too many in-flight frames, something has
2512 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002513 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002514 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002515 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2516 kInFlightWarnLimitHighSpeed) {
2517 CLOGE("In-flight list too large for high speed configuration: %zu",
2518 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002519 }
2520}
2521
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002522void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2523 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2524 if (result == nullptr) return;
2525
2526 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2527 (int32_t*)&frameNumber, 1) != OK) {
2528 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2529 return;
2530 }
2531
2532 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2533 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2534 return;
2535 }
2536
2537 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2538
2539 // Valid result, insert into queue
2540 List<CaptureResult>::iterator queuedResult =
2541 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2542 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2543 ", burstId = %" PRId32, __FUNCTION__,
2544 queuedResult->mResultExtras.requestId,
2545 queuedResult->mResultExtras.frameNumber,
2546 queuedResult->mResultExtras.burstId);
2547
2548 mResultSignal.signal();
2549}
2550
2551
2552void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2553 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2554 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2555 Mutex::Autolock l(mOutputLock);
2556
2557 CaptureResult captureResult;
2558 captureResult.mResultExtras = resultExtras;
2559 captureResult.mMetadata = partialResult;
2560
2561 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2562}
2563
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002564
2565void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2566 CaptureResultExtras &resultExtras,
2567 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002568 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002569 bool reprocess,
2570 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002571 if (pendingMetadata.isEmpty())
2572 return;
2573
2574 Mutex::Autolock l(mOutputLock);
2575
2576 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002577 if (reprocess) {
2578 if (frameNumber < mNextReprocessResultFrameNumber) {
2579 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002580 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002581 frameNumber, mNextReprocessResultFrameNumber);
2582 return;
2583 }
2584 mNextReprocessResultFrameNumber = frameNumber + 1;
2585 } else {
2586 if (frameNumber < mNextResultFrameNumber) {
2587 SET_ERR("Out-of-order capture result metadata submitted! "
2588 "(got frame number %d, expecting %d)",
2589 frameNumber, mNextResultFrameNumber);
2590 return;
2591 }
2592 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002593 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002594
2595 CaptureResult captureResult;
2596 captureResult.mResultExtras = resultExtras;
2597 captureResult.mMetadata = pendingMetadata;
2598
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002599 // Append any previous partials to form a complete result
2600 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2601 captureResult.mMetadata.append(collectedPartialResult);
2602 }
2603
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002604 // Derive some new keys for backward compaibility
2605 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2606 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2607 int32_t defaultBoost[1] = {100};
2608 captureResult.mMetadata.update(
2609 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2610 defaultBoost, 1);
2611 }
2612
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002613 captureResult.mMetadata.sort();
2614
2615 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002616 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2617 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002618 SET_ERR("No timestamp provided by HAL for frame %d!",
2619 frameNumber);
2620 return;
2621 }
2622
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002623 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2624 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2625
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002626 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002627}
2628
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002629/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002630 * Camera HAL device callback methods
2631 */
2632
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002633void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002634 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002635
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002636 status_t res;
2637
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002638 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002639 if (result->result == NULL && result->num_output_buffers == 0 &&
2640 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002641 SET_ERR("No result data provided by HAL for frame %d",
2642 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002643 return;
2644 }
Zhijun He204e3292014-07-14 17:09:23 -07002645
2646 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2647 // partial_result to 1 when metadata is included in this result.
2648 if (!mUsePartialResult &&
2649 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2650 result->result != NULL &&
2651 result->partial_result != 1) {
2652 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2653 " if partial result is not supported",
2654 frameNumber, result->partial_result);
2655 return;
2656 }
2657
2658 bool isPartialResult = false;
2659 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002660 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002661 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002662
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002663 // Get shutter timestamp and resultExtras from list of in-flight requests,
2664 // where it was added by the shutter notification for this frame. If the
2665 // shutter timestamp isn't received yet, append the output buffers to the
2666 // in-flight request and they will be returned when the shutter timestamp
2667 // arrives. Update the in-flight status and remove the in-flight entry if
2668 // all result data and shutter timestamp have been received.
2669 nsecs_t shutterTimestamp = 0;
2670
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002671 {
2672 Mutex::Autolock l(mInFlightLock);
2673 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2674 if (idx == NAME_NOT_FOUND) {
2675 SET_ERR("Unknown frame number for capture result: %d",
2676 frameNumber);
2677 return;
2678 }
2679 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002680 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2681 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2682 ", partialResultCount = %d",
2683 __FUNCTION__, request.resultExtras.requestId,
2684 request.resultExtras.frameNumber, request.resultExtras.burstId,
2685 result->partial_result);
2686 // Always update the partial count to the latest one if it's not 0
2687 // (buffers only). When framework aggregates adjacent partial results
2688 // into one, the latest partial count will be used.
2689 if (result->partial_result != 0)
2690 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002691
2692 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002693 if (mUsePartialResult && result->result != NULL) {
2694 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2695 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2696 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2697 " the range of [1, %d] when metadata is included in the result",
2698 frameNumber, result->partial_result, mNumPartialResults);
2699 return;
2700 }
2701 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002702 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002703 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002704 }
Zhijun He204e3292014-07-14 17:09:23 -07002705 } else {
2706 camera_metadata_ro_entry_t partialResultEntry;
2707 res = find_camera_metadata_ro_entry(result->result,
2708 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2709 if (res != NAME_NOT_FOUND &&
2710 partialResultEntry.count > 0 &&
2711 partialResultEntry.data.u8[0] ==
2712 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2713 // A partial result. Flag this as such, and collect this
2714 // set of metadata into the in-flight entry.
2715 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002716 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002717 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002718 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002719 ANDROID_QUIRKS_PARTIAL_RESULT);
2720 }
2721 }
2722
2723 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002724 // Send partial capture result
2725 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2726 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002727 }
2728 }
2729
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002730 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002731 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002732
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002733 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002734 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002735 if (request.haveResultMetadata) {
2736 SET_ERR("Called multiple times with metadata for frame %d",
2737 frameNumber);
2738 return;
2739 }
Zhijun He204e3292014-07-14 17:09:23 -07002740 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002741 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002742 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002743 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002744 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002745 request.haveResultMetadata = true;
2746 }
2747
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002748 uint32_t numBuffersReturned = result->num_output_buffers;
2749 if (result->input_buffer != NULL) {
2750 if (hasInputBufferInRequest) {
2751 numBuffersReturned += 1;
2752 } else {
2753 ALOGW("%s: Input buffer should be NULL if there is no input"
2754 " buffer sent in the request",
2755 __FUNCTION__);
2756 }
2757 }
2758 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002759 if (request.numBuffersLeft < 0) {
2760 SET_ERR("Too many buffers returned for frame %d",
2761 frameNumber);
2762 return;
2763 }
2764
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002765 camera_metadata_ro_entry_t entry;
2766 res = find_camera_metadata_ro_entry(result->result,
2767 ANDROID_SENSOR_TIMESTAMP, &entry);
2768 if (res == OK && entry.count == 1) {
2769 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002770 }
2771
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002772 // If shutter event isn't received yet, append the output buffers to
2773 // the in-flight request. Otherwise, return the output buffers to
2774 // streams.
2775 if (shutterTimestamp == 0) {
2776 request.pendingOutputBuffers.appendArray(result->output_buffers,
2777 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002778 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002779 returnOutputBuffers(result->output_buffers,
2780 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002781 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002782
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002783 if (result->result != NULL && !isPartialResult) {
2784 if (shutterTimestamp == 0) {
2785 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002786 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002787 } else {
2788 CameraMetadata metadata;
2789 metadata = result->result;
2790 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002791 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2792 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002793 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002794 }
2795
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002796 removeInFlightRequestIfReadyLocked(idx);
2797 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002798
Zhijun Hef0d962a2014-06-30 10:24:11 -07002799 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002800 if (hasInputBufferInRequest) {
2801 Camera3Stream *stream =
2802 Camera3Stream::cast(result->input_buffer->stream);
2803 res = stream->returnInputBuffer(*(result->input_buffer));
2804 // Note: stream may be deallocated at this point, if this buffer was the
2805 // last reference to it.
2806 if (res != OK) {
2807 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2808 " its stream:%s (%d)", __FUNCTION__,
2809 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002810 }
2811 } else {
2812 ALOGW("%s: Input buffer should be NULL if there is no input"
2813 " buffer sent in the request, skipping input buffer return.",
2814 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002815 }
2816 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002817}
2818
2819void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002820 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002821 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002822 {
2823 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002824 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002825 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002826
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002827 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002828 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002829 return;
2830 }
2831
2832 switch (msg->type) {
2833 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002834 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002835 break;
2836 }
2837 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002838 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002839 break;
2840 }
2841 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002842 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002843 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002844 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002845}
2846
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002847void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002848 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002849
2850 // Map camera HAL error codes to ICameraDeviceCallback error codes
2851 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002852 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002853 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002854 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002855 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002856 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002858 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002860 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002861 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002862 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002863 };
2864
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002865 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002866 ((msg.error_code >= 0) &&
2867 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2868 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002869 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002870
2871 int streamId = 0;
2872 if (msg.error_stream != NULL) {
2873 Camera3Stream *stream =
2874 Camera3Stream::cast(msg.error_stream);
2875 streamId = stream->getId();
2876 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002877 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2878 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002879 streamId, msg.error_code);
2880
2881 CaptureResultExtras resultExtras;
2882 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002883 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002884 // SET_ERR calls notifyError
2885 SET_ERR("Camera HAL reported serious device error");
2886 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002887 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2888 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2889 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890 {
2891 Mutex::Autolock l(mInFlightLock);
2892 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2893 if (idx >= 0) {
2894 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2895 r.requestStatus = msg.error_code;
2896 resultExtras = r.resultExtras;
2897 } else {
2898 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002899 ALOGE("Camera %s: %s: cannot find in-flight request on "
2900 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002901 resultExtras.frameNumber);
2902 }
2903 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002904 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002905 if (listener != NULL) {
2906 listener->notifyError(errorCode, resultExtras);
2907 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002908 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002909 }
2910 break;
2911 default:
2912 // SET_ERR calls notifyError
2913 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2914 break;
2915 }
2916}
2917
2918void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002919 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002920 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002921
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002922 // Set timestamp for the request in the in-flight tracking
2923 // and get the request ID to send upstream
2924 {
2925 Mutex::Autolock l(mInFlightLock);
2926 idx = mInFlightMap.indexOfKey(msg.frame_number);
2927 if (idx >= 0) {
2928 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002929
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002930 // Verify ordering of shutter notifications
2931 {
2932 Mutex::Autolock l(mOutputLock);
2933 // TODO: need to track errors for tighter bounds on expected frame number.
2934 if (r.hasInputBuffer) {
2935 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2936 SET_ERR("Shutter notification out-of-order. Expected "
2937 "notification for frame %d, got frame %d",
2938 mNextReprocessShutterFrameNumber, msg.frame_number);
2939 return;
2940 }
2941 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2942 } else {
2943 if (msg.frame_number < mNextShutterFrameNumber) {
2944 SET_ERR("Shutter notification out-of-order. Expected "
2945 "notification for frame %d, got frame %d",
2946 mNextShutterFrameNumber, msg.frame_number);
2947 return;
2948 }
2949 mNextShutterFrameNumber = msg.frame_number + 1;
2950 }
2951 }
2952
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
2954 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002955 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
2956 // Call listener, if any
2957 if (listener != NULL) {
2958 listener->notifyShutter(r.resultExtras, msg.timestamp);
2959 }
2960
2961 r.shutterTimestamp = msg.timestamp;
2962
2963 // send pending result and buffers
2964 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002965 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002966 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002967 returnOutputBuffers(r.pendingOutputBuffers.array(),
2968 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2969 r.pendingOutputBuffers.clear();
2970
2971 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972 }
2973 }
2974 if (idx < 0) {
2975 SET_ERR("Shutter notification for non-existent frame number %d",
2976 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002977 }
2978}
2979
2980
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002981CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002982 ALOGV("%s", __FUNCTION__);
2983
Igor Murashkin1e479c02013-09-06 16:55:14 -07002984 CameraMetadata retVal;
2985
2986 if (mRequestThread != NULL) {
2987 retVal = mRequestThread->getLatestRequest();
2988 }
2989
Igor Murashkin1e479c02013-09-06 16:55:14 -07002990 return retVal;
2991}
2992
Jianing Weicb0652e2014-03-12 18:29:36 -07002993
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002994void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2995 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2996 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2997}
2998
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002999/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003000 * HalInterface inner class methods
3001 */
3002
3003Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3004 mHal3Device(device) {}
3005
3006Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3007 mHal3Device(nullptr),
3008 mHidlSession(session) {}
3009
3010Camera3Device::HalInterface::HalInterface() :
3011 mHal3Device(nullptr) {}
3012
3013Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3014 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3015
3016bool Camera3Device::HalInterface::valid() {
3017 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3018}
3019
3020void Camera3Device::HalInterface::clear() {
3021 mHal3Device = nullptr;
3022 mHidlSession.clear();
3023}
3024
3025status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3026 camera3_request_template_t templateId,
3027 /*out*/ camera_metadata_t **requestTemplate) {
3028 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3029 if (!valid()) return INVALID_OPERATION;
3030 status_t res = OK;
3031
3032 if (mHal3Device != nullptr) {
3033 const camera_metadata *r;
3034 r = mHal3Device->ops->construct_default_request_settings(
3035 mHal3Device, templateId);
3036 if (r == nullptr) return BAD_VALUE;
3037 *requestTemplate = clone_camera_metadata(r);
3038 if (requestTemplate == nullptr) {
3039 ALOGE("%s: Unable to clone camera metadata received from HAL",
3040 __FUNCTION__);
3041 return INVALID_OPERATION;
3042 }
3043 } else {
3044 common::V1_0::Status status;
3045 RequestTemplate id;
3046 switch (templateId) {
3047 case CAMERA3_TEMPLATE_PREVIEW:
3048 id = RequestTemplate::PREVIEW;
3049 break;
3050 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3051 id = RequestTemplate::STILL_CAPTURE;
3052 break;
3053 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3054 id = RequestTemplate::VIDEO_RECORD;
3055 break;
3056 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3057 id = RequestTemplate::VIDEO_SNAPSHOT;
3058 break;
3059 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3060 id = RequestTemplate::ZERO_SHUTTER_LAG;
3061 break;
3062 case CAMERA3_TEMPLATE_MANUAL:
3063 id = RequestTemplate::MANUAL;
3064 break;
3065 default:
3066 // Unknown template ID
3067 return BAD_VALUE;
3068 }
3069 mHidlSession->constructDefaultRequestSettings(id,
3070 [&status, &requestTemplate]
3071 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3072 status = s;
3073 if (status == common::V1_0::Status::OK) {
3074 const camera_metadata *r =
3075 reinterpret_cast<const camera_metadata_t*>(request.data());
3076 size_t expectedSize = request.size();
3077 int ret = validate_camera_metadata_structure(r, &expectedSize);
3078 if (ret == OK) {
3079 *requestTemplate = clone_camera_metadata(r);
3080 if (*requestTemplate == nullptr) {
3081 ALOGE("%s: Unable to clone camera metadata received from HAL",
3082 __FUNCTION__);
3083 status = common::V1_0::Status::INTERNAL_ERROR;
3084 }
3085 } else {
3086 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3087 status = common::V1_0::Status::INTERNAL_ERROR;
3088 }
3089 }
3090 });
3091 res = CameraProviderManager::mapToStatusT(status);
3092 }
3093 return res;
3094}
3095
3096status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3097 ATRACE_NAME("CameraHal::configureStreams");
3098 if (!valid()) return INVALID_OPERATION;
3099 status_t res = OK;
3100
3101 if (mHal3Device != nullptr) {
3102 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3103 } else {
3104 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003105 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003106 StreamConfiguration requestedConfiguration;
3107 requestedConfiguration.streams.resize(config->num_streams);
3108 for (size_t i = 0; i < config->num_streams; i++) {
3109 Stream &dst = requestedConfiguration.streams[i];
3110 camera3_stream_t *src = config->streams[i];
3111
3112 int streamId = Camera3Stream::cast(src)->getId();
3113 StreamType streamType;
3114 switch (src->stream_type) {
3115 case CAMERA3_STREAM_OUTPUT:
3116 streamType = StreamType::OUTPUT;
3117 break;
3118 case CAMERA3_STREAM_INPUT:
3119 streamType = StreamType::INPUT;
3120 break;
3121 default:
3122 ALOGE("%s: Stream %d: Unsupported stream type %d",
3123 __FUNCTION__, streamId, config->streams[i]->stream_type);
3124 return BAD_VALUE;
3125 }
3126 dst.id = streamId;
3127 dst.streamType = streamType;
3128 dst.width = src->width;
3129 dst.height = src->height;
3130 dst.format = mapToPixelFormat(src->format);
3131 dst.usage = mapToConsumerUsage(src->usage);
3132 dst.dataSpace = mapToHidlDataspace(src->data_space);
3133 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003134
3135 activeStreams.insert(streamId);
3136 // Create Buffer ID map if necessary
3137 if (mBufferIdMaps.count(streamId) == 0) {
3138 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3139 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003140 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003141 // remove BufferIdMap for deleted streams
3142 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3143 int streamId = it->first;
3144 bool active = activeStreams.count(streamId) > 0;
3145 if (!active) {
3146 it = mBufferIdMaps.erase(it);
3147 } else {
3148 ++it;
3149 }
3150 }
3151
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003152 requestedConfiguration.operationMode = mapToStreamConfigurationMode(
3153 (camera3_stream_configuration_mode_t) config->operation_mode);
3154
3155 // Invoke configureStreams
3156
3157 HalStreamConfiguration finalConfiguration;
3158 common::V1_0::Status status;
3159 mHidlSession->configureStreams(requestedConfiguration,
3160 [&status, &finalConfiguration]
3161 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3162 finalConfiguration = halConfiguration;
3163 status = s;
3164 });
3165 if (status != common::V1_0::Status::OK ) {
3166 return CameraProviderManager::mapToStatusT(status);
3167 }
3168
3169 // And convert output stream configuration from HIDL
3170
3171 for (size_t i = 0; i < config->num_streams; i++) {
3172 camera3_stream_t *dst = config->streams[i];
3173 int streamId = Camera3Stream::cast(dst)->getId();
3174
3175 // Start scan at i, with the assumption that the stream order matches
3176 size_t realIdx = i;
3177 bool found = false;
3178 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3179 if (finalConfiguration.streams[realIdx].id == streamId) {
3180 found = true;
3181 break;
3182 }
3183 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3184 }
3185 if (!found) {
3186 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3187 __FUNCTION__, streamId);
3188 return INVALID_OPERATION;
3189 }
3190 HalStream &src = finalConfiguration.streams[realIdx];
3191
3192 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3193 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3194 if (dst->format != overrideFormat) {
3195 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3196 streamId, dst->format);
3197 }
3198 } else {
3199 // Override allowed with IMPLEMENTATION_DEFINED
3200 dst->format = overrideFormat;
3201 }
3202
3203 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3204 if (src.producerUsage != 0) {
3205 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3206 __FUNCTION__, streamId);
3207 return INVALID_OPERATION;
3208 }
3209 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3210 } else {
3211 // OUTPUT
3212 if (src.consumerUsage != 0) {
3213 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3214 __FUNCTION__, streamId);
3215 return INVALID_OPERATION;
3216 }
3217 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3218 }
3219 dst->max_buffers = src.maxBuffers;
3220 }
3221 }
3222 return res;
3223}
3224
3225status_t Camera3Device::HalInterface::processCaptureRequest(
3226 camera3_capture_request_t *request) {
3227 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003228 if (!valid()) return INVALID_OPERATION;
3229 status_t res = OK;
3230
3231 if (mHal3Device != nullptr) {
3232 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3233 } else {
3234 device::V3_2::CaptureRequest captureRequest;
3235 captureRequest.frameNumber = request->frame_number;
3236 std::vector<native_handle_t*> handlesCreated;
3237 // A null request settings maps to a size-0 CameraMetadata
3238 if (request->settings != nullptr) {
3239 captureRequest.settings.setToExternal(
3240 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3241 get_camera_metadata_size(request->settings));
3242 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003243
3244 {
3245 std::lock_guard<std::mutex> lock(mInflightLock);
3246 if (request->input_buffer != nullptr) {
3247 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003248 buffer_handle_t buf = *(request->input_buffer->buffer);
3249 auto pair = getBufferId(buf, streamId);
3250 bool isNewBuffer = pair.first;
3251 uint64_t bufferId = pair.second;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003252 captureRequest.inputBuffer.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003253 captureRequest.inputBuffer.bufferId = bufferId;
3254 captureRequest.inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003255 captureRequest.inputBuffer.status = BufferStatus::OK;
3256 native_handle_t *acquireFence = nullptr;
3257 if (request->input_buffer->acquire_fence != -1) {
3258 acquireFence = native_handle_create(1,0);
3259 acquireFence->data[0] = request->input_buffer->acquire_fence;
3260 handlesCreated.push_back(acquireFence);
3261 }
3262 captureRequest.inputBuffer.acquireFence = acquireFence;
3263 captureRequest.inputBuffer.releaseFence = nullptr;
3264
3265 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003266 request->input_buffer->buffer,
3267 request->input_buffer->acquire_fence);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003268 } else {
3269 captureRequest.inputBuffer.streamId = -1;
3270 captureRequest.inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003271 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003272
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003273 captureRequest.outputBuffers.resize(request->num_output_buffers);
3274 for (size_t i = 0; i < request->num_output_buffers; i++) {
3275 const camera3_stream_buffer_t *src = request->output_buffers + i;
3276 StreamBuffer &dst = captureRequest.outputBuffers[i];
3277 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003278 buffer_handle_t buf = *(src->buffer);
3279 auto pair = getBufferId(buf, streamId);
3280 bool isNewBuffer = pair.first;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003281 dst.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003282 dst.bufferId = pair.second;
3283 dst.buffer = isNewBuffer ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003284 dst.status = BufferStatus::OK;
3285 native_handle_t *acquireFence = nullptr;
3286 if (src->acquire_fence != -1) {
3287 acquireFence = native_handle_create(1,0);
3288 acquireFence->data[0] = src->acquire_fence;
3289 handlesCreated.push_back(acquireFence);
3290 }
3291 dst.acquireFence = acquireFence;
3292 dst.releaseFence = nullptr;
3293
3294 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003295 src->buffer, src->acquire_fence);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003296 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003297 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003298 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3299
3300 for (auto& handle : handlesCreated) {
3301 native_handle_delete(handle);
3302 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003303 res = CameraProviderManager::mapToStatusT(status);
3304 }
3305 return res;
3306}
3307
3308status_t Camera3Device::HalInterface::flush() {
3309 ATRACE_NAME("CameraHal::flush");
3310 if (!valid()) return INVALID_OPERATION;
3311 status_t res = OK;
3312
3313 if (mHal3Device != nullptr) {
3314 res = mHal3Device->ops->flush(mHal3Device);
3315 } else {
3316 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3317 }
3318 return res;
3319}
3320
3321status_t Camera3Device::HalInterface::dump(int fd) {
3322 ATRACE_NAME("CameraHal::dump");
3323 if (!valid()) return INVALID_OPERATION;
3324 status_t res = OK;
3325
3326 if (mHal3Device != nullptr) {
3327 mHal3Device->ops->dump(mHal3Device, fd);
3328 } else {
3329 // Handled by CameraProviderManager::dump
3330 }
3331 return res;
3332}
3333
3334status_t Camera3Device::HalInterface::close() {
3335 ATRACE_NAME("CameraHal::close()");
3336 if (!valid()) return INVALID_OPERATION;
3337 status_t res = OK;
3338
3339 if (mHal3Device != nullptr) {
3340 mHal3Device->common.close(&mHal3Device->common);
3341 } else {
3342 mHidlSession->close();
3343 }
3344 return res;
3345}
3346
3347status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003348 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003349 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003350 auto pair = std::make_pair(buffer, acquireFence);
3351 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003352 return OK;
3353}
3354
3355status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003356 int32_t frameNumber, int32_t streamId,
3357 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003358 std::lock_guard<std::mutex> lock(mInflightLock);
3359
3360 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3361 auto it = mInflightBufferMap.find(key);
3362 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003363 auto pair = it->second;
3364 *buffer = pair.first;
3365 int acquireFence = pair.second;
3366 if (acquireFence > 0) {
3367 ::close(acquireFence);
3368 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003369 mInflightBufferMap.erase(it);
3370 return OK;
3371}
3372
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003373std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3374 const buffer_handle_t& buf, int streamId) {
3375 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3376
3377 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3378 auto it = bIdMap.find(buf);
3379 if (it == bIdMap.end()) {
3380 bIdMap[buf] = mNextBufferId++;
3381 return std::make_pair(true, mNextBufferId - 1);
3382 } else {
3383 return std::make_pair(false, it->second);
3384 }
3385}
3386
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003387/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003388 * RequestThread inner class methods
3389 */
3390
3391Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003392 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003393 HalInterface* interface,
3394 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003395 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003396 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003397 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003398 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003399 mInterface(interface),
3400 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003401 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003402 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003403 mReconfigured(false),
3404 mDoPause(false),
3405 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003406 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003407 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003408 mCurrentAfTriggerId(0),
3409 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003410 mRepeatingLastFrameNumber(
3411 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003412 mAeLockAvailable(aeLockAvailable),
3413 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003414 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003415}
3416
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003417Camera3Device::RequestThread::~RequestThread() {}
3418
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003419void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003420 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003421 Mutex::Autolock l(mRequestLock);
3422 mListener = listener;
3423}
3424
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003425void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003426 Mutex::Autolock l(mRequestLock);
3427 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003428 // Prepare video stream for high speed recording.
3429 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003430}
3431
Jianing Wei90e59c92014-03-12 18:29:36 -07003432status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003433 List<sp<CaptureRequest> > &requests,
3434 /*out*/
3435 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003436 Mutex::Autolock l(mRequestLock);
3437 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3438 ++it) {
3439 mRequestQueue.push_back(*it);
3440 }
3441
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003442 if (lastFrameNumber != NULL) {
3443 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3444 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3445 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3446 *lastFrameNumber);
3447 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003448
Jianing Wei90e59c92014-03-12 18:29:36 -07003449 unpauseForNewRequests();
3450
3451 return OK;
3452}
3453
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003454
3455status_t Camera3Device::RequestThread::queueTrigger(
3456 RequestTrigger trigger[],
3457 size_t count) {
3458
3459 Mutex::Autolock l(mTriggerMutex);
3460 status_t ret;
3461
3462 for (size_t i = 0; i < count; ++i) {
3463 ret = queueTriggerLocked(trigger[i]);
3464
3465 if (ret != OK) {
3466 return ret;
3467 }
3468 }
3469
3470 return OK;
3471}
3472
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003473const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3474 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003475 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003476 if (d != nullptr) return d->mId;
3477 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003478}
3479
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003480status_t Camera3Device::RequestThread::queueTriggerLocked(
3481 RequestTrigger trigger) {
3482
3483 uint32_t tag = trigger.metadataTag;
3484 ssize_t index = mTriggerMap.indexOfKey(tag);
3485
3486 switch (trigger.getTagType()) {
3487 case TYPE_BYTE:
3488 // fall-through
3489 case TYPE_INT32:
3490 break;
3491 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003492 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3493 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003494 return INVALID_OPERATION;
3495 }
3496
3497 /**
3498 * Collect only the latest trigger, since we only have 1 field
3499 * in the request settings per trigger tag, and can't send more than 1
3500 * trigger per request.
3501 */
3502 if (index != NAME_NOT_FOUND) {
3503 mTriggerMap.editValueAt(index) = trigger;
3504 } else {
3505 mTriggerMap.add(tag, trigger);
3506 }
3507
3508 return OK;
3509}
3510
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003511status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003512 const RequestList &requests,
3513 /*out*/
3514 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003515 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003516 if (lastFrameNumber != NULL) {
3517 *lastFrameNumber = mRepeatingLastFrameNumber;
3518 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003519 mRepeatingRequests.clear();
3520 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3521 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003522
3523 unpauseForNewRequests();
3524
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003525 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003526 return OK;
3527}
3528
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003529bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003530 if (mRepeatingRequests.empty()) {
3531 return false;
3532 }
3533 int32_t requestId = requestIn->mResultExtras.requestId;
3534 const RequestList &repeatRequests = mRepeatingRequests;
3535 // All repeating requests are guaranteed to have same id so only check first quest
3536 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3537 return (firstRequest->mResultExtras.requestId == requestId);
3538}
3539
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003540status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003541 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003542 return clearRepeatingRequestsLocked(lastFrameNumber);
3543
3544}
3545
3546status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003547 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003548 if (lastFrameNumber != NULL) {
3549 *lastFrameNumber = mRepeatingLastFrameNumber;
3550 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003551 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003552 return OK;
3553}
3554
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003555status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003556 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003557 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003558 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003559
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003560 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003561
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003562 // Send errors for all requests pending in the request queue, including
3563 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003564 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003565 if (listener != NULL) {
3566 for (RequestList::iterator it = mRequestQueue.begin();
3567 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003568 // Abort the input buffers for reprocess requests.
3569 if ((*it)->mInputStream != NULL) {
3570 camera3_stream_buffer_t inputBuffer;
3571 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3572 if (res != OK) {
3573 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3574 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3575 } else {
3576 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3577 if (res != OK) {
3578 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3579 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3580 }
3581 }
3582 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003583 // Set the frame number this request would have had, if it
3584 // had been submitted; this frame number will not be reused.
3585 // The requestId and burstId fields were set when the request was
3586 // submitted originally (in convertMetadataListToRequestListLocked)
3587 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003588 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003589 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003590 }
3591 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003592 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003593
3594 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003595 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003596 if (lastFrameNumber != NULL) {
3597 *lastFrameNumber = mRepeatingLastFrameNumber;
3598 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003599 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003600 return OK;
3601}
3602
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003603status_t Camera3Device::RequestThread::flush() {
3604 ATRACE_CALL();
3605 Mutex::Autolock l(mFlushLock);
3606
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003607 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3608 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003609 }
3610
3611 return -ENOTSUP;
3612}
3613
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003614void Camera3Device::RequestThread::setPaused(bool paused) {
3615 Mutex::Autolock l(mPauseLock);
3616 mDoPause = paused;
3617 mDoPauseSignal.signal();
3618}
3619
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003620status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3621 int32_t requestId, nsecs_t timeout) {
3622 Mutex::Autolock l(mLatestRequestMutex);
3623 status_t res;
3624 while (mLatestRequestId != requestId) {
3625 nsecs_t startTime = systemTime();
3626
3627 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3628 if (res != OK) return res;
3629
3630 timeout -= (systemTime() - startTime);
3631 }
3632
3633 return OK;
3634}
3635
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003636void Camera3Device::RequestThread::requestExit() {
3637 // Call parent to set up shutdown
3638 Thread::requestExit();
3639 // The exit from any possible waits
3640 mDoPauseSignal.signal();
3641 mRequestSignal.signal();
3642}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003643
Chien-Yu Chend196d612015-06-22 19:49:01 -07003644
3645/**
3646 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3647 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3648 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3649 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3650 * request.
3651 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003652void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003653 request->mAeTriggerCancelOverride.applyAeLock = false;
3654 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3655
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003656 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003657 return;
3658 }
3659
3660 camera_metadata_entry_t aePrecaptureTrigger =
3661 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3662 if (aePrecaptureTrigger.count > 0 &&
3663 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3664 // Always override CANCEL to IDLE
3665 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3666 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3667 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3668 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3669 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3670
3671 if (mAeLockAvailable == true) {
3672 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3673 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3674 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3675 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3676 request->mAeTriggerCancelOverride.applyAeLock = true;
3677 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3678 }
3679 }
3680 }
3681}
3682
3683/**
3684 * Override result metadata for cancelling AE precapture trigger applied in
3685 * handleAePrecaptureCancelRequest().
3686 */
3687void Camera3Device::overrideResultForPrecaptureCancel(
3688 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3689 if (aeTriggerCancelOverride.applyAeLock) {
3690 // Only devices <= v3.2 should have this override
3691 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3692 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3693 }
3694
3695 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3696 // Only devices <= v3.2 should have this override
3697 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3698 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3699 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3700 }
3701}
3702
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003703void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003704 bool surfaceAbandoned = false;
3705 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003706 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003707 {
3708 Mutex::Autolock l(mRequestLock);
3709 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3710 // repeating requests.
3711 for (const auto& request : mRepeatingRequests) {
3712 for (const auto& s : request->mOutputStreams) {
3713 if (s->isAbandoned()) {
3714 surfaceAbandoned = true;
3715 clearRepeatingRequestsLocked(&lastFrameNumber);
3716 break;
3717 }
3718 }
3719 if (surfaceAbandoned) {
3720 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003721 }
3722 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003723 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003724 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003725
3726 if (listener != NULL && surfaceAbandoned) {
3727 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003728 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003729}
3730
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003731bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003732 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003733 status_t res;
3734
3735 // Handle paused state.
3736 if (waitIfPaused()) {
3737 return true;
3738 }
3739
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003740 // Wait for the next batch of requests.
3741 waitForNextRequestBatch();
3742 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003743 return true;
3744 }
3745
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003746 // Get the latest request ID, if any
3747 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003748 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003749 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003750 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003751 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003752 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003753 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3754 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003755 }
3756
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003757 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003758 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003759 if (res == TIMED_OUT) {
3760 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003761 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003762 // Check if any stream is abandoned.
3763 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003764 return true;
3765 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003766 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003767 return false;
3768 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003769
Zhijun Hecc27e112013-10-03 16:12:43 -07003770 // Inform waitUntilRequestProcessed thread of a new request ID
3771 {
3772 Mutex::Autolock al(mLatestRequestMutex);
3773
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003774 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003775 mLatestRequestSignal.signal();
3776 }
3777
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003778 // Submit a batch of requests to HAL.
3779 // Use flush lock only when submitting multilple requests in a batch.
3780 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3781 // which may take a long time to finish so synchronizing flush() and
3782 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3783 // For now, only synchronize for high speed recording and we should figure something out for
3784 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003785 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003786
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003787 if (useFlushLock) {
3788 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003789 }
3790
Zhijun Hef0645c12016-08-02 00:58:11 -07003791 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003792 mNextRequests.size());
3793 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003794 // Submit request and block until ready for next one
3795 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003796 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003797
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003798 if (res != OK) {
3799 // Should only get a failure here for malformed requests or device-level
3800 // errors, so consider all errors fatal. Bad metadata failures should
3801 // come through notify.
3802 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3803 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3804 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003805 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003806 if (useFlushLock) {
3807 mFlushLock.unlock();
3808 }
3809 return false;
3810 }
3811
3812 // Mark that the request has be submitted successfully.
3813 nextRequest.submitted = true;
3814
3815 // Update the latest request sent to HAL
3816 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3817 Mutex::Autolock al(mLatestRequestMutex);
3818
3819 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3820 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003821
3822 sp<Camera3Device> parent = mParent.promote();
3823 if (parent != NULL) {
3824 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3825 0, mLatestRequest);
3826 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003827 }
3828
3829 if (nextRequest.halRequest.settings != NULL) {
3830 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3831 }
3832
3833 // Remove any previously queued triggers (after unlock)
3834 res = removeTriggers(mPrevRequest);
3835 if (res != OK) {
3836 SET_ERR("RequestThread: Unable to remove triggers "
3837 "(capture request %d, HAL device: %s (%d)",
3838 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003839 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003840 if (useFlushLock) {
3841 mFlushLock.unlock();
3842 }
3843 return false;
3844 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003845 }
3846
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003847 if (useFlushLock) {
3848 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003849 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003850
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003851 // Unset as current request
3852 {
3853 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003854 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003855 }
3856
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003857 return true;
3858}
3859
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003860status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003861 ATRACE_CALL();
3862
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003863 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003864 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3865 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3866 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3867
3868 // Prepare a request to HAL
3869 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3870
3871 // Insert any queued triggers (before metadata is locked)
3872 status_t res = insertTriggers(captureRequest);
3873
3874 if (res < 0) {
3875 SET_ERR("RequestThread: Unable to insert triggers "
3876 "(capture request %d, HAL device: %s (%d)",
3877 halRequest->frame_number, strerror(-res), res);
3878 return INVALID_OPERATION;
3879 }
3880 int triggerCount = res;
3881 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3882 mPrevTriggers = triggerCount;
3883
3884 // If the request is the same as last, or we had triggers last time
3885 if (mPrevRequest != captureRequest || triggersMixedIn) {
3886 /**
3887 * HAL workaround:
3888 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3889 */
3890 res = addDummyTriggerIds(captureRequest);
3891 if (res != OK) {
3892 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3893 "(capture request %d, HAL device: %s (%d)",
3894 halRequest->frame_number, strerror(-res), res);
3895 return INVALID_OPERATION;
3896 }
3897
3898 /**
3899 * The request should be presorted so accesses in HAL
3900 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3901 */
3902 captureRequest->mSettings.sort();
3903 halRequest->settings = captureRequest->mSettings.getAndLock();
3904 mPrevRequest = captureRequest;
3905 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3906
3907 IF_ALOGV() {
3908 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3909 find_camera_metadata_ro_entry(
3910 halRequest->settings,
3911 ANDROID_CONTROL_AF_TRIGGER,
3912 &e
3913 );
3914 if (e.count > 0) {
3915 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3916 __FUNCTION__,
3917 halRequest->frame_number,
3918 e.data.u8[0]);
3919 }
3920 }
3921 } else {
3922 // leave request.settings NULL to indicate 'reuse latest given'
3923 ALOGVV("%s: Request settings are REUSED",
3924 __FUNCTION__);
3925 }
3926
3927 uint32_t totalNumBuffers = 0;
3928
3929 // Fill in buffers
3930 if (captureRequest->mInputStream != NULL) {
3931 halRequest->input_buffer = &captureRequest->mInputBuffer;
3932 totalNumBuffers += 1;
3933 } else {
3934 halRequest->input_buffer = NULL;
3935 }
3936
3937 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3938 captureRequest->mOutputStreams.size());
3939 halRequest->output_buffers = outputBuffers->array();
3940 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003941 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
3942
3943 // Prepare video buffers for high speed recording on the first video request.
3944 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3945 // Only try to prepare video stream on the first video request.
3946 mPrepareVideoStream = false;
3947
3948 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3949 while (res == NOT_ENOUGH_DATA) {
3950 res = outputStream->prepareNextBuffer();
3951 }
3952 if (res != OK) {
3953 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3954 __FUNCTION__, strerror(-res), res);
3955 outputStream->cancelPrepare();
3956 }
3957 }
3958
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08003959 res = outputStream->getBuffer(&outputBuffers->editItemAt(i),
3960 captureRequest->mOutputSurfaces[i]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003961 if (res != OK) {
3962 // Can't get output buffer from gralloc queue - this could be due to
3963 // abandoned queue or other consumer misbehavior, so not a fatal
3964 // error
3965 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3966 " %s (%d)", strerror(-res), res);
3967
3968 return TIMED_OUT;
3969 }
3970 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07003971
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003972 }
3973 totalNumBuffers += halRequest->num_output_buffers;
3974
3975 // Log request in the in-flight queue
3976 sp<Camera3Device> parent = mParent.promote();
3977 if (parent == NULL) {
3978 // Should not happen, and nowhere to send errors to, so just log it
3979 CLOGE("RequestThread: Parent is gone");
3980 return INVALID_OPERATION;
3981 }
3982 res = parent->registerInFlight(halRequest->frame_number,
3983 totalNumBuffers, captureRequest->mResultExtras,
3984 /*hasInput*/halRequest->input_buffer != NULL,
3985 captureRequest->mAeTriggerCancelOverride);
3986 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3987 ", burstId = %" PRId32 ".",
3988 __FUNCTION__,
3989 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3990 captureRequest->mResultExtras.burstId);
3991 if (res != OK) {
3992 SET_ERR("RequestThread: Unable to register new in-flight request:"
3993 " %s (%d)", strerror(-res), res);
3994 return INVALID_OPERATION;
3995 }
3996 }
3997
3998 return OK;
3999}
4000
Igor Murashkin1e479c02013-09-06 16:55:14 -07004001CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4002 Mutex::Autolock al(mLatestRequestMutex);
4003
4004 ALOGV("RequestThread::%s", __FUNCTION__);
4005
4006 return mLatestRequest;
4007}
4008
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004009bool Camera3Device::RequestThread::isStreamPending(
4010 sp<Camera3StreamInterface>& stream) {
4011 Mutex::Autolock l(mRequestLock);
4012
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004013 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004014 if (!nextRequest.submitted) {
4015 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4016 if (stream == s) return true;
4017 }
4018 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004019 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004020 }
4021
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004022 for (const auto& request : mRequestQueue) {
4023 for (const auto& s : request->mOutputStreams) {
4024 if (stream == s) return true;
4025 }
4026 if (stream == request->mInputStream) return true;
4027 }
4028
4029 for (const auto& request : mRepeatingRequests) {
4030 for (const auto& s : request->mOutputStreams) {
4031 if (stream == s) return true;
4032 }
4033 if (stream == request->mInputStream) return true;
4034 }
4035
4036 return false;
4037}
Jianing Weicb0652e2014-03-12 18:29:36 -07004038
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004039void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4040 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004041 return;
4042 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004043
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004044 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004045 // Skip the ones that have been submitted successfully.
4046 if (nextRequest.submitted) {
4047 continue;
4048 }
4049
4050 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4051 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4052 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4053
4054 if (halRequest->settings != NULL) {
4055 captureRequest->mSettings.unlock(halRequest->settings);
4056 }
4057
4058 if (captureRequest->mInputStream != NULL) {
4059 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4060 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4061 }
4062
4063 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4064 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4065 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4066 }
4067
4068 if (sendRequestError) {
4069 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004070 sp<NotificationListener> listener = mListener.promote();
4071 if (listener != NULL) {
4072 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004073 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004074 captureRequest->mResultExtras);
4075 }
4076 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004077
4078 // Remove yet-to-be submitted inflight request from inflightMap
4079 {
4080 sp<Camera3Device> parent = mParent.promote();
4081 if (parent != NULL) {
4082 Mutex::Autolock l(parent->mInFlightLock);
4083 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4084 if (idx >= 0) {
4085 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4086 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4087 parent->removeInFlightMapEntryLocked(idx);
4088 }
4089 }
4090 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004091 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004092
4093 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004094 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004095}
4096
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004097void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004098 // Optimized a bit for the simple steady-state case (single repeating
4099 // request), to avoid putting that request in the queue temporarily.
4100 Mutex::Autolock l(mRequestLock);
4101
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004102 assert(mNextRequests.empty());
4103
4104 NextRequest nextRequest;
4105 nextRequest.captureRequest = waitForNextRequestLocked();
4106 if (nextRequest.captureRequest == nullptr) {
4107 return;
4108 }
4109
4110 nextRequest.halRequest = camera3_capture_request_t();
4111 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004112 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004113
4114 // Wait for additional requests
4115 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4116
4117 for (size_t i = 1; i < batchSize; i++) {
4118 NextRequest additionalRequest;
4119 additionalRequest.captureRequest = waitForNextRequestLocked();
4120 if (additionalRequest.captureRequest == nullptr) {
4121 break;
4122 }
4123
4124 additionalRequest.halRequest = camera3_capture_request_t();
4125 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004126 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004127 }
4128
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004129 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004130 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004131 mNextRequests.size(), batchSize);
4132 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004133 }
4134
4135 return;
4136}
4137
4138sp<Camera3Device::CaptureRequest>
4139 Camera3Device::RequestThread::waitForNextRequestLocked() {
4140 status_t res;
4141 sp<CaptureRequest> nextRequest;
4142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004143 while (mRequestQueue.empty()) {
4144 if (!mRepeatingRequests.empty()) {
4145 // Always atomically enqueue all requests in a repeating request
4146 // list. Guarantees a complete in-sequence set of captures to
4147 // application.
4148 const RequestList &requests = mRepeatingRequests;
4149 RequestList::const_iterator firstRequest =
4150 requests.begin();
4151 nextRequest = *firstRequest;
4152 mRequestQueue.insert(mRequestQueue.end(),
4153 ++firstRequest,
4154 requests.end());
4155 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004156
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004157 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004158
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004159 break;
4160 }
4161
4162 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4163
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004164 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4165 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004166 Mutex::Autolock pl(mPauseLock);
4167 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004168 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004169 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004170 // Let the tracker know
4171 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4172 if (statusTracker != 0) {
4173 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4174 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004175 }
4176 // Stop waiting for now and let thread management happen
4177 return NULL;
4178 }
4179 }
4180
4181 if (nextRequest == NULL) {
4182 // Don't have a repeating request already in hand, so queue
4183 // must have an entry now.
4184 RequestList::iterator firstRequest =
4185 mRequestQueue.begin();
4186 nextRequest = *firstRequest;
4187 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004188 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4189 sp<NotificationListener> listener = mListener.promote();
4190 if (listener != NULL) {
4191 listener->notifyRequestQueueEmpty();
4192 }
4193 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004194 }
4195
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004196 // In case we've been unpaused by setPaused clearing mDoPause, need to
4197 // update internal pause state (capture/setRepeatingRequest unpause
4198 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004200 if (mPaused) {
4201 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4202 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4203 if (statusTracker != 0) {
4204 statusTracker->markComponentActive(mStatusId);
4205 }
4206 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004207 mPaused = false;
4208
4209 // Check if we've reconfigured since last time, and reset the preview
4210 // request if so. Can't use 'NULL request == repeat' across configure calls.
4211 if (mReconfigured) {
4212 mPrevRequest.clear();
4213 mReconfigured = false;
4214 }
4215
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004216 if (nextRequest != NULL) {
4217 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004218 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4219 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004220
4221 // Since RequestThread::clear() removes buffers from the input stream,
4222 // get the right buffer here before unlocking mRequestLock
4223 if (nextRequest->mInputStream != NULL) {
4224 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4225 if (res != OK) {
4226 // Can't get input buffer from gralloc queue - this could be due to
4227 // disconnected queue or other producer misbehavior, so not a fatal
4228 // error
4229 ALOGE("%s: Can't get input buffer, skipping request:"
4230 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004231
4232 sp<NotificationListener> listener = mListener.promote();
4233 if (listener != NULL) {
4234 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004235 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004236 nextRequest->mResultExtras);
4237 }
4238 return NULL;
4239 }
4240 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004241 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004242
4243 handleAePrecaptureCancelRequest(nextRequest);
4244
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004245 return nextRequest;
4246}
4247
4248bool Camera3Device::RequestThread::waitIfPaused() {
4249 status_t res;
4250 Mutex::Autolock l(mPauseLock);
4251 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004252 if (mPaused == false) {
4253 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004254 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4255 // Let the tracker know
4256 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4257 if (statusTracker != 0) {
4258 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4259 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004261
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004262 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004263 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004264 return true;
4265 }
4266 }
4267 // We don't set mPaused to false here, because waitForNextRequest needs
4268 // to further manage the paused state in case of starvation.
4269 return false;
4270}
4271
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004272void Camera3Device::RequestThread::unpauseForNewRequests() {
4273 // With work to do, mark thread as unpaused.
4274 // If paused by request (setPaused), don't resume, to avoid
4275 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004276 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004277 Mutex::Autolock p(mPauseLock);
4278 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004279 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4280 if (mPaused) {
4281 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4282 if (statusTracker != 0) {
4283 statusTracker->markComponentActive(mStatusId);
4284 }
4285 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004286 mPaused = false;
4287 }
4288}
4289
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004290void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4291 sp<Camera3Device> parent = mParent.promote();
4292 if (parent != NULL) {
4293 va_list args;
4294 va_start(args, fmt);
4295
4296 parent->setErrorStateV(fmt, args);
4297
4298 va_end(args);
4299 }
4300}
4301
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004302status_t Camera3Device::RequestThread::insertTriggers(
4303 const sp<CaptureRequest> &request) {
4304
4305 Mutex::Autolock al(mTriggerMutex);
4306
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004307 sp<Camera3Device> parent = mParent.promote();
4308 if (parent == NULL) {
4309 CLOGE("RequestThread: Parent is gone");
4310 return DEAD_OBJECT;
4311 }
4312
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004313 CameraMetadata &metadata = request->mSettings;
4314 size_t count = mTriggerMap.size();
4315
4316 for (size_t i = 0; i < count; ++i) {
4317 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004318 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004319
4320 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4321 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4322 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004323 if (isAeTrigger) {
4324 request->mResultExtras.precaptureTriggerId = triggerId;
4325 mCurrentPreCaptureTriggerId = triggerId;
4326 } else {
4327 request->mResultExtras.afTriggerId = triggerId;
4328 mCurrentAfTriggerId = triggerId;
4329 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004330 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4331 continue; // Trigger ID tag is deprecated since device HAL 3.2
4332 }
4333 }
4334
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004335 camera_metadata_entry entry = metadata.find(tag);
4336
4337 if (entry.count > 0) {
4338 /**
4339 * Already has an entry for this trigger in the request.
4340 * Rewrite it with our requested trigger value.
4341 */
4342 RequestTrigger oldTrigger = trigger;
4343
4344 oldTrigger.entryValue = entry.data.u8[0];
4345
4346 mTriggerReplacedMap.add(tag, oldTrigger);
4347 } else {
4348 /**
4349 * More typical, no trigger entry, so we just add it
4350 */
4351 mTriggerRemovedMap.add(tag, trigger);
4352 }
4353
4354 status_t res;
4355
4356 switch (trigger.getTagType()) {
4357 case TYPE_BYTE: {
4358 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4359 res = metadata.update(tag,
4360 &entryValue,
4361 /*count*/1);
4362 break;
4363 }
4364 case TYPE_INT32:
4365 res = metadata.update(tag,
4366 &trigger.entryValue,
4367 /*count*/1);
4368 break;
4369 default:
4370 ALOGE("%s: Type not supported: 0x%x",
4371 __FUNCTION__,
4372 trigger.getTagType());
4373 return INVALID_OPERATION;
4374 }
4375
4376 if (res != OK) {
4377 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4378 ", value %d", __FUNCTION__, trigger.getTagName(),
4379 trigger.entryValue);
4380 return res;
4381 }
4382
4383 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4384 trigger.getTagName(),
4385 trigger.entryValue);
4386 }
4387
4388 mTriggerMap.clear();
4389
4390 return count;
4391}
4392
4393status_t Camera3Device::RequestThread::removeTriggers(
4394 const sp<CaptureRequest> &request) {
4395 Mutex::Autolock al(mTriggerMutex);
4396
4397 CameraMetadata &metadata = request->mSettings;
4398
4399 /**
4400 * Replace all old entries with their old values.
4401 */
4402 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4403 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4404
4405 status_t res;
4406
4407 uint32_t tag = trigger.metadataTag;
4408 switch (trigger.getTagType()) {
4409 case TYPE_BYTE: {
4410 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4411 res = metadata.update(tag,
4412 &entryValue,
4413 /*count*/1);
4414 break;
4415 }
4416 case TYPE_INT32:
4417 res = metadata.update(tag,
4418 &trigger.entryValue,
4419 /*count*/1);
4420 break;
4421 default:
4422 ALOGE("%s: Type not supported: 0x%x",
4423 __FUNCTION__,
4424 trigger.getTagType());
4425 return INVALID_OPERATION;
4426 }
4427
4428 if (res != OK) {
4429 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4430 ", trigger value %d", __FUNCTION__,
4431 trigger.getTagName(), trigger.entryValue);
4432 return res;
4433 }
4434 }
4435 mTriggerReplacedMap.clear();
4436
4437 /**
4438 * Remove all new entries.
4439 */
4440 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4441 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4442 status_t res = metadata.erase(trigger.metadataTag);
4443
4444 if (res != OK) {
4445 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4446 ", trigger value %d", __FUNCTION__,
4447 trigger.getTagName(), trigger.entryValue);
4448 return res;
4449 }
4450 }
4451 mTriggerRemovedMap.clear();
4452
4453 return OK;
4454}
4455
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004456status_t Camera3Device::RequestThread::addDummyTriggerIds(
4457 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004458 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004459 static const int32_t dummyTriggerId = 1;
4460 status_t res;
4461
4462 CameraMetadata &metadata = request->mSettings;
4463
4464 // If AF trigger is active, insert a dummy AF trigger ID if none already
4465 // exists
4466 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4467 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4468 if (afTrigger.count > 0 &&
4469 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4470 afId.count == 0) {
4471 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4472 if (res != OK) return res;
4473 }
4474
4475 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4476 // if none already exists
4477 camera_metadata_entry pcTrigger =
4478 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4479 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4480 if (pcTrigger.count > 0 &&
4481 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4482 pcId.count == 0) {
4483 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4484 &dummyTriggerId, 1);
4485 if (res != OK) return res;
4486 }
4487
4488 return OK;
4489}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004490
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004491/**
4492 * PreparerThread inner class methods
4493 */
4494
4495Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004496 Thread(/*canCallJava*/false), mListener(nullptr),
4497 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004498}
4499
4500Camera3Device::PreparerThread::~PreparerThread() {
4501 Thread::requestExitAndWait();
4502 if (mCurrentStream != nullptr) {
4503 mCurrentStream->cancelPrepare();
4504 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4505 mCurrentStream.clear();
4506 }
4507 clear();
4508}
4509
Ruben Brunkc78ac262015-08-13 17:58:46 -07004510status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004511 status_t res;
4512
4513 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004514 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004515
Ruben Brunkc78ac262015-08-13 17:58:46 -07004516 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004517 if (res == OK) {
4518 // No preparation needed, fire listener right off
4519 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004520 if (listener != NULL) {
4521 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004522 }
4523 return OK;
4524 } else if (res != NOT_ENOUGH_DATA) {
4525 return res;
4526 }
4527
4528 // Need to prepare, start up thread if necessary
4529 if (!mActive) {
4530 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4531 // isn't running
4532 Thread::requestExitAndWait();
4533 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4534 if (res != OK) {
4535 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004536 if (listener != NULL) {
4537 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004538 }
4539 return res;
4540 }
4541 mCancelNow = false;
4542 mActive = true;
4543 ALOGV("%s: Preparer stream started", __FUNCTION__);
4544 }
4545
4546 // queue up the work
4547 mPendingStreams.push_back(stream);
4548 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4549
4550 return OK;
4551}
4552
4553status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004554 Mutex::Autolock l(mLock);
4555
4556 for (const auto& stream : mPendingStreams) {
4557 stream->cancelPrepare();
4558 }
4559 mPendingStreams.clear();
4560 mCancelNow = true;
4561
4562 return OK;
4563}
4564
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004565void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004566 Mutex::Autolock l(mLock);
4567 mListener = listener;
4568}
4569
4570bool Camera3Device::PreparerThread::threadLoop() {
4571 status_t res;
4572 {
4573 Mutex::Autolock l(mLock);
4574 if (mCurrentStream == nullptr) {
4575 // End thread if done with work
4576 if (mPendingStreams.empty()) {
4577 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4578 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4579 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4580 mActive = false;
4581 return false;
4582 }
4583
4584 // Get next stream to prepare
4585 auto it = mPendingStreams.begin();
4586 mCurrentStream = *it;
4587 mPendingStreams.erase(it);
4588 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4589 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4590 } else if (mCancelNow) {
4591 mCurrentStream->cancelPrepare();
4592 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4593 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4594 mCurrentStream.clear();
4595 mCancelNow = false;
4596 return true;
4597 }
4598 }
4599
4600 res = mCurrentStream->prepareNextBuffer();
4601 if (res == NOT_ENOUGH_DATA) return true;
4602 if (res != OK) {
4603 // Something bad happened; try to recover by cancelling prepare and
4604 // signalling listener anyway
4605 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4606 mCurrentStream->getId(), res, strerror(-res));
4607 mCurrentStream->cancelPrepare();
4608 }
4609
4610 // This stream has finished, notify listener
4611 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004612 sp<NotificationListener> listener = mListener.promote();
4613 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004614 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4615 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004616 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004617 }
4618
4619 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4620 mCurrentStream.clear();
4621
4622 return true;
4623}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004624
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004625/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004626 * Static callback forwarding methods from HAL to instance
4627 */
4628
4629void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4630 const camera3_capture_result *result) {
4631 Camera3Device *d =
4632 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004633
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004634 d->processCaptureResult(result);
4635}
4636
4637void Camera3Device::sNotify(const camera3_callback_ops *cb,
4638 const camera3_notify_msg *msg) {
4639 Camera3Device *d =
4640 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4641 d->notify(msg);
4642}
4643
4644}; // namespace android