blob: 3b9cb1a5587ec31547bc9395b538f804f7151a82 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mListener(NULL)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080078{
79 ATRACE_CALL();
80 camera3_callback_ops::notify = &sNotify;
81 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080082 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080083}
84
85Camera3Device::~Camera3Device()
86{
87 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080088 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080089 disconnect();
90}
91
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080093 return mId;
94}
95
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080096/**
97 * CameraDeviceBase interface
98 */
99
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800100status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700103 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800104 Mutex::Autolock l(mLock);
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800107 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700108 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109 return INVALID_OPERATION;
110 }
111
112 /** Open HAL device */
113
114 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800115
116 camera3_device_t *device;
117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118 ATRACE_BEGIN("CameraHal::open");
119 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800120 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800121 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800122
123 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700124 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800125 return res;
126 }
127
128 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700130 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700131 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800133 device->common.version);
134 device->common.close(&device->common);
135 return BAD_VALUE;
136 }
137
138 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800140 if (res != OK) return res;
141
142 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700143 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
144 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700145 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800146 device->common.close(&device->common);
147 return BAD_VALUE;
148 }
149
150 /** Initialize device with callback functions */
151
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800152 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800153 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700154 ATRACE_END();
155
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800156 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700157 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
158 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800159 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800160 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800161 }
162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800163 /** Everything is good to go */
164
165 mDeviceVersion = device->common.version;
166 mDeviceInfo = info.static_camera_characteristics;
167 mInterface = std::make_unique<HalInterface>(device);
168
169 return initializeCommonLocked();
170}
171
172status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
173 ATRACE_CALL();
174 Mutex::Autolock il(mInterfaceLock);
175 Mutex::Autolock l(mLock);
176
177 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
178 if (mStatus != STATUS_UNINITIALIZED) {
179 CLOGE("Already initialized!");
180 return INVALID_OPERATION;
181 }
182 if (manager == nullptr) return INVALID_OPERATION;
183
184 sp<ICameraDeviceSession> session;
185 ATRACE_BEGIN("CameraHal::openSession");
186 status_t res = manager->openSession(String8::std_string(mId), this,
187 /*out*/ &session);
188 ATRACE_END();
189 if (res != OK) {
190 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
191 return res;
192 }
193
194 res = manager->getCameraCharacteristics(String8::std_string(mId), &mDeviceInfo);
195 if (res != OK) {
196 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
197 session->close();
198 return res;
199 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800200
201 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
202 // for now use 3_4 to keep legacy devices working
203 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800204 mInterface = std::make_unique<HalInterface>(session);
205
206 return initializeCommonLocked();
207}
208
209status_t Camera3Device::initializeCommonLocked() {
210
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700211 /** Start up status tracker thread */
212 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800213 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700214 if (res != OK) {
215 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
216 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800217 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700218 mStatusTracker.clear();
219 return res;
220 }
221
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700222 /** Register in-flight map to the status tracker */
223 mInFlightStatusId = mStatusTracker->addComponent();
224
Zhijun He125684a2015-12-26 15:07:30 -0800225 /** Create buffer manager */
226 mBufferManager = new Camera3BufferManager();
227
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700228 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800229 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
230 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
231 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700232 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
233 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
234 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800235
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700236 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800237 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
238 aeLockAvailable);
239 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800240 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700241 SET_ERR_L("Unable to start request queue thread: %s (%d)",
242 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800243 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800244 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800245 return res;
246 }
247
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700248 mPreparerThread = new PreparerThread();
249
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700250 // Determine whether we need to derive sensitivity boost values for older devices.
251 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
252 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800253 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700254 mDerivePostRawSensKey = true;
255 }
256
Ruben Brunk183f0562015-08-12 12:55:02 -0700257 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800258 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700259 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700260 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800262
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800263 // Measure the clock domain offset between camera and video/hw_composer
264 camera_metadata_entry timestampSource =
265 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
266 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
267 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
268 mTimestampOffset = getMonoToBoottimeOffset();
269 }
270
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700271 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700272 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
273 camera_metadata_entry partialResultsCount =
274 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
275 if (partialResultsCount.count > 0) {
276 mNumPartialResults = partialResultsCount.data.i32[0];
277 mUsePartialResult = (mNumPartialResults > 1);
278 }
279 } else {
280 camera_metadata_entry partialResultsQuirk =
281 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
282 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
283 mUsePartialResult = true;
284 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700285 }
286
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700287 camera_metadata_entry configs =
288 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
289 for (uint32_t i = 0; i < configs.count; i += 4) {
290 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
291 configs.data.i32[i + 3] ==
292 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
293 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
294 configs.data.i32[i + 2]));
295 }
296 }
297
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800298 return OK;
299}
300
301status_t Camera3Device::disconnect() {
302 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700303 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700305 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800306
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700307 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800308
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 {
310 Mutex::Autolock l(mLock);
311 if (mStatus == STATUS_UNINITIALIZED) return res;
312
313 if (mStatus == STATUS_ACTIVE ||
314 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
315 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700316 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700318 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 } else {
320 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
321 if (res != OK) {
322 SET_ERR_L("Timeout waiting for HAL to drain");
323 // Continue to close device even in case of error
324 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 if (mStatus == STATUS_ERROR) {
329 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700330 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331
332 if (mStatusTracker != NULL) {
333 mStatusTracker->requestExit();
334 }
335
336 if (mRequestThread != NULL) {
337 mRequestThread->requestExit();
338 }
339
340 mOutputStreams.clear();
341 mInputStream.clear();
342 }
343
344 // Joining done without holding mLock, otherwise deadlocks may ensue
345 // as the threads try to access parent state
346 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
347 // HAL may be in a bad state, so waiting for request thread
348 // (which may be stuck in the HAL processCaptureRequest call)
349 // could be dangerous.
350 mRequestThread->join();
351 }
352
353 if (mStatusTracker != NULL) {
354 mStatusTracker->join();
355 }
356
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700358 {
359 Mutex::Autolock l(mLock);
360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800361 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700362 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800363 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800365 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800367
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700368 // Call close without internal mutex held, as the HAL close may need to
369 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800370 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700371
372 {
373 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800374 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700375 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700376 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800377
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700378 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700379 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800380}
381
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382// For dumping/debugging only -
383// try to acquire a lock a few times, eventually give up to proceed with
384// debug/dump operations
385bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
386 bool gotLock = false;
387 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
388 if (lock.tryLock() == NO_ERROR) {
389 gotLock = true;
390 break;
391 } else {
392 usleep(kDumpSleepDuration);
393 }
394 }
395 return gotLock;
396}
397
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700398Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
399 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
400 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
401 const int STREAM_CONFIGURATION_SIZE = 4;
402 const int STREAM_FORMAT_OFFSET = 0;
403 const int STREAM_WIDTH_OFFSET = 1;
404 const int STREAM_HEIGHT_OFFSET = 2;
405 const int STREAM_IS_INPUT_OFFSET = 3;
406 camera_metadata_ro_entry_t availableStreamConfigs =
407 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
408 if (availableStreamConfigs.count == 0 ||
409 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
410 return Size(0, 0);
411 }
412
413 // Get max jpeg size (area-wise).
414 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
415 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
416 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
417 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
418 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
419 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
420 && format == HAL_PIXEL_FORMAT_BLOB &&
421 (width * height > maxJpegWidth * maxJpegHeight)) {
422 maxJpegWidth = width;
423 maxJpegHeight = height;
424 }
425 }
426 } else {
427 camera_metadata_ro_entry availableJpegSizes =
428 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
429 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
430 return Size(0, 0);
431 }
432
433 // Get max jpeg size (area-wise).
434 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
435 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
436 > (maxJpegWidth * maxJpegHeight)) {
437 maxJpegWidth = availableJpegSizes.data.i32[i];
438 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
439 }
440 }
441 }
442 return Size(maxJpegWidth, maxJpegHeight);
443}
444
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800445nsecs_t Camera3Device::getMonoToBoottimeOffset() {
446 // try three times to get the clock offset, choose the one
447 // with the minimum gap in measurements.
448 const int tries = 3;
449 nsecs_t bestGap, measured;
450 for (int i = 0; i < tries; ++i) {
451 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
452 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
453 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
454 const nsecs_t gap = tmono2 - tmono;
455 if (i == 0 || gap < bestGap) {
456 bestGap = gap;
457 measured = tbase - ((tmono + tmono2) >> 1);
458 }
459 }
460 return measured;
461}
462
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700463/**
464 * Map Android N dataspace definitions back to Android M definitions, for
465 * use with HALv3.3 or older.
466 *
467 * Only map where correspondences exist, and otherwise preserve the value.
468 */
469android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
470 switch (dataSpace) {
471 case HAL_DATASPACE_V0_SRGB_LINEAR:
472 return HAL_DATASPACE_SRGB_LINEAR;
473 case HAL_DATASPACE_V0_SRGB:
474 return HAL_DATASPACE_SRGB;
475 case HAL_DATASPACE_V0_JFIF:
476 return HAL_DATASPACE_JFIF;
477 case HAL_DATASPACE_V0_BT601_625:
478 return HAL_DATASPACE_BT601_625;
479 case HAL_DATASPACE_V0_BT601_525:
480 return HAL_DATASPACE_BT601_525;
481 case HAL_DATASPACE_V0_BT709:
482 return HAL_DATASPACE_BT709;
483 default:
484 return dataSpace;
485 }
486}
487
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
489 int frameworkFormat) {
490 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
491}
492
493DataspaceFlags Camera3Device::mapToHidlDataspace(
494 android_dataspace dataSpace) {
495 return dataSpace;
496}
497
498ConsumerUsageFlags Camera3Device::mapToConsumerUsage(
499 uint32_t usage) {
500 return usage;
501}
502
503StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
504 switch (rotation) {
505 case CAMERA3_STREAM_ROTATION_0:
506 return StreamRotation::ROTATION_0;
507 case CAMERA3_STREAM_ROTATION_90:
508 return StreamRotation::ROTATION_90;
509 case CAMERA3_STREAM_ROTATION_180:
510 return StreamRotation::ROTATION_180;
511 case CAMERA3_STREAM_ROTATION_270:
512 return StreamRotation::ROTATION_270;
513 }
514 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
515 return StreamRotation::ROTATION_0;
516}
517
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800518status_t Camera3Device::mapToStreamConfigurationMode(
519 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
520 if (mode == nullptr) return BAD_VALUE;
521 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
522 switch(operationMode) {
523 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
524 *mode = StreamConfigurationMode::NORMAL_MODE;
525 break;
526 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
527 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
528 break;
529 default:
530 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
531 return BAD_VALUE;
532 }
533 } else {
534 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800535 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800536 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800537}
538
539camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
540 switch (status) {
541 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
542 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
543 }
544 return CAMERA3_BUFFER_STATUS_ERROR;
545}
546
547int Camera3Device::mapToFrameworkFormat(
548 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
549 return static_cast<uint32_t>(pixelFormat);
550}
551
552uint32_t Camera3Device::mapConsumerToFrameworkUsage(
553 ConsumerUsageFlags usage) {
554 return usage;
555}
556
557uint32_t Camera3Device::mapProducerToFrameworkUsage(
558 ProducerUsageFlags usage) {
559 return usage;
560}
561
Zhijun Hef7da0962014-04-24 13:27:56 -0700562ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700563 // Get max jpeg size (area-wise).
564 Size maxJpegResolution = getMaxJpegResolution();
565 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800566 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
567 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700568 return BAD_VALUE;
569 }
570
Zhijun Hef7da0962014-04-24 13:27:56 -0700571 // Get max jpeg buffer size
572 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700573 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
574 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800575 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
576 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700577 return BAD_VALUE;
578 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700579 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800580 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700581
582 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700583 float scaleFactor = ((float) (width * height)) /
584 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800585 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
586 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700587 if (jpegBufferSize > maxJpegBufferSize) {
588 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700589 }
590
591 return jpegBufferSize;
592}
593
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700594ssize_t Camera3Device::getPointCloudBufferSize() const {
595 const int FLOATS_PER_POINT=4;
596 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
597 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800598 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
599 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700600 return BAD_VALUE;
601 }
602 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
603 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
604 return maxBytesForPointCloud;
605}
606
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800607ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800608 const int PER_CONFIGURATION_SIZE = 3;
609 const int WIDTH_OFFSET = 0;
610 const int HEIGHT_OFFSET = 1;
611 const int SIZE_OFFSET = 2;
612 camera_metadata_ro_entry rawOpaqueSizes =
613 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800614 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800615 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
617 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800618 return BAD_VALUE;
619 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700620
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800621 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
622 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
623 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
624 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
625 }
626 }
627
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
629 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800630 return BAD_VALUE;
631}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700632
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800633status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
634 ATRACE_CALL();
635 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700636
637 // Try to lock, but continue in case of failure (to avoid blocking in
638 // deadlocks)
639 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
640 bool gotLock = tryLockSpinRightRound(mLock);
641
642 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800643 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
644 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800646 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
647 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700648
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800649 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700650
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800651 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700652 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800653 int n = args.size();
654 for (int i = 0; i < n; i++) {
655 if (args[i] == templatesOption) {
656 dumpTemplates = true;
657 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700658 if (args[i] == monitorOption) {
659 if (i + 1 < n) {
660 String8 monitorTags = String8(args[i + 1]);
661 if (monitorTags == "off") {
662 mTagMonitor.disableMonitoring();
663 } else {
664 mTagMonitor.parseTagsToMonitor(monitorTags);
665 }
666 } else {
667 mTagMonitor.disableMonitoring();
668 }
669 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800670 }
671
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800673
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800674 const char *status =
675 mStatus == STATUS_ERROR ? "ERROR" :
676 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700677 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
678 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800679 mStatus == STATUS_ACTIVE ? "ACTIVE" :
680 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700681
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700683 if (mStatus == STATUS_ERROR) {
684 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
685 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800686 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800687 const char *mode =
688 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
689 mOperatingMode == static_cast<int>(
690 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
691 "CUSTOM";
692 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800693
694 if (mInputStream != NULL) {
695 write(fd, lines.string(), lines.size());
696 mInputStream->dump(fd, args);
697 } else {
698 lines.appendFormat(" No input stream.\n");
699 write(fd, lines.string(), lines.size());
700 }
701 for (size_t i = 0; i < mOutputStreams.size(); i++) {
702 mOutputStreams[i]->dump(fd,args);
703 }
704
Zhijun He431503c2016-03-07 17:30:16 -0800705 if (mBufferManager != NULL) {
706 lines = String8(" Camera3 Buffer Manager:\n");
707 write(fd, lines.string(), lines.size());
708 mBufferManager->dump(fd, args);
709 }
Zhijun He125684a2015-12-26 15:07:30 -0800710
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700711 lines = String8(" In-flight requests:\n");
712 if (mInFlightMap.size() == 0) {
713 lines.append(" None\n");
714 } else {
715 for (size_t i = 0; i < mInFlightMap.size(); i++) {
716 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700717 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700718 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800719 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700720 r.numBuffersLeft);
721 }
722 }
723 write(fd, lines.string(), lines.size());
724
Igor Murashkin1e479c02013-09-06 16:55:14 -0700725 {
726 lines = String8(" Last request sent:\n");
727 write(fd, lines.string(), lines.size());
728
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700729 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700730 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
731 }
732
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800733 if (dumpTemplates) {
734 const char *templateNames[] = {
735 "TEMPLATE_PREVIEW",
736 "TEMPLATE_STILL_CAPTURE",
737 "TEMPLATE_VIDEO_RECORD",
738 "TEMPLATE_VIDEO_SNAPSHOT",
739 "TEMPLATE_ZERO_SHUTTER_LAG",
740 "TEMPLATE_MANUAL"
741 };
742
743 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800744 camera_metadata_t *templateRequest = nullptr;
745 mInterface->constructDefaultRequestSettings(
746 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800747 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800748 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800749 lines.append(" Not supported\n");
750 write(fd, lines.string(), lines.size());
751 } else {
752 write(fd, lines.string(), lines.size());
753 dump_indented_camera_metadata(templateRequest,
754 fd, /*verbosity*/2, /*indentation*/8);
755 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800756 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800757 }
758 }
759
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700760 mTagMonitor.dumpMonitoredMetadata(fd);
761
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800762 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800763 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800764 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800765 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800766 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800767
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700768 if (gotLock) mLock.unlock();
769 if (gotInterfaceLock) mInterfaceLock.unlock();
770
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771 return OK;
772}
773
774const CameraMetadata& Camera3Device::info() const {
775 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800776 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
777 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700778 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800779 mStatus == STATUS_ERROR ?
780 "when in error state" : "before init");
781 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800782 return mDeviceInfo;
783}
784
Jianing Wei90e59c92014-03-12 18:29:36 -0700785status_t Camera3Device::checkStatusOkToCaptureLocked() {
786 switch (mStatus) {
787 case STATUS_ERROR:
788 CLOGE("Device has encountered a serious error");
789 return INVALID_OPERATION;
790 case STATUS_UNINITIALIZED:
791 CLOGE("Device not initialized");
792 return INVALID_OPERATION;
793 case STATUS_UNCONFIGURED:
794 case STATUS_CONFIGURED:
795 case STATUS_ACTIVE:
796 // OK
797 break;
798 default:
799 SET_ERR_L("Unexpected status: %d", mStatus);
800 return INVALID_OPERATION;
801 }
802 return OK;
803}
804
805status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 const List<const CameraMetadata> &metadataList,
807 const std::list<const SurfaceMap> &surfaceMaps,
808 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700809 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 if (requestList == NULL) {
811 CLOGE("requestList cannot be NULL.");
812 return BAD_VALUE;
813 }
814
Jianing Weicb0652e2014-03-12 18:29:36 -0700815 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
817 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
818 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
819 ++metadataIt, ++surfaceMapIt) {
820 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700821 if (newRequest == 0) {
822 CLOGE("Can't create capture request");
823 return BAD_VALUE;
824 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700825
Shuzhen Wang9d066012016-09-30 11:30:20 -0700826 newRequest->mRepeating = repeating;
827
Jianing Weicb0652e2014-03-12 18:29:36 -0700828 // Setup burst Id and request Id
829 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
831 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700832 CLOGE("RequestID entry exists; but must not be empty in metadata");
833 return BAD_VALUE;
834 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700836 } else {
837 CLOGE("RequestID does not exist in metadata");
838 return BAD_VALUE;
839 }
840
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700842
843 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700845 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
846 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
847 return BAD_VALUE;
848 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700849
850 // Setup batch size if this is a high speed video recording request.
851 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
852 auto firstRequest = requestList->begin();
853 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
854 if (outputStream->isVideoStream()) {
855 (*firstRequest)->mBatchSize = requestList->size();
856 break;
857 }
858 }
859 }
860
Jianing Wei90e59c92014-03-12 18:29:36 -0700861 return OK;
862}
863
Jianing Weicb0652e2014-03-12 18:29:36 -0700864status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800865 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800866
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700867 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868 std::list<const SurfaceMap> surfaceMaps;
869 convertToRequestList(requests, surfaceMaps, request);
870
871 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
872}
873
874void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
875 std::list<const SurfaceMap>& surfaceMaps,
876 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700877 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700878
879 SurfaceMap surfaceMap;
880 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
881 // With no surface list passed in, stream and surface will have 1-to-1
882 // mapping. So the surface index is 0 for each stream in the surfaceMap.
883 for (size_t i = 0; i < streams.count; i++) {
884 surfaceMap[streams.data.i32[i]].push_back(0);
885 }
886 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800887}
888
Jianing Wei90e59c92014-03-12 18:29:36 -0700889status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700890 const List<const CameraMetadata> &requests,
891 const std::list<const SurfaceMap> &surfaceMaps,
892 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700893 /*out*/
894 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700895 ATRACE_CALL();
896 Mutex::Autolock il(mInterfaceLock);
897 Mutex::Autolock l(mLock);
898
899 status_t res = checkStatusOkToCaptureLocked();
900 if (res != OK) {
901 // error logged by previous call
902 return res;
903 }
904
905 RequestList requestList;
906
Shuzhen Wang0129d522016-10-30 22:43:41 -0700907 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
908 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700909 if (res != OK) {
910 // error logged by previous call
911 return res;
912 }
913
914 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700915 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700916 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700917 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 }
919
920 if (res == OK) {
921 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
922 if (res != OK) {
923 SET_ERR_L("Can't transition to active in %f seconds!",
924 kActiveTimeout/1e9);
925 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700927 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700928 } else {
929 CLOGE("Cannot queue request. Impossible.");
930 return BAD_VALUE;
931 }
932
933 return res;
934}
935
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936hardware::Return<void> Camera3Device::processCaptureResult(
937 const device::V3_2::CaptureResult& result) {
938 camera3_capture_result r;
939 status_t res;
940 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800941 if (result.result.size() != 0) {
942 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
943 size_t expected_metadata_size = result.result.size();
944 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
945 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
946 __FUNCTION__, result.frameNumber, strerror(-res), res);
947 return hardware::Void();
948 }
949 } else {
950 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800951 }
952
953 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
954 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
955 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
956 auto& bDst = outputBuffers[i];
957 const StreamBuffer &bSrc = result.outputBuffers[i];
958
959 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
960 if (idx == -1) {
961 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
962 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
963 return hardware::Void();
964 }
965 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
966
967 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800968 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800969 if (res != OK) {
970 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
971 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
972 return hardware::Void();
973 }
974 bDst.buffer = buffer;
975 bDst.status = mapHidlBufferStatus(bSrc.status);
976 bDst.acquire_fence = -1;
977 if (bSrc.releaseFence == nullptr) {
978 bDst.release_fence = -1;
979 } else if (bSrc.releaseFence->numFds == 1) {
980 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
981 } else {
982 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
983 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
984 return hardware::Void();
985 }
986 }
987 r.num_output_buffers = outputBuffers.size();
988 r.output_buffers = outputBuffers.data();
989
990 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800991 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800992 r.input_buffer = nullptr;
993 } else {
994 if (mInputStream->getId() != result.inputBuffer.streamId) {
995 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
996 result.frameNumber, result.inputBuffer.streamId);
997 return hardware::Void();
998 }
999 inputBuffer.stream = mInputStream->asHalStream();
1000 buffer_handle_t *buffer;
1001 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1002 &buffer);
1003 if (res != OK) {
1004 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1005 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
1006 return hardware::Void();
1007 }
1008 inputBuffer.buffer = buffer;
1009 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1010 inputBuffer.acquire_fence = -1;
1011 if (result.inputBuffer.releaseFence == nullptr) {
1012 inputBuffer.release_fence = -1;
1013 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1014 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1015 } else {
1016 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1017 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
1018 return hardware::Void();
1019 }
1020 r.input_buffer = &inputBuffer;
1021 }
1022
1023 r.partial_result = result.partialResult;
1024
1025 processCaptureResult(&r);
1026
1027 return hardware::Void();
1028}
1029
1030hardware::Return<void> Camera3Device::notify(
1031 const NotifyMsg& msg) {
1032 camera3_notify_msg m;
1033 switch (msg.type) {
1034 case MsgType::ERROR:
1035 m.type = CAMERA3_MSG_ERROR;
1036 m.message.error.frame_number = msg.msg.error.frameNumber;
1037 if (msg.msg.error.errorStreamId >= 0) {
1038 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
1039 if (idx == -1) {
1040 ALOGE("%s: Frame %d: Invalid error stream id %d",
1041 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1042 return hardware::Void();
1043 }
1044 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1045 } else {
1046 m.message.error.error_stream = nullptr;
1047 }
1048 switch (msg.msg.error.errorCode) {
1049 case ErrorCode::ERROR_DEVICE:
1050 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1051 break;
1052 case ErrorCode::ERROR_REQUEST:
1053 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1054 break;
1055 case ErrorCode::ERROR_RESULT:
1056 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1057 break;
1058 case ErrorCode::ERROR_BUFFER:
1059 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1060 break;
1061 }
1062 break;
1063 case MsgType::SHUTTER:
1064 m.type = CAMERA3_MSG_SHUTTER;
1065 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1066 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1067 break;
1068 }
1069 notify(&m);
1070
1071 return hardware::Void();
1072}
1073
Jianing Weicb0652e2014-03-12 18:29:36 -07001074status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001075 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001076 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001077 ATRACE_CALL();
1078
Shuzhen Wang0129d522016-10-30 22:43:41 -07001079 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001080}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001081
Jianing Weicb0652e2014-03-12 18:29:36 -07001082status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1083 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001084 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001086 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001087 std::list<const SurfaceMap> surfaceMaps;
1088 convertToRequestList(requests, surfaceMaps, request);
1089
1090 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1091 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001092}
1093
Jianing Weicb0652e2014-03-12 18:29:36 -07001094status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001096 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001097 ATRACE_CALL();
1098
Shuzhen Wang0129d522016-10-30 22:43:41 -07001099 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001100}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001101
1102sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 status_t res;
1105
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001106 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001108 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001109 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001110 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001111 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001112 } else if (mStatus == STATUS_UNCONFIGURED) {
1113 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001114 CLOGE("No streams configured");
1115 return NULL;
1116 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 }
1118
Shuzhen Wang0129d522016-10-30 22:43:41 -07001119 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001120 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001121}
1122
Jianing Weicb0652e2014-03-12 18:29:36 -07001123status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001124 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001125 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001127
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128 switch (mStatus) {
1129 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001130 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001131 return INVALID_OPERATION;
1132 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001133 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001134 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 case STATUS_UNCONFIGURED:
1136 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 case STATUS_ACTIVE:
1138 // OK
1139 break;
1140 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001141 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001142 return INVALID_OPERATION;
1143 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001144 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001145
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001146 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001147}
1148
1149status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1150 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001151 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001152
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001153 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001154}
1155
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001156status_t Camera3Device::createInputStream(
1157 uint32_t width, uint32_t height, int format, int *id) {
1158 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001159 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001160 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001161 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1162 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001163
1164 status_t res;
1165 bool wasActive = false;
1166
1167 switch (mStatus) {
1168 case STATUS_ERROR:
1169 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1170 return INVALID_OPERATION;
1171 case STATUS_UNINITIALIZED:
1172 ALOGE("%s: Device not initialized", __FUNCTION__);
1173 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 case STATUS_UNCONFIGURED:
1175 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001176 // OK
1177 break;
1178 case STATUS_ACTIVE:
1179 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001180 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001181 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001182 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001183 return res;
1184 }
1185 wasActive = true;
1186 break;
1187 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001188 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001189 return INVALID_OPERATION;
1190 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001192
1193 if (mInputStream != 0) {
1194 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1195 return INVALID_OPERATION;
1196 }
1197
1198 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1199 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001201
1202 mInputStream = newStream;
1203
1204 *id = mNextStreamId++;
1205
1206 // Continue captures if active at start
1207 if (wasActive) {
1208 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1209 res = configureStreamsLocked();
1210 if (res != OK) {
1211 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1212 __FUNCTION__, mNextStreamId, strerror(-res), res);
1213 return res;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001216 }
1217
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001218 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001219 return OK;
1220}
1221
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001222status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001223 uint32_t width, uint32_t height, int format,
1224 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001225 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001226 ATRACE_CALL();
1227
1228 if (consumer == nullptr) {
1229 ALOGE("%s: consumer must not be null", __FUNCTION__);
1230 return BAD_VALUE;
1231 }
1232
1233 std::vector<sp<Surface>> consumers;
1234 consumers.push_back(consumer);
1235
1236 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001237 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001238}
1239
1240status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1241 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1242 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001243 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001247 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001248 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1249 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001250
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 status_t res;
1252 bool wasActive = false;
1253
1254 switch (mStatus) {
1255 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001256 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 return INVALID_OPERATION;
1258 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001259 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 case STATUS_UNCONFIGURED:
1262 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 // OK
1264 break;
1265 case STATUS_ACTIVE:
1266 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001269 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return res;
1271 }
1272 wasActive = true;
1273 break;
1274 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001275 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return INVALID_OPERATION;
1277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279
1280 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001281 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001282 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001283 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001284 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1285 }
Zhijun He5d677d12016-05-29 16:52:39 -07001286
Shuzhen Wang0129d522016-10-30 22:43:41 -07001287 if (consumers.size() == 0 && !hasDeferredConsumer) {
1288 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1289 return BAD_VALUE;
1290 }
Zhijun He5d677d12016-05-29 16:52:39 -07001291 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1292 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001293 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001294 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1295 return BAD_VALUE;
1296 }
1297
Shuzhen Wang0129d522016-10-30 22:43:41 -07001298 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001299 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1300 return BAD_VALUE;
1301 }
1302
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001303 // Use legacy dataspace values for older HALs
1304 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1305 dataSpace = mapToLegacyDataspace(dataSpace);
1306 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001307 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001308 ssize_t blobBufferSize;
1309 if (dataSpace != HAL_DATASPACE_DEPTH) {
1310 blobBufferSize = getJpegBufferSize(width, height);
1311 if (blobBufferSize <= 0) {
1312 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1313 return BAD_VALUE;
1314 }
1315 } else {
1316 blobBufferSize = getPointCloudBufferSize();
1317 if (blobBufferSize <= 0) {
1318 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1319 return BAD_VALUE;
1320 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001321 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001322 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001323 width, height, blobBufferSize, format, dataSpace, rotation,
1324 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001325 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1326 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1327 if (rawOpaqueBufferSize <= 0) {
1328 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1329 return BAD_VALUE;
1330 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001331 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001332 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1333 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001334 } else if (isShared) {
1335 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1336 width, height, format, consumerUsage, dataSpace, rotation,
1337 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001338 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001339 newStream = new Camera3OutputStream(mNextStreamId,
1340 width, height, format, consumerUsage, dataSpace, rotation,
1341 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001342 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001343 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001344 width, height, format, dataSpace, rotation,
1345 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001347 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348
Zhijun He125684a2015-12-26 15:07:30 -08001349 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001350 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1351 * requires buffers to be statically allocated for internal static buffer registration, while
1352 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1353 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001354 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001355 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001356 newStream->setBufferManager(mBufferManager);
1357 }
1358
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 res = mOutputStreams.add(mNextStreamId, newStream);
1360 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001361 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 return res;
1363 }
1364
1365 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001366 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367
1368 // Continue captures if active at start
1369 if (wasActive) {
1370 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1371 res = configureStreamsLocked();
1372 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001373 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1374 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 return res;
1376 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001377 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001379 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001381}
1382
1383status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1384 ATRACE_CALL();
1385 (void)outputId; (void)id;
1386
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001387 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001388 return INVALID_OPERATION;
1389}
1390
1391
1392status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001393 uint32_t *width, uint32_t *height,
1394 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001395 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001396 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001398
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 switch (mStatus) {
1400 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001401 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return INVALID_OPERATION;
1403 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001404 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001406 case STATUS_UNCONFIGURED:
1407 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 case STATUS_ACTIVE:
1409 // OK
1410 break;
1411 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001412 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001413 return INVALID_OPERATION;
1414 }
1415
1416 ssize_t idx = mOutputStreams.indexOfKey(id);
1417 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001418 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 return idx;
1420 }
1421
1422 if (width) *width = mOutputStreams[idx]->getWidth();
1423 if (height) *height = mOutputStreams[idx]->getHeight();
1424 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001425 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001427}
1428
1429status_t Camera3Device::setStreamTransform(int id,
1430 int transform) {
1431 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001432 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001434
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 switch (mStatus) {
1436 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001437 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 return INVALID_OPERATION;
1439 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001440 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001442 case STATUS_UNCONFIGURED:
1443 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001444 case STATUS_ACTIVE:
1445 // OK
1446 break;
1447 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001448 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 return INVALID_OPERATION;
1450 }
1451
1452 ssize_t idx = mOutputStreams.indexOfKey(id);
1453 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 CLOGE("Stream %d does not exist",
1455 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 return BAD_VALUE;
1457 }
1458
1459 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001460}
1461
1462status_t Camera3Device::deleteStream(int id) {
1463 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001464 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 Mutex::Autolock l(mLock);
1466 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001468 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001469
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 // CameraDevice semantics require device to already be idle before
1471 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001472 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001474 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 }
1476
Igor Murashkin2fba5842013-04-22 14:03:54 -07001477 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001478 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 if (mInputStream != NULL && id == mInputStream->getId()) {
1480 deletedStream = mInputStream;
1481 mInputStream.clear();
1482 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001483 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001484 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 return BAD_VALUE;
1486 }
Zhijun He5f446352014-01-22 09:49:33 -08001487 }
1488
1489 // Delete output stream or the output part of a bi-directional stream.
1490 if (outputStreamIdx != NAME_NOT_FOUND) {
1491 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 mOutputStreams.removeItem(id);
1493 }
1494
1495 // Free up the stream endpoint so that it can be used by some other stream
1496 res = deletedStream->disconnect();
1497 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 // fall through since we want to still list the stream as deleted.
1500 }
1501 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001502 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503
1504 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001505}
1506
1507status_t Camera3Device::deleteReprocessStream(int id) {
1508 ATRACE_CALL();
1509 (void)id;
1510
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001511 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001512 return INVALID_OPERATION;
1513}
1514
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001515status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001516 ATRACE_CALL();
1517 ALOGV("%s: E", __FUNCTION__);
1518
1519 Mutex::Autolock il(mInterfaceLock);
1520 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001521
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001522 bool isConstrainedHighSpeed =
1523 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
1524 operatingMode;
1525
1526 if (mOperatingMode != operatingMode) {
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001527 mNeedConfig = true;
1528 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001529 mOperatingMode = operatingMode;
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001530 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001531
1532 return configureStreamsLocked();
1533}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001534
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001535status_t Camera3Device::getInputBufferProducer(
1536 sp<IGraphicBufferProducer> *producer) {
1537 Mutex::Autolock il(mInterfaceLock);
1538 Mutex::Autolock l(mLock);
1539
1540 if (producer == NULL) {
1541 return BAD_VALUE;
1542 } else if (mInputStream == NULL) {
1543 return INVALID_OPERATION;
1544 }
1545
1546 return mInputStream->getInputBufferProducer(producer);
1547}
1548
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001549status_t Camera3Device::createDefaultRequest(int templateId,
1550 CameraMetadata *request) {
1551 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001552 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001553
1554 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1555 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1556 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1557 return BAD_VALUE;
1558 }
1559
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 Mutex::Autolock l(mLock);
1562
1563 switch (mStatus) {
1564 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001565 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 return INVALID_OPERATION;
1567 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001568 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 case STATUS_UNCONFIGURED:
1571 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 case STATUS_ACTIVE:
1573 // OK
1574 break;
1575 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001576 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 return INVALID_OPERATION;
1578 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001579
Zhijun Hea1530f12014-09-14 12:44:20 -07001580 if (!mRequestTemplateCache[templateId].isEmpty()) {
1581 *request = mRequestTemplateCache[templateId];
1582 return OK;
1583 }
1584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001585 camera_metadata_t *rawRequest;
1586 status_t res = mInterface->constructDefaultRequestSettings(
1587 (camera3_request_template_t) templateId, &rawRequest);
1588 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001589 ALOGI("%s: template %d is not supported on this camera device",
1590 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001591 return res;
1592 } else if (res != OK) {
1593 CLOGE("Unable to construct request template %d: %s (%d)",
1594 templateId, strerror(-res), res);
1595 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001596 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001598 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001600 // Derive some new keys for backward compatibility
1601 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1602 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1603 int32_t defaultBoost[1] = {100};
1604 mRequestTemplateCache[templateId].update(
1605 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1606 defaultBoost, 1);
1607 }
1608
1609 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610 return OK;
1611}
1612
1613status_t Camera3Device::waitUntilDrained() {
1614 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001615 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617
Zhijun He69a37482014-03-23 18:44:49 -07001618 return waitUntilDrainedLocked();
1619}
1620
1621status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001622 switch (mStatus) {
1623 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001624 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 ALOGV("%s: Already idle", __FUNCTION__);
1626 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 case STATUS_CONFIGURED:
1628 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 case STATUS_ERROR:
1630 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 break;
1633 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001634 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001635 return INVALID_OPERATION;
1636 }
1637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001638 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001640 if (res != OK) {
1641 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1642 res);
1643 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 return res;
1645}
1646
Ruben Brunk183f0562015-08-12 12:55:02 -07001647
1648void Camera3Device::internalUpdateStatusLocked(Status status) {
1649 mStatus = status;
1650 mRecentStatusUpdates.add(mStatus);
1651 mStatusChanged.broadcast();
1652}
1653
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001654// Pause to reconfigure
1655status_t Camera3Device::internalPauseAndWaitLocked() {
1656 mRequestThread->setPaused(true);
1657 mPauseStateNotify = true;
1658
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001659 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001660 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1661 if (res != OK) {
1662 SET_ERR_L("Can't idle device in %f seconds!",
1663 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001664 }
1665
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001666 return res;
1667}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001668
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001669// Resume after internalPauseAndWaitLocked
1670status_t Camera3Device::internalResumeLocked() {
1671 status_t res;
1672
1673 mRequestThread->setPaused(false);
1674
1675 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1676 if (res != OK) {
1677 SET_ERR_L("Can't transition to active in %f seconds!",
1678 kActiveTimeout/1e9);
1679 }
1680 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001681 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001682}
1683
Ruben Brunk183f0562015-08-12 12:55:02 -07001684status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001685 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001686
1687 size_t startIndex = 0;
1688 if (mStatusWaiters == 0) {
1689 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1690 // this status list
1691 mRecentStatusUpdates.clear();
1692 } else {
1693 // If other threads are waiting on updates to this status list, set the position of the
1694 // first element that this list will check rather than clearing the list.
1695 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001696 }
1697
Ruben Brunk183f0562015-08-12 12:55:02 -07001698 mStatusWaiters++;
1699
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001700 bool stateSeen = false;
1701 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001702 if (active == (mStatus == STATUS_ACTIVE)) {
1703 // Desired state is current
1704 break;
1705 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706
1707 res = mStatusChanged.waitRelative(mLock, timeout);
1708 if (res != OK) break;
1709
Ruben Brunk183f0562015-08-12 12:55:02 -07001710 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1711 // transitions.
1712 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1713 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1714 __FUNCTION__);
1715
1716 // Encountered desired state since we began waiting
1717 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001718 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1719 stateSeen = true;
1720 break;
1721 }
1722 }
1723 } while (!stateSeen);
1724
Ruben Brunk183f0562015-08-12 12:55:02 -07001725 mStatusWaiters--;
1726
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 return res;
1728}
1729
1730
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001731status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001733 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001735 if (listener != NULL && mListener != NULL) {
1736 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1737 }
1738 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001739 mRequestThread->setNotificationListener(listener);
1740 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001741
1742 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001745bool Camera3Device::willNotify3A() {
1746 return false;
1747}
1748
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001750 status_t res;
1751 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001753 while (mResultQueue.empty()) {
1754 res = mResultSignal.waitRelative(mOutputLock, timeout);
1755 if (res == TIMED_OUT) {
1756 return res;
1757 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001758 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1759 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001760 return res;
1761 }
1762 }
1763 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764}
1765
Jianing Weicb0652e2014-03-12 18:29:36 -07001766status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001768 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001770 if (mResultQueue.empty()) {
1771 return NOT_ENOUGH_DATA;
1772 }
1773
Jianing Weicb0652e2014-03-12 18:29:36 -07001774 if (frame == NULL) {
1775 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1776 return BAD_VALUE;
1777 }
1778
1779 CaptureResult &result = *(mResultQueue.begin());
1780 frame->mResultExtras = result.mResultExtras;
1781 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001782 mResultQueue.erase(mResultQueue.begin());
1783
1784 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785}
1786
1787status_t Camera3Device::triggerAutofocus(uint32_t id) {
1788 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001791 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1792 // Mix-in this trigger into the next request and only the next request.
1793 RequestTrigger trigger[] = {
1794 {
1795 ANDROID_CONTROL_AF_TRIGGER,
1796 ANDROID_CONTROL_AF_TRIGGER_START
1797 },
1798 {
1799 ANDROID_CONTROL_AF_TRIGGER_ID,
1800 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001801 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001802 };
1803
1804 return mRequestThread->queueTrigger(trigger,
1805 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806}
1807
1808status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1809 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001812 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1813 // Mix-in this trigger into the next request and only the next request.
1814 RequestTrigger trigger[] = {
1815 {
1816 ANDROID_CONTROL_AF_TRIGGER,
1817 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1818 },
1819 {
1820 ANDROID_CONTROL_AF_TRIGGER_ID,
1821 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001822 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001824
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001825 return mRequestThread->queueTrigger(trigger,
1826 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001827}
1828
1829status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1830 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001832
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001833 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1834 // Mix-in this trigger into the next request and only the next request.
1835 RequestTrigger trigger[] = {
1836 {
1837 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1838 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1839 },
1840 {
1841 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1842 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001843 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001844 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001845
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001846 return mRequestThread->queueTrigger(trigger,
1847 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001848}
1849
1850status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1851 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1852 ATRACE_CALL();
1853 (void)reprocessStreamId; (void)buffer; (void)listener;
1854
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001855 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001856 return INVALID_OPERATION;
1857}
1858
Jianing Weicb0652e2014-03-12 18:29:36 -07001859status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001860 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001861 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001863
Zhijun He7ef20392014-04-21 16:04:17 -07001864 {
1865 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001866 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001867 }
1868
Zhijun He491e3412013-12-27 10:57:44 -08001869 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001870 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001871 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001872 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001873 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001874 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001875 }
1876
1877 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001878}
1879
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001880status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001881 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1882}
1883
1884status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001885 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001886 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001887 Mutex::Autolock il(mInterfaceLock);
1888 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001889
1890 sp<Camera3StreamInterface> stream;
1891 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1892 if (outputStreamIdx == NAME_NOT_FOUND) {
1893 CLOGE("Stream %d does not exist", streamId);
1894 return BAD_VALUE;
1895 }
1896
1897 stream = mOutputStreams.editValueAt(outputStreamIdx);
1898
1899 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001900 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001901 return BAD_VALUE;
1902 }
1903
1904 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001905 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001906 return BAD_VALUE;
1907 }
1908
Ruben Brunkc78ac262015-08-13 17:58:46 -07001909 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001910}
1911
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001912status_t Camera3Device::tearDown(int streamId) {
1913 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001914 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001915 Mutex::Autolock il(mInterfaceLock);
1916 Mutex::Autolock l(mLock);
1917
1918 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1919 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001920 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001921 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001922 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001923 return NO_INIT;
1924 }
1925
1926 sp<Camera3StreamInterface> stream;
1927 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1928 if (outputStreamIdx == NAME_NOT_FOUND) {
1929 CLOGE("Stream %d does not exist", streamId);
1930 return BAD_VALUE;
1931 }
1932
1933 stream = mOutputStreams.editValueAt(outputStreamIdx);
1934
1935 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1936 CLOGE("Stream %d is a target of a in-progress request", streamId);
1937 return BAD_VALUE;
1938 }
1939
1940 return stream->tearDown();
1941}
1942
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001943status_t Camera3Device::addBufferListenerForStream(int streamId,
1944 wp<Camera3StreamBufferListener> listener) {
1945 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001946 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001947 Mutex::Autolock il(mInterfaceLock);
1948 Mutex::Autolock l(mLock);
1949
1950 sp<Camera3StreamInterface> stream;
1951 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1952 if (outputStreamIdx == NAME_NOT_FOUND) {
1953 CLOGE("Stream %d does not exist", streamId);
1954 return BAD_VALUE;
1955 }
1956
1957 stream = mOutputStreams.editValueAt(outputStreamIdx);
1958 stream->addBufferListener(listener);
1959
1960 return OK;
1961}
1962
Zhijun He204e3292014-07-14 17:09:23 -07001963uint32_t Camera3Device::getDeviceVersion() {
1964 ATRACE_CALL();
1965 Mutex::Autolock il(mInterfaceLock);
1966 return mDeviceVersion;
1967}
1968
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001969/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001970 * Methods called by subclasses
1971 */
1972
1973void Camera3Device::notifyStatus(bool idle) {
1974 {
1975 // Need mLock to safely update state and synchronize to current
1976 // state of methods in flight.
1977 Mutex::Autolock l(mLock);
1978 // We can get various system-idle notices from the status tracker
1979 // while starting up. Only care about them if we've actually sent
1980 // in some requests recently.
1981 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1982 return;
1983 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001984 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001985 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001986 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001987
1988 // Skip notifying listener if we're doing some user-transparent
1989 // state changes
1990 if (mPauseStateNotify) return;
1991 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001992
1993 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001994 {
1995 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001996 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001997 }
1998 if (idle && listener != NULL) {
1999 listener->notifyIdle();
2000 }
2001}
2002
Shuzhen Wang758c2152017-01-10 18:26:18 -08002003status_t Camera3Device::setConsumerSurfaces(int streamId,
2004 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07002005 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002006 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2007 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002008 Mutex::Autolock il(mInterfaceLock);
2009 Mutex::Autolock l(mLock);
2010
Shuzhen Wang758c2152017-01-10 18:26:18 -08002011 if (consumers.size() == 0) {
2012 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002013 return BAD_VALUE;
2014 }
2015
2016 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2017 if (idx == NAME_NOT_FOUND) {
2018 CLOGE("Stream %d is unknown", streamId);
2019 return idx;
2020 }
2021 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002022 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002023 if (res != OK) {
2024 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2025 return res;
2026 }
2027
Shuzhen Wang0129d522016-10-30 22:43:41 -07002028 if (stream->isConsumerConfigurationDeferred()) {
2029 if (!stream->isConfiguring()) {
2030 CLOGE("Stream %d was already fully configured.", streamId);
2031 return INVALID_OPERATION;
2032 }
Zhijun He5d677d12016-05-29 16:52:39 -07002033
Shuzhen Wang0129d522016-10-30 22:43:41 -07002034 res = stream->finishConfiguration();
2035 if (res != OK) {
2036 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2037 stream->getId(), strerror(-res), res);
2038 return res;
2039 }
Zhijun He5d677d12016-05-29 16:52:39 -07002040 }
2041
2042 return OK;
2043}
2044
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002045/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046 * Camera3Device private methods
2047 */
2048
2049sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002050 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 ATRACE_CALL();
2052 status_t res;
2053
2054 sp<CaptureRequest> newRequest = new CaptureRequest;
2055 newRequest->mSettings = request;
2056
2057 camera_metadata_entry_t inputStreams =
2058 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2059 if (inputStreams.count > 0) {
2060 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002061 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002062 CLOGE("Request references unknown input stream %d",
2063 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 return NULL;
2065 }
2066 // Lazy completion of stream configuration (allocation/registration)
2067 // on first use
2068 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002069 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002070 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002071 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002073 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074 return NULL;
2075 }
2076 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002077 // Check if stream is being prepared
2078 if (mInputStream->isPreparing()) {
2079 CLOGE("Request references an input stream that's being prepared!");
2080 return NULL;
2081 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002082
2083 newRequest->mInputStream = mInputStream;
2084 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2085 }
2086
2087 camera_metadata_entry_t streams =
2088 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2089 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002090 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002091 return NULL;
2092 }
2093
2094 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002095 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002097 CLOGE("Request references unknown stream %d",
2098 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002099 return NULL;
2100 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002101 sp<Camera3OutputStreamInterface> stream =
2102 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103
Zhijun He5d677d12016-05-29 16:52:39 -07002104 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002105 auto iter = surfaceMap.find(streams.data.i32[i]);
2106 if (iter != surfaceMap.end()) {
2107 const std::vector<size_t>& surfaces = iter->second;
2108 for (const auto& surface : surfaces) {
2109 if (stream->isConsumerConfigurationDeferred(surface)) {
2110 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2111 "due to deferred consumer", stream->getId(), surface);
2112 return NULL;
2113 }
2114 }
2115 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002116 }
2117
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002118 // Lazy completion of stream configuration (allocation/registration)
2119 // on first use
2120 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002121 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002123 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2124 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 return NULL;
2126 }
2127 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002128 // Check if stream is being prepared
2129 if (stream->isPreparing()) {
2130 CLOGE("Request references an output stream that's being prepared!");
2131 return NULL;
2132 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133
2134 newRequest->mOutputStreams.push(stream);
2135 }
2136 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002137 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
2139 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002140}
2141
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002142bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2143 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2144 Size size = mSupportedOpaqueInputSizes[i];
2145 if (size.width == width && size.height == height) {
2146 return true;
2147 }
2148 }
2149
2150 return false;
2151}
2152
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002153void Camera3Device::cancelStreamsConfigurationLocked() {
2154 int res = OK;
2155 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2156 res = mInputStream->cancelConfiguration();
2157 if (res != OK) {
2158 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2159 mInputStream->getId(), strerror(-res), res);
2160 }
2161 }
2162
2163 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2164 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2165 if (outputStream->isConfiguring()) {
2166 res = outputStream->cancelConfiguration();
2167 if (res != OK) {
2168 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2169 outputStream->getId(), strerror(-res), res);
2170 }
2171 }
2172 }
2173
2174 // Return state to that at start of call, so that future configures
2175 // properly clean things up
2176 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2177 mNeedConfig = true;
2178}
2179
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002180status_t Camera3Device::configureStreamsLocked() {
2181 ATRACE_CALL();
2182 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002183
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002184 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002185 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002186 return INVALID_OPERATION;
2187 }
2188
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002189 if (!mNeedConfig) {
2190 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2191 return OK;
2192 }
2193
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002194 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2195 // adding a dummy stream instead.
2196 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2197 if (mOutputStreams.size() == 0) {
2198 addDummyStreamLocked();
2199 } else {
2200 tryRemoveDummyStreamLocked();
2201 }
2202
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002203 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002204 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205
2206 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002207 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002208 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2209
2210 Vector<camera3_stream_t*> streams;
2211 streams.setCapacity(config.num_streams);
2212
2213 if (mInputStream != NULL) {
2214 camera3_stream_t *inputStream;
2215 inputStream = mInputStream->startConfiguration();
2216 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002217 CLOGE("Can't start input stream configuration");
2218 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002219 return INVALID_OPERATION;
2220 }
2221 streams.add(inputStream);
2222 }
2223
2224 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002225
2226 // Don't configure bidi streams twice, nor add them twice to the list
2227 if (mOutputStreams[i].get() ==
2228 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2229
2230 config.num_streams--;
2231 continue;
2232 }
2233
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 camera3_stream_t *outputStream;
2235 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2236 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002237 CLOGE("Can't start output stream configuration");
2238 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 return INVALID_OPERATION;
2240 }
2241 streams.add(outputStream);
2242 }
2243
2244 config.streams = streams.editArray();
2245
2246 // Do the HAL configuration; will potentially touch stream
2247 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002248
2249 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002250
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002251 if (res == BAD_VALUE) {
2252 // HAL rejected this set of streams as unsupported, clean up config
2253 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002254 CLOGE("Set of requested inputs/outputs not supported by HAL");
2255 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002256 return BAD_VALUE;
2257 } else if (res != OK) {
2258 // Some other kind of error from configure_streams - this is not
2259 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002260 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2261 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 return res;
2263 }
2264
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002265 // Finish all stream configuration immediately.
2266 // TODO: Try to relax this later back to lazy completion, which should be
2267 // faster
2268
Igor Murashkin073f8572013-05-02 14:59:28 -07002269 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002270 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002271 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002272 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002273 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002274 cancelStreamsConfigurationLocked();
2275 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002276 }
2277 }
2278
2279 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002280 sp<Camera3OutputStreamInterface> outputStream =
2281 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002282 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002283 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002284 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002285 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002286 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002287 cancelStreamsConfigurationLocked();
2288 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002289 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002290 }
2291 }
2292
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293 // Request thread needs to know to avoid using repeat-last-settings protocol
2294 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002295 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296
Zhijun He90f7c372016-08-16 16:19:43 -07002297 char value[PROPERTY_VALUE_MAX];
2298 property_get("camera.fifo.disable", value, "0");
2299 int32_t disableFifo = atoi(value);
2300 if (disableFifo != 1) {
2301 // Boost priority of request thread to SCHED_FIFO.
2302 pid_t requestThreadTid = mRequestThread->getTid();
2303 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002304 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002305 if (res != OK) {
2306 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2307 strerror(-res), res);
2308 } else {
2309 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2310 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002311 }
2312
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002313 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002314
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002315 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316
Ruben Brunk183f0562015-08-12 12:55:02 -07002317 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2318 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002319
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002320 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002321
Zhijun He0a210512014-07-24 13:45:15 -07002322 // tear down the deleted streams after configure streams.
2323 mDeletedStreams.clear();
2324
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002326}
2327
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002328status_t Camera3Device::addDummyStreamLocked() {
2329 ATRACE_CALL();
2330 status_t res;
2331
2332 if (mDummyStreamId != NO_STREAM) {
2333 // Should never be adding a second dummy stream when one is already
2334 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002335 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2336 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002337 return INVALID_OPERATION;
2338 }
2339
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002340 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002341
2342 sp<Camera3OutputStreamInterface> dummyStream =
2343 new Camera3DummyStream(mNextStreamId);
2344
2345 res = mOutputStreams.add(mNextStreamId, dummyStream);
2346 if (res < 0) {
2347 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2348 return res;
2349 }
2350
2351 mDummyStreamId = mNextStreamId;
2352 mNextStreamId++;
2353
2354 return OK;
2355}
2356
2357status_t Camera3Device::tryRemoveDummyStreamLocked() {
2358 ATRACE_CALL();
2359 status_t res;
2360
2361 if (mDummyStreamId == NO_STREAM) return OK;
2362 if (mOutputStreams.size() == 1) return OK;
2363
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002364 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002365
2366 // Ok, have a dummy stream and there's at least one other output stream,
2367 // so remove the dummy
2368
2369 sp<Camera3StreamInterface> deletedStream;
2370 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2371 if (outputStreamIdx == NAME_NOT_FOUND) {
2372 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2373 return INVALID_OPERATION;
2374 }
2375
2376 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2377 mOutputStreams.removeItemsAt(outputStreamIdx);
2378
2379 // Free up the stream endpoint so that it can be used by some other stream
2380 res = deletedStream->disconnect();
2381 if (res != OK) {
2382 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2383 // fall through since we want to still list the stream as deleted.
2384 }
2385 mDeletedStreams.add(deletedStream);
2386 mDummyStreamId = NO_STREAM;
2387
2388 return res;
2389}
2390
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002391void Camera3Device::setErrorState(const char *fmt, ...) {
2392 Mutex::Autolock l(mLock);
2393 va_list args;
2394 va_start(args, fmt);
2395
2396 setErrorStateLockedV(fmt, args);
2397
2398 va_end(args);
2399}
2400
2401void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2402 Mutex::Autolock l(mLock);
2403 setErrorStateLockedV(fmt, args);
2404}
2405
2406void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2407 va_list args;
2408 va_start(args, fmt);
2409
2410 setErrorStateLockedV(fmt, args);
2411
2412 va_end(args);
2413}
2414
2415void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002416 // Print out all error messages to log
2417 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002418 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002419
2420 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002421 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002422
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002423 mErrorCause = errorCause;
2424
2425 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002426 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002427
2428 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002429 sp<NotificationListener> listener = mListener.promote();
2430 if (listener != NULL) {
2431 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002432 CaptureResultExtras());
2433 }
2434
2435 // Save stack trace. View by dumping it later.
2436 CameraTraces::saveTrace();
2437 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002438}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002439
2440/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002441 * In-flight request management
2442 */
2443
Jianing Weicb0652e2014-03-12 18:29:36 -07002444status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002445 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2446 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002447 ATRACE_CALL();
2448 Mutex::Autolock l(mInFlightLock);
2449
2450 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002451 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2452 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002453 if (res < 0) return res;
2454
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002455 if (mInFlightMap.size() == 1) {
2456 mStatusTracker->markComponentActive(mInFlightStatusId);
2457 }
2458
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002459 return OK;
2460}
2461
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002462void Camera3Device::returnOutputBuffers(
2463 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2464 nsecs_t timestamp) {
2465 for (size_t i = 0; i < numBuffers; i++)
2466 {
2467 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2468 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2469 // Note: stream may be deallocated at this point, if this buffer was
2470 // the last reference to it.
2471 if (res != OK) {
2472 ALOGE("Can't return buffer to its stream: %s (%d)",
2473 strerror(-res), res);
2474 }
2475 }
2476}
2477
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002478void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2479 mInFlightMap.removeItemsAt(idx, 1);
2480
2481 // Indicate idle inFlightMap to the status tracker
2482 if (mInFlightMap.size() == 0) {
2483 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2484 }
2485}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002486
2487void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2488
2489 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2490 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2491
2492 nsecs_t sensorTimestamp = request.sensorTimestamp;
2493 nsecs_t shutterTimestamp = request.shutterTimestamp;
2494
2495 // Check if it's okay to remove the request from InFlightMap:
2496 // In the case of a successful request:
2497 // all input and output buffers, all result metadata, shutter callback
2498 // arrived.
2499 // In the case of a unsuccessful request:
2500 // all input and output buffers arrived.
2501 if (request.numBuffersLeft == 0 &&
2502 (request.requestStatus != OK ||
2503 (request.haveResultMetadata && shutterTimestamp != 0))) {
2504 ATRACE_ASYNC_END("frame capture", frameNumber);
2505
2506 // Sanity check - if sensor timestamp matches shutter timestamp
2507 if (request.requestStatus == OK &&
2508 sensorTimestamp != shutterTimestamp) {
2509 SET_ERR("sensor timestamp (%" PRId64
2510 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2511 sensorTimestamp, frameNumber, shutterTimestamp);
2512 }
2513
2514 // for an unsuccessful request, it may have pending output buffers to
2515 // return.
2516 assert(request.requestStatus != OK ||
2517 request.pendingOutputBuffers.size() == 0);
2518 returnOutputBuffers(request.pendingOutputBuffers.array(),
2519 request.pendingOutputBuffers.size(), 0);
2520
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002521 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002522 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2523 }
2524
2525 // Sanity check - if we have too many in-flight frames, something has
2526 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002527 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002528 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002529 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2530 kInFlightWarnLimitHighSpeed) {
2531 CLOGE("In-flight list too large for high speed configuration: %zu",
2532 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002533 }
2534}
2535
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002536void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2537 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2538 if (result == nullptr) return;
2539
2540 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2541 (int32_t*)&frameNumber, 1) != OK) {
2542 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2543 return;
2544 }
2545
2546 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2547 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2548 return;
2549 }
2550
2551 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2552
2553 // Valid result, insert into queue
2554 List<CaptureResult>::iterator queuedResult =
2555 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2556 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2557 ", burstId = %" PRId32, __FUNCTION__,
2558 queuedResult->mResultExtras.requestId,
2559 queuedResult->mResultExtras.frameNumber,
2560 queuedResult->mResultExtras.burstId);
2561
2562 mResultSignal.signal();
2563}
2564
2565
2566void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2567 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2568 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2569 Mutex::Autolock l(mOutputLock);
2570
2571 CaptureResult captureResult;
2572 captureResult.mResultExtras = resultExtras;
2573 captureResult.mMetadata = partialResult;
2574
2575 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2576}
2577
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002578
2579void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2580 CaptureResultExtras &resultExtras,
2581 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002582 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002583 bool reprocess,
2584 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002585 if (pendingMetadata.isEmpty())
2586 return;
2587
2588 Mutex::Autolock l(mOutputLock);
2589
2590 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002591 if (reprocess) {
2592 if (frameNumber < mNextReprocessResultFrameNumber) {
2593 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002594 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002595 frameNumber, mNextReprocessResultFrameNumber);
2596 return;
2597 }
2598 mNextReprocessResultFrameNumber = frameNumber + 1;
2599 } else {
2600 if (frameNumber < mNextResultFrameNumber) {
2601 SET_ERR("Out-of-order capture result metadata submitted! "
2602 "(got frame number %d, expecting %d)",
2603 frameNumber, mNextResultFrameNumber);
2604 return;
2605 }
2606 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002607 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002608
2609 CaptureResult captureResult;
2610 captureResult.mResultExtras = resultExtras;
2611 captureResult.mMetadata = pendingMetadata;
2612
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002613 // Append any previous partials to form a complete result
2614 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2615 captureResult.mMetadata.append(collectedPartialResult);
2616 }
2617
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002618 // Derive some new keys for backward compaibility
2619 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2620 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2621 int32_t defaultBoost[1] = {100};
2622 captureResult.mMetadata.update(
2623 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2624 defaultBoost, 1);
2625 }
2626
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002627 captureResult.mMetadata.sort();
2628
2629 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002630 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2631 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002632 SET_ERR("No timestamp provided by HAL for frame %d!",
2633 frameNumber);
2634 return;
2635 }
2636
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002637 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2638 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2639
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002640 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002641}
2642
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002643/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644 * Camera HAL device callback methods
2645 */
2646
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002647void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002648 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002649
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002650 status_t res;
2651
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002652 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002653 if (result->result == NULL && result->num_output_buffers == 0 &&
2654 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002655 SET_ERR("No result data provided by HAL for frame %d",
2656 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002657 return;
2658 }
Zhijun He204e3292014-07-14 17:09:23 -07002659
2660 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2661 // partial_result to 1 when metadata is included in this result.
2662 if (!mUsePartialResult &&
2663 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2664 result->result != NULL &&
2665 result->partial_result != 1) {
2666 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2667 " if partial result is not supported",
2668 frameNumber, result->partial_result);
2669 return;
2670 }
2671
2672 bool isPartialResult = false;
2673 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002674 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002675 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002676
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002677 // Get shutter timestamp and resultExtras from list of in-flight requests,
2678 // where it was added by the shutter notification for this frame. If the
2679 // shutter timestamp isn't received yet, append the output buffers to the
2680 // in-flight request and they will be returned when the shutter timestamp
2681 // arrives. Update the in-flight status and remove the in-flight entry if
2682 // all result data and shutter timestamp have been received.
2683 nsecs_t shutterTimestamp = 0;
2684
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002685 {
2686 Mutex::Autolock l(mInFlightLock);
2687 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2688 if (idx == NAME_NOT_FOUND) {
2689 SET_ERR("Unknown frame number for capture result: %d",
2690 frameNumber);
2691 return;
2692 }
2693 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002694 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2695 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2696 ", partialResultCount = %d",
2697 __FUNCTION__, request.resultExtras.requestId,
2698 request.resultExtras.frameNumber, request.resultExtras.burstId,
2699 result->partial_result);
2700 // Always update the partial count to the latest one if it's not 0
2701 // (buffers only). When framework aggregates adjacent partial results
2702 // into one, the latest partial count will be used.
2703 if (result->partial_result != 0)
2704 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002705
2706 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002707 if (mUsePartialResult && result->result != NULL) {
2708 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2709 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2710 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2711 " the range of [1, %d] when metadata is included in the result",
2712 frameNumber, result->partial_result, mNumPartialResults);
2713 return;
2714 }
2715 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002716 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002717 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002718 }
Zhijun He204e3292014-07-14 17:09:23 -07002719 } else {
2720 camera_metadata_ro_entry_t partialResultEntry;
2721 res = find_camera_metadata_ro_entry(result->result,
2722 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2723 if (res != NAME_NOT_FOUND &&
2724 partialResultEntry.count > 0 &&
2725 partialResultEntry.data.u8[0] ==
2726 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2727 // A partial result. Flag this as such, and collect this
2728 // set of metadata into the in-flight entry.
2729 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002730 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002731 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002732 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002733 ANDROID_QUIRKS_PARTIAL_RESULT);
2734 }
2735 }
2736
2737 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002738 // Send partial capture result
2739 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2740 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002741 }
2742 }
2743
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002744 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002745 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002746
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002747 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002748 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002749 if (request.haveResultMetadata) {
2750 SET_ERR("Called multiple times with metadata for frame %d",
2751 frameNumber);
2752 return;
2753 }
Zhijun He204e3292014-07-14 17:09:23 -07002754 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002755 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002756 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002757 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002758 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002759 request.haveResultMetadata = true;
2760 }
2761
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002762 uint32_t numBuffersReturned = result->num_output_buffers;
2763 if (result->input_buffer != NULL) {
2764 if (hasInputBufferInRequest) {
2765 numBuffersReturned += 1;
2766 } else {
2767 ALOGW("%s: Input buffer should be NULL if there is no input"
2768 " buffer sent in the request",
2769 __FUNCTION__);
2770 }
2771 }
2772 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002773 if (request.numBuffersLeft < 0) {
2774 SET_ERR("Too many buffers returned for frame %d",
2775 frameNumber);
2776 return;
2777 }
2778
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002779 camera_metadata_ro_entry_t entry;
2780 res = find_camera_metadata_ro_entry(result->result,
2781 ANDROID_SENSOR_TIMESTAMP, &entry);
2782 if (res == OK && entry.count == 1) {
2783 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002784 }
2785
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002786 // If shutter event isn't received yet, append the output buffers to
2787 // the in-flight request. Otherwise, return the output buffers to
2788 // streams.
2789 if (shutterTimestamp == 0) {
2790 request.pendingOutputBuffers.appendArray(result->output_buffers,
2791 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002792 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002793 returnOutputBuffers(result->output_buffers,
2794 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002795 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002796
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002797 if (result->result != NULL && !isPartialResult) {
2798 if (shutterTimestamp == 0) {
2799 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002800 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002801 } else {
2802 CameraMetadata metadata;
2803 metadata = result->result;
2804 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002805 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2806 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002807 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002808 }
2809
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002810 removeInFlightRequestIfReadyLocked(idx);
2811 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002812
Zhijun Hef0d962a2014-06-30 10:24:11 -07002813 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002814 if (hasInputBufferInRequest) {
2815 Camera3Stream *stream =
2816 Camera3Stream::cast(result->input_buffer->stream);
2817 res = stream->returnInputBuffer(*(result->input_buffer));
2818 // Note: stream may be deallocated at this point, if this buffer was the
2819 // last reference to it.
2820 if (res != OK) {
2821 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2822 " its stream:%s (%d)", __FUNCTION__,
2823 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002824 }
2825 } else {
2826 ALOGW("%s: Input buffer should be NULL if there is no input"
2827 " buffer sent in the request, skipping input buffer return.",
2828 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002829 }
2830 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002831}
2832
2833void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002834 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002835 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002836 {
2837 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002838 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002839 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002840
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002841 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002842 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002843 return;
2844 }
2845
2846 switch (msg->type) {
2847 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002849 break;
2850 }
2851 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002852 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002853 break;
2854 }
2855 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002856 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002857 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002858 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002859}
2860
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002861void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002862 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002863
2864 // Map camera HAL error codes to ICameraDeviceCallback error codes
2865 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002866 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002867 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002868 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002870 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002871 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002872 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002873 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002874 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002875 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002876 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002877 };
2878
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002879 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 ((msg.error_code >= 0) &&
2881 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2882 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002883 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002884
2885 int streamId = 0;
2886 if (msg.error_stream != NULL) {
2887 Camera3Stream *stream =
2888 Camera3Stream::cast(msg.error_stream);
2889 streamId = stream->getId();
2890 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002891 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2892 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002893 streamId, msg.error_code);
2894
2895 CaptureResultExtras resultExtras;
2896 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002897 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002898 // SET_ERR calls notifyError
2899 SET_ERR("Camera HAL reported serious device error");
2900 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2902 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2903 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002904 {
2905 Mutex::Autolock l(mInFlightLock);
2906 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2907 if (idx >= 0) {
2908 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2909 r.requestStatus = msg.error_code;
2910 resultExtras = r.resultExtras;
2911 } else {
2912 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002913 ALOGE("Camera %s: %s: cannot find in-flight request on "
2914 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002915 resultExtras.frameNumber);
2916 }
2917 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002918 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002919 if (listener != NULL) {
2920 listener->notifyError(errorCode, resultExtras);
2921 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002923 }
2924 break;
2925 default:
2926 // SET_ERR calls notifyError
2927 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2928 break;
2929 }
2930}
2931
2932void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002933 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002934 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002935
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002936 // Set timestamp for the request in the in-flight tracking
2937 // and get the request ID to send upstream
2938 {
2939 Mutex::Autolock l(mInFlightLock);
2940 idx = mInFlightMap.indexOfKey(msg.frame_number);
2941 if (idx >= 0) {
2942 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002943
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002944 // Verify ordering of shutter notifications
2945 {
2946 Mutex::Autolock l(mOutputLock);
2947 // TODO: need to track errors for tighter bounds on expected frame number.
2948 if (r.hasInputBuffer) {
2949 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2950 SET_ERR("Shutter notification out-of-order. Expected "
2951 "notification for frame %d, got frame %d",
2952 mNextReprocessShutterFrameNumber, msg.frame_number);
2953 return;
2954 }
2955 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2956 } else {
2957 if (msg.frame_number < mNextShutterFrameNumber) {
2958 SET_ERR("Shutter notification out-of-order. Expected "
2959 "notification for frame %d, got frame %d",
2960 mNextShutterFrameNumber, msg.frame_number);
2961 return;
2962 }
2963 mNextShutterFrameNumber = msg.frame_number + 1;
2964 }
2965 }
2966
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002967 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
2968 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002969 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
2970 // Call listener, if any
2971 if (listener != NULL) {
2972 listener->notifyShutter(r.resultExtras, msg.timestamp);
2973 }
2974
2975 r.shutterTimestamp = msg.timestamp;
2976
2977 // send pending result and buffers
2978 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002979 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002980 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002981 returnOutputBuffers(r.pendingOutputBuffers.array(),
2982 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2983 r.pendingOutputBuffers.clear();
2984
2985 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002986 }
2987 }
2988 if (idx < 0) {
2989 SET_ERR("Shutter notification for non-existent frame number %d",
2990 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002991 }
2992}
2993
2994
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002995CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002996 ALOGV("%s", __FUNCTION__);
2997
Igor Murashkin1e479c02013-09-06 16:55:14 -07002998 CameraMetadata retVal;
2999
3000 if (mRequestThread != NULL) {
3001 retVal = mRequestThread->getLatestRequest();
3002 }
3003
Igor Murashkin1e479c02013-09-06 16:55:14 -07003004 return retVal;
3005}
3006
Jianing Weicb0652e2014-03-12 18:29:36 -07003007
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003008void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3009 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3010 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3011}
3012
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003013/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003014 * HalInterface inner class methods
3015 */
3016
3017Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3018 mHal3Device(device) {}
3019
3020Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3021 mHal3Device(nullptr),
3022 mHidlSession(session) {}
3023
3024Camera3Device::HalInterface::HalInterface() :
3025 mHal3Device(nullptr) {}
3026
3027Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3028 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3029
3030bool Camera3Device::HalInterface::valid() {
3031 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3032}
3033
3034void Camera3Device::HalInterface::clear() {
3035 mHal3Device = nullptr;
3036 mHidlSession.clear();
3037}
3038
3039status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3040 camera3_request_template_t templateId,
3041 /*out*/ camera_metadata_t **requestTemplate) {
3042 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3043 if (!valid()) return INVALID_OPERATION;
3044 status_t res = OK;
3045
3046 if (mHal3Device != nullptr) {
3047 const camera_metadata *r;
3048 r = mHal3Device->ops->construct_default_request_settings(
3049 mHal3Device, templateId);
3050 if (r == nullptr) return BAD_VALUE;
3051 *requestTemplate = clone_camera_metadata(r);
3052 if (requestTemplate == nullptr) {
3053 ALOGE("%s: Unable to clone camera metadata received from HAL",
3054 __FUNCTION__);
3055 return INVALID_OPERATION;
3056 }
3057 } else {
3058 common::V1_0::Status status;
3059 RequestTemplate id;
3060 switch (templateId) {
3061 case CAMERA3_TEMPLATE_PREVIEW:
3062 id = RequestTemplate::PREVIEW;
3063 break;
3064 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3065 id = RequestTemplate::STILL_CAPTURE;
3066 break;
3067 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3068 id = RequestTemplate::VIDEO_RECORD;
3069 break;
3070 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3071 id = RequestTemplate::VIDEO_SNAPSHOT;
3072 break;
3073 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3074 id = RequestTemplate::ZERO_SHUTTER_LAG;
3075 break;
3076 case CAMERA3_TEMPLATE_MANUAL:
3077 id = RequestTemplate::MANUAL;
3078 break;
3079 default:
3080 // Unknown template ID
3081 return BAD_VALUE;
3082 }
3083 mHidlSession->constructDefaultRequestSettings(id,
3084 [&status, &requestTemplate]
3085 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3086 status = s;
3087 if (status == common::V1_0::Status::OK) {
3088 const camera_metadata *r =
3089 reinterpret_cast<const camera_metadata_t*>(request.data());
3090 size_t expectedSize = request.size();
3091 int ret = validate_camera_metadata_structure(r, &expectedSize);
3092 if (ret == OK) {
3093 *requestTemplate = clone_camera_metadata(r);
3094 if (*requestTemplate == nullptr) {
3095 ALOGE("%s: Unable to clone camera metadata received from HAL",
3096 __FUNCTION__);
3097 status = common::V1_0::Status::INTERNAL_ERROR;
3098 }
3099 } else {
3100 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3101 status = common::V1_0::Status::INTERNAL_ERROR;
3102 }
3103 }
3104 });
3105 res = CameraProviderManager::mapToStatusT(status);
3106 }
3107 return res;
3108}
3109
3110status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3111 ATRACE_NAME("CameraHal::configureStreams");
3112 if (!valid()) return INVALID_OPERATION;
3113 status_t res = OK;
3114
3115 if (mHal3Device != nullptr) {
3116 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3117 } else {
3118 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003119 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120 StreamConfiguration requestedConfiguration;
3121 requestedConfiguration.streams.resize(config->num_streams);
3122 for (size_t i = 0; i < config->num_streams; i++) {
3123 Stream &dst = requestedConfiguration.streams[i];
3124 camera3_stream_t *src = config->streams[i];
3125
3126 int streamId = Camera3Stream::cast(src)->getId();
3127 StreamType streamType;
3128 switch (src->stream_type) {
3129 case CAMERA3_STREAM_OUTPUT:
3130 streamType = StreamType::OUTPUT;
3131 break;
3132 case CAMERA3_STREAM_INPUT:
3133 streamType = StreamType::INPUT;
3134 break;
3135 default:
3136 ALOGE("%s: Stream %d: Unsupported stream type %d",
3137 __FUNCTION__, streamId, config->streams[i]->stream_type);
3138 return BAD_VALUE;
3139 }
3140 dst.id = streamId;
3141 dst.streamType = streamType;
3142 dst.width = src->width;
3143 dst.height = src->height;
3144 dst.format = mapToPixelFormat(src->format);
3145 dst.usage = mapToConsumerUsage(src->usage);
3146 dst.dataSpace = mapToHidlDataspace(src->data_space);
3147 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003148
3149 activeStreams.insert(streamId);
3150 // Create Buffer ID map if necessary
3151 if (mBufferIdMaps.count(streamId) == 0) {
3152 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3153 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003154 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003155 // remove BufferIdMap for deleted streams
3156 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3157 int streamId = it->first;
3158 bool active = activeStreams.count(streamId) > 0;
3159 if (!active) {
3160 it = mBufferIdMaps.erase(it);
3161 } else {
3162 ++it;
3163 }
3164 }
3165
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003166 res = mapToStreamConfigurationMode(
3167 (camera3_stream_configuration_mode_t) config->operation_mode,
3168 /*out*/ &requestedConfiguration.operationMode);
3169 if (res != OK) {
3170 return res;
3171 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003172
3173 // Invoke configureStreams
3174
3175 HalStreamConfiguration finalConfiguration;
3176 common::V1_0::Status status;
3177 mHidlSession->configureStreams(requestedConfiguration,
3178 [&status, &finalConfiguration]
3179 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3180 finalConfiguration = halConfiguration;
3181 status = s;
3182 });
3183 if (status != common::V1_0::Status::OK ) {
3184 return CameraProviderManager::mapToStatusT(status);
3185 }
3186
3187 // And convert output stream configuration from HIDL
3188
3189 for (size_t i = 0; i < config->num_streams; i++) {
3190 camera3_stream_t *dst = config->streams[i];
3191 int streamId = Camera3Stream::cast(dst)->getId();
3192
3193 // Start scan at i, with the assumption that the stream order matches
3194 size_t realIdx = i;
3195 bool found = false;
3196 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3197 if (finalConfiguration.streams[realIdx].id == streamId) {
3198 found = true;
3199 break;
3200 }
3201 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3202 }
3203 if (!found) {
3204 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3205 __FUNCTION__, streamId);
3206 return INVALID_OPERATION;
3207 }
3208 HalStream &src = finalConfiguration.streams[realIdx];
3209
3210 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3211 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3212 if (dst->format != overrideFormat) {
3213 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3214 streamId, dst->format);
3215 }
3216 } else {
3217 // Override allowed with IMPLEMENTATION_DEFINED
3218 dst->format = overrideFormat;
3219 }
3220
3221 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3222 if (src.producerUsage != 0) {
3223 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3224 __FUNCTION__, streamId);
3225 return INVALID_OPERATION;
3226 }
3227 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3228 } else {
3229 // OUTPUT
3230 if (src.consumerUsage != 0) {
3231 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3232 __FUNCTION__, streamId);
3233 return INVALID_OPERATION;
3234 }
3235 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3236 }
3237 dst->max_buffers = src.maxBuffers;
3238 }
3239 }
3240 return res;
3241}
3242
3243status_t Camera3Device::HalInterface::processCaptureRequest(
3244 camera3_capture_request_t *request) {
3245 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003246 if (!valid()) return INVALID_OPERATION;
3247 status_t res = OK;
3248
3249 if (mHal3Device != nullptr) {
3250 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3251 } else {
3252 device::V3_2::CaptureRequest captureRequest;
3253 captureRequest.frameNumber = request->frame_number;
3254 std::vector<native_handle_t*> handlesCreated;
3255 // A null request settings maps to a size-0 CameraMetadata
3256 if (request->settings != nullptr) {
3257 captureRequest.settings.setToExternal(
3258 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3259 get_camera_metadata_size(request->settings));
3260 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003261
3262 {
3263 std::lock_guard<std::mutex> lock(mInflightLock);
3264 if (request->input_buffer != nullptr) {
3265 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003266 buffer_handle_t buf = *(request->input_buffer->buffer);
3267 auto pair = getBufferId(buf, streamId);
3268 bool isNewBuffer = pair.first;
3269 uint64_t bufferId = pair.second;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003270 captureRequest.inputBuffer.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003271 captureRequest.inputBuffer.bufferId = bufferId;
3272 captureRequest.inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003273 captureRequest.inputBuffer.status = BufferStatus::OK;
3274 native_handle_t *acquireFence = nullptr;
3275 if (request->input_buffer->acquire_fence != -1) {
3276 acquireFence = native_handle_create(1,0);
3277 acquireFence->data[0] = request->input_buffer->acquire_fence;
3278 handlesCreated.push_back(acquireFence);
3279 }
3280 captureRequest.inputBuffer.acquireFence = acquireFence;
3281 captureRequest.inputBuffer.releaseFence = nullptr;
3282
3283 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003284 request->input_buffer->buffer,
3285 request->input_buffer->acquire_fence);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003286 } else {
3287 captureRequest.inputBuffer.streamId = -1;
3288 captureRequest.inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003289 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003290
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003291 captureRequest.outputBuffers.resize(request->num_output_buffers);
3292 for (size_t i = 0; i < request->num_output_buffers; i++) {
3293 const camera3_stream_buffer_t *src = request->output_buffers + i;
3294 StreamBuffer &dst = captureRequest.outputBuffers[i];
3295 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003296 buffer_handle_t buf = *(src->buffer);
3297 auto pair = getBufferId(buf, streamId);
3298 bool isNewBuffer = pair.first;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003299 dst.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003300 dst.bufferId = pair.second;
3301 dst.buffer = isNewBuffer ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003302 dst.status = BufferStatus::OK;
3303 native_handle_t *acquireFence = nullptr;
3304 if (src->acquire_fence != -1) {
3305 acquireFence = native_handle_create(1,0);
3306 acquireFence->data[0] = src->acquire_fence;
3307 handlesCreated.push_back(acquireFence);
3308 }
3309 dst.acquireFence = acquireFence;
3310 dst.releaseFence = nullptr;
3311
3312 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003313 src->buffer, src->acquire_fence);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003314 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003315 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003316 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3317
3318 for (auto& handle : handlesCreated) {
3319 native_handle_delete(handle);
3320 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003321 res = CameraProviderManager::mapToStatusT(status);
3322 }
3323 return res;
3324}
3325
3326status_t Camera3Device::HalInterface::flush() {
3327 ATRACE_NAME("CameraHal::flush");
3328 if (!valid()) return INVALID_OPERATION;
3329 status_t res = OK;
3330
3331 if (mHal3Device != nullptr) {
3332 res = mHal3Device->ops->flush(mHal3Device);
3333 } else {
3334 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3335 }
3336 return res;
3337}
3338
3339status_t Camera3Device::HalInterface::dump(int fd) {
3340 ATRACE_NAME("CameraHal::dump");
3341 if (!valid()) return INVALID_OPERATION;
3342 status_t res = OK;
3343
3344 if (mHal3Device != nullptr) {
3345 mHal3Device->ops->dump(mHal3Device, fd);
3346 } else {
3347 // Handled by CameraProviderManager::dump
3348 }
3349 return res;
3350}
3351
3352status_t Camera3Device::HalInterface::close() {
3353 ATRACE_NAME("CameraHal::close()");
3354 if (!valid()) return INVALID_OPERATION;
3355 status_t res = OK;
3356
3357 if (mHal3Device != nullptr) {
3358 mHal3Device->common.close(&mHal3Device->common);
3359 } else {
3360 mHidlSession->close();
3361 }
3362 return res;
3363}
3364
3365status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003366 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003367 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003368 auto pair = std::make_pair(buffer, acquireFence);
3369 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003370 return OK;
3371}
3372
3373status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003374 int32_t frameNumber, int32_t streamId,
3375 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003376 std::lock_guard<std::mutex> lock(mInflightLock);
3377
3378 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3379 auto it = mInflightBufferMap.find(key);
3380 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003381 auto pair = it->second;
3382 *buffer = pair.first;
3383 int acquireFence = pair.second;
3384 if (acquireFence > 0) {
3385 ::close(acquireFence);
3386 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003387 mInflightBufferMap.erase(it);
3388 return OK;
3389}
3390
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003391std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3392 const buffer_handle_t& buf, int streamId) {
3393 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3394
3395 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3396 auto it = bIdMap.find(buf);
3397 if (it == bIdMap.end()) {
3398 bIdMap[buf] = mNextBufferId++;
3399 return std::make_pair(true, mNextBufferId - 1);
3400 } else {
3401 return std::make_pair(false, it->second);
3402 }
3403}
3404
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003405/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003406 * RequestThread inner class methods
3407 */
3408
3409Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003410 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003411 HalInterface* interface,
3412 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003413 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003414 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003415 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003416 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003417 mInterface(interface),
3418 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003419 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003420 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003421 mReconfigured(false),
3422 mDoPause(false),
3423 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003424 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003425 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003426 mCurrentAfTriggerId(0),
3427 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003428 mRepeatingLastFrameNumber(
3429 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003430 mAeLockAvailable(aeLockAvailable),
3431 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003432 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003433}
3434
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003435Camera3Device::RequestThread::~RequestThread() {}
3436
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003437void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003438 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003439 Mutex::Autolock l(mRequestLock);
3440 mListener = listener;
3441}
3442
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003443void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003444 Mutex::Autolock l(mRequestLock);
3445 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003446 // Prepare video stream for high speed recording.
3447 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003448}
3449
Jianing Wei90e59c92014-03-12 18:29:36 -07003450status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003451 List<sp<CaptureRequest> > &requests,
3452 /*out*/
3453 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003454 Mutex::Autolock l(mRequestLock);
3455 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3456 ++it) {
3457 mRequestQueue.push_back(*it);
3458 }
3459
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003460 if (lastFrameNumber != NULL) {
3461 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3462 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3463 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3464 *lastFrameNumber);
3465 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003466
Jianing Wei90e59c92014-03-12 18:29:36 -07003467 unpauseForNewRequests();
3468
3469 return OK;
3470}
3471
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003472
3473status_t Camera3Device::RequestThread::queueTrigger(
3474 RequestTrigger trigger[],
3475 size_t count) {
3476
3477 Mutex::Autolock l(mTriggerMutex);
3478 status_t ret;
3479
3480 for (size_t i = 0; i < count; ++i) {
3481 ret = queueTriggerLocked(trigger[i]);
3482
3483 if (ret != OK) {
3484 return ret;
3485 }
3486 }
3487
3488 return OK;
3489}
3490
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003491const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3492 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003493 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003494 if (d != nullptr) return d->mId;
3495 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003496}
3497
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003498status_t Camera3Device::RequestThread::queueTriggerLocked(
3499 RequestTrigger trigger) {
3500
3501 uint32_t tag = trigger.metadataTag;
3502 ssize_t index = mTriggerMap.indexOfKey(tag);
3503
3504 switch (trigger.getTagType()) {
3505 case TYPE_BYTE:
3506 // fall-through
3507 case TYPE_INT32:
3508 break;
3509 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003510 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3511 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003512 return INVALID_OPERATION;
3513 }
3514
3515 /**
3516 * Collect only the latest trigger, since we only have 1 field
3517 * in the request settings per trigger tag, and can't send more than 1
3518 * trigger per request.
3519 */
3520 if (index != NAME_NOT_FOUND) {
3521 mTriggerMap.editValueAt(index) = trigger;
3522 } else {
3523 mTriggerMap.add(tag, trigger);
3524 }
3525
3526 return OK;
3527}
3528
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003529status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003530 const RequestList &requests,
3531 /*out*/
3532 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003533 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003534 if (lastFrameNumber != NULL) {
3535 *lastFrameNumber = mRepeatingLastFrameNumber;
3536 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003537 mRepeatingRequests.clear();
3538 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3539 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003540
3541 unpauseForNewRequests();
3542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003543 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003544 return OK;
3545}
3546
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003547bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003548 if (mRepeatingRequests.empty()) {
3549 return false;
3550 }
3551 int32_t requestId = requestIn->mResultExtras.requestId;
3552 const RequestList &repeatRequests = mRepeatingRequests;
3553 // All repeating requests are guaranteed to have same id so only check first quest
3554 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3555 return (firstRequest->mResultExtras.requestId == requestId);
3556}
3557
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003558status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003559 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003560 return clearRepeatingRequestsLocked(lastFrameNumber);
3561
3562}
3563
3564status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003565 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003566 if (lastFrameNumber != NULL) {
3567 *lastFrameNumber = mRepeatingLastFrameNumber;
3568 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003569 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003570 return OK;
3571}
3572
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003573status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003574 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003575 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003576 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003577
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003578 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003579
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003580 // Send errors for all requests pending in the request queue, including
3581 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003582 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003583 if (listener != NULL) {
3584 for (RequestList::iterator it = mRequestQueue.begin();
3585 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003586 // Abort the input buffers for reprocess requests.
3587 if ((*it)->mInputStream != NULL) {
3588 camera3_stream_buffer_t inputBuffer;
3589 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3590 if (res != OK) {
3591 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3592 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3593 } else {
3594 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3595 if (res != OK) {
3596 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3597 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3598 }
3599 }
3600 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003601 // Set the frame number this request would have had, if it
3602 // had been submitted; this frame number will not be reused.
3603 // The requestId and burstId fields were set when the request was
3604 // submitted originally (in convertMetadataListToRequestListLocked)
3605 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003607 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003608 }
3609 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003610 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003611
3612 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003613 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003614 if (lastFrameNumber != NULL) {
3615 *lastFrameNumber = mRepeatingLastFrameNumber;
3616 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003617 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003618 return OK;
3619}
3620
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003621status_t Camera3Device::RequestThread::flush() {
3622 ATRACE_CALL();
3623 Mutex::Autolock l(mFlushLock);
3624
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003625 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3626 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003627 }
3628
3629 return -ENOTSUP;
3630}
3631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003632void Camera3Device::RequestThread::setPaused(bool paused) {
3633 Mutex::Autolock l(mPauseLock);
3634 mDoPause = paused;
3635 mDoPauseSignal.signal();
3636}
3637
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003638status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3639 int32_t requestId, nsecs_t timeout) {
3640 Mutex::Autolock l(mLatestRequestMutex);
3641 status_t res;
3642 while (mLatestRequestId != requestId) {
3643 nsecs_t startTime = systemTime();
3644
3645 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3646 if (res != OK) return res;
3647
3648 timeout -= (systemTime() - startTime);
3649 }
3650
3651 return OK;
3652}
3653
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003654void Camera3Device::RequestThread::requestExit() {
3655 // Call parent to set up shutdown
3656 Thread::requestExit();
3657 // The exit from any possible waits
3658 mDoPauseSignal.signal();
3659 mRequestSignal.signal();
3660}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003661
Chien-Yu Chend196d612015-06-22 19:49:01 -07003662
3663/**
3664 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3665 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3666 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3667 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3668 * request.
3669 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003670void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003671 request->mAeTriggerCancelOverride.applyAeLock = false;
3672 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3673
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003674 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003675 return;
3676 }
3677
3678 camera_metadata_entry_t aePrecaptureTrigger =
3679 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3680 if (aePrecaptureTrigger.count > 0 &&
3681 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3682 // Always override CANCEL to IDLE
3683 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3684 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3685 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3686 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3687 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3688
3689 if (mAeLockAvailable == true) {
3690 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3691 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3692 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3693 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3694 request->mAeTriggerCancelOverride.applyAeLock = true;
3695 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3696 }
3697 }
3698 }
3699}
3700
3701/**
3702 * Override result metadata for cancelling AE precapture trigger applied in
3703 * handleAePrecaptureCancelRequest().
3704 */
3705void Camera3Device::overrideResultForPrecaptureCancel(
3706 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3707 if (aeTriggerCancelOverride.applyAeLock) {
3708 // Only devices <= v3.2 should have this override
3709 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3710 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3711 }
3712
3713 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3714 // Only devices <= v3.2 should have this override
3715 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3716 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3717 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3718 }
3719}
3720
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003721void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003722 bool surfaceAbandoned = false;
3723 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003724 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003725 {
3726 Mutex::Autolock l(mRequestLock);
3727 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3728 // repeating requests.
3729 for (const auto& request : mRepeatingRequests) {
3730 for (const auto& s : request->mOutputStreams) {
3731 if (s->isAbandoned()) {
3732 surfaceAbandoned = true;
3733 clearRepeatingRequestsLocked(&lastFrameNumber);
3734 break;
3735 }
3736 }
3737 if (surfaceAbandoned) {
3738 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003739 }
3740 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003741 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003742 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003743
3744 if (listener != NULL && surfaceAbandoned) {
3745 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003746 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003747}
3748
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003749bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003750 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003751 status_t res;
3752
3753 // Handle paused state.
3754 if (waitIfPaused()) {
3755 return true;
3756 }
3757
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003758 // Wait for the next batch of requests.
3759 waitForNextRequestBatch();
3760 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003761 return true;
3762 }
3763
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003764 // Get the latest request ID, if any
3765 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003766 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003767 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003768 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003769 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003770 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003771 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3772 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003773 }
3774
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003775 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003776 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003777 if (res == TIMED_OUT) {
3778 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003779 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003780 // Check if any stream is abandoned.
3781 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003782 return true;
3783 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003784 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003785 return false;
3786 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003787
Zhijun Hecc27e112013-10-03 16:12:43 -07003788 // Inform waitUntilRequestProcessed thread of a new request ID
3789 {
3790 Mutex::Autolock al(mLatestRequestMutex);
3791
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003792 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003793 mLatestRequestSignal.signal();
3794 }
3795
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003796 // Submit a batch of requests to HAL.
3797 // Use flush lock only when submitting multilple requests in a batch.
3798 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3799 // which may take a long time to finish so synchronizing flush() and
3800 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3801 // For now, only synchronize for high speed recording and we should figure something out for
3802 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003803 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003804
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003805 if (useFlushLock) {
3806 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003807 }
3808
Zhijun Hef0645c12016-08-02 00:58:11 -07003809 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003810 mNextRequests.size());
3811 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003812 // Submit request and block until ready for next one
3813 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003814 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003815
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003816 if (res != OK) {
3817 // Should only get a failure here for malformed requests or device-level
3818 // errors, so consider all errors fatal. Bad metadata failures should
3819 // come through notify.
3820 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3821 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3822 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003823 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003824 if (useFlushLock) {
3825 mFlushLock.unlock();
3826 }
3827 return false;
3828 }
3829
3830 // Mark that the request has be submitted successfully.
3831 nextRequest.submitted = true;
3832
3833 // Update the latest request sent to HAL
3834 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3835 Mutex::Autolock al(mLatestRequestMutex);
3836
3837 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3838 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003839
3840 sp<Camera3Device> parent = mParent.promote();
3841 if (parent != NULL) {
3842 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3843 0, mLatestRequest);
3844 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003845 }
3846
3847 if (nextRequest.halRequest.settings != NULL) {
3848 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3849 }
3850
3851 // Remove any previously queued triggers (after unlock)
3852 res = removeTriggers(mPrevRequest);
3853 if (res != OK) {
3854 SET_ERR("RequestThread: Unable to remove triggers "
3855 "(capture request %d, HAL device: %s (%d)",
3856 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003857 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003858 if (useFlushLock) {
3859 mFlushLock.unlock();
3860 }
3861 return false;
3862 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003863 }
3864
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003865 if (useFlushLock) {
3866 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003867 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003868
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003869 // Unset as current request
3870 {
3871 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003872 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003873 }
3874
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003875 return true;
3876}
3877
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003878status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003879 ATRACE_CALL();
3880
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003881 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003882 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3883 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3884 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3885
3886 // Prepare a request to HAL
3887 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3888
3889 // Insert any queued triggers (before metadata is locked)
3890 status_t res = insertTriggers(captureRequest);
3891
3892 if (res < 0) {
3893 SET_ERR("RequestThread: Unable to insert triggers "
3894 "(capture request %d, HAL device: %s (%d)",
3895 halRequest->frame_number, strerror(-res), res);
3896 return INVALID_OPERATION;
3897 }
3898 int triggerCount = res;
3899 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3900 mPrevTriggers = triggerCount;
3901
3902 // If the request is the same as last, or we had triggers last time
3903 if (mPrevRequest != captureRequest || triggersMixedIn) {
3904 /**
3905 * HAL workaround:
3906 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3907 */
3908 res = addDummyTriggerIds(captureRequest);
3909 if (res != OK) {
3910 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3911 "(capture request %d, HAL device: %s (%d)",
3912 halRequest->frame_number, strerror(-res), res);
3913 return INVALID_OPERATION;
3914 }
3915
3916 /**
3917 * The request should be presorted so accesses in HAL
3918 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3919 */
3920 captureRequest->mSettings.sort();
3921 halRequest->settings = captureRequest->mSettings.getAndLock();
3922 mPrevRequest = captureRequest;
3923 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3924
3925 IF_ALOGV() {
3926 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3927 find_camera_metadata_ro_entry(
3928 halRequest->settings,
3929 ANDROID_CONTROL_AF_TRIGGER,
3930 &e
3931 );
3932 if (e.count > 0) {
3933 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3934 __FUNCTION__,
3935 halRequest->frame_number,
3936 e.data.u8[0]);
3937 }
3938 }
3939 } else {
3940 // leave request.settings NULL to indicate 'reuse latest given'
3941 ALOGVV("%s: Request settings are REUSED",
3942 __FUNCTION__);
3943 }
3944
3945 uint32_t totalNumBuffers = 0;
3946
3947 // Fill in buffers
3948 if (captureRequest->mInputStream != NULL) {
3949 halRequest->input_buffer = &captureRequest->mInputBuffer;
3950 totalNumBuffers += 1;
3951 } else {
3952 halRequest->input_buffer = NULL;
3953 }
3954
3955 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3956 captureRequest->mOutputStreams.size());
3957 halRequest->output_buffers = outputBuffers->array();
3958 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003959 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
3960
3961 // Prepare video buffers for high speed recording on the first video request.
3962 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3963 // Only try to prepare video stream on the first video request.
3964 mPrepareVideoStream = false;
3965
3966 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3967 while (res == NOT_ENOUGH_DATA) {
3968 res = outputStream->prepareNextBuffer();
3969 }
3970 if (res != OK) {
3971 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3972 __FUNCTION__, strerror(-res), res);
3973 outputStream->cancelPrepare();
3974 }
3975 }
3976
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08003977 res = outputStream->getBuffer(&outputBuffers->editItemAt(i),
3978 captureRequest->mOutputSurfaces[i]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003979 if (res != OK) {
3980 // Can't get output buffer from gralloc queue - this could be due to
3981 // abandoned queue or other consumer misbehavior, so not a fatal
3982 // error
3983 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3984 " %s (%d)", strerror(-res), res);
3985
3986 return TIMED_OUT;
3987 }
3988 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07003989
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003990 }
3991 totalNumBuffers += halRequest->num_output_buffers;
3992
3993 // Log request in the in-flight queue
3994 sp<Camera3Device> parent = mParent.promote();
3995 if (parent == NULL) {
3996 // Should not happen, and nowhere to send errors to, so just log it
3997 CLOGE("RequestThread: Parent is gone");
3998 return INVALID_OPERATION;
3999 }
4000 res = parent->registerInFlight(halRequest->frame_number,
4001 totalNumBuffers, captureRequest->mResultExtras,
4002 /*hasInput*/halRequest->input_buffer != NULL,
4003 captureRequest->mAeTriggerCancelOverride);
4004 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4005 ", burstId = %" PRId32 ".",
4006 __FUNCTION__,
4007 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4008 captureRequest->mResultExtras.burstId);
4009 if (res != OK) {
4010 SET_ERR("RequestThread: Unable to register new in-flight request:"
4011 " %s (%d)", strerror(-res), res);
4012 return INVALID_OPERATION;
4013 }
4014 }
4015
4016 return OK;
4017}
4018
Igor Murashkin1e479c02013-09-06 16:55:14 -07004019CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4020 Mutex::Autolock al(mLatestRequestMutex);
4021
4022 ALOGV("RequestThread::%s", __FUNCTION__);
4023
4024 return mLatestRequest;
4025}
4026
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004027bool Camera3Device::RequestThread::isStreamPending(
4028 sp<Camera3StreamInterface>& stream) {
4029 Mutex::Autolock l(mRequestLock);
4030
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004031 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004032 if (!nextRequest.submitted) {
4033 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4034 if (stream == s) return true;
4035 }
4036 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004037 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004038 }
4039
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004040 for (const auto& request : mRequestQueue) {
4041 for (const auto& s : request->mOutputStreams) {
4042 if (stream == s) return true;
4043 }
4044 if (stream == request->mInputStream) return true;
4045 }
4046
4047 for (const auto& request : mRepeatingRequests) {
4048 for (const auto& s : request->mOutputStreams) {
4049 if (stream == s) return true;
4050 }
4051 if (stream == request->mInputStream) return true;
4052 }
4053
4054 return false;
4055}
Jianing Weicb0652e2014-03-12 18:29:36 -07004056
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004057void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4058 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 return;
4060 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004061
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004062 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004063 // Skip the ones that have been submitted successfully.
4064 if (nextRequest.submitted) {
4065 continue;
4066 }
4067
4068 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4069 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4070 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4071
4072 if (halRequest->settings != NULL) {
4073 captureRequest->mSettings.unlock(halRequest->settings);
4074 }
4075
4076 if (captureRequest->mInputStream != NULL) {
4077 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4078 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4079 }
4080
4081 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4082 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4083 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4084 }
4085
4086 if (sendRequestError) {
4087 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004088 sp<NotificationListener> listener = mListener.promote();
4089 if (listener != NULL) {
4090 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004091 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004092 captureRequest->mResultExtras);
4093 }
4094 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004095
4096 // Remove yet-to-be submitted inflight request from inflightMap
4097 {
4098 sp<Camera3Device> parent = mParent.promote();
4099 if (parent != NULL) {
4100 Mutex::Autolock l(parent->mInFlightLock);
4101 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4102 if (idx >= 0) {
4103 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4104 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4105 parent->removeInFlightMapEntryLocked(idx);
4106 }
4107 }
4108 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004109 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004110
4111 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004112 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004113}
4114
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004115void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004116 // Optimized a bit for the simple steady-state case (single repeating
4117 // request), to avoid putting that request in the queue temporarily.
4118 Mutex::Autolock l(mRequestLock);
4119
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004120 assert(mNextRequests.empty());
4121
4122 NextRequest nextRequest;
4123 nextRequest.captureRequest = waitForNextRequestLocked();
4124 if (nextRequest.captureRequest == nullptr) {
4125 return;
4126 }
4127
4128 nextRequest.halRequest = camera3_capture_request_t();
4129 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004130 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131
4132 // Wait for additional requests
4133 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4134
4135 for (size_t i = 1; i < batchSize; i++) {
4136 NextRequest additionalRequest;
4137 additionalRequest.captureRequest = waitForNextRequestLocked();
4138 if (additionalRequest.captureRequest == nullptr) {
4139 break;
4140 }
4141
4142 additionalRequest.halRequest = camera3_capture_request_t();
4143 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004144 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004145 }
4146
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004147 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004148 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004149 mNextRequests.size(), batchSize);
4150 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004151 }
4152
4153 return;
4154}
4155
4156sp<Camera3Device::CaptureRequest>
4157 Camera3Device::RequestThread::waitForNextRequestLocked() {
4158 status_t res;
4159 sp<CaptureRequest> nextRequest;
4160
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004161 while (mRequestQueue.empty()) {
4162 if (!mRepeatingRequests.empty()) {
4163 // Always atomically enqueue all requests in a repeating request
4164 // list. Guarantees a complete in-sequence set of captures to
4165 // application.
4166 const RequestList &requests = mRepeatingRequests;
4167 RequestList::const_iterator firstRequest =
4168 requests.begin();
4169 nextRequest = *firstRequest;
4170 mRequestQueue.insert(mRequestQueue.end(),
4171 ++firstRequest,
4172 requests.end());
4173 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004174
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004175 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004177 break;
4178 }
4179
4180 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4181
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004182 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4183 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004184 Mutex::Autolock pl(mPauseLock);
4185 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004186 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004187 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004188 // Let the tracker know
4189 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4190 if (statusTracker != 0) {
4191 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4192 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004193 }
4194 // Stop waiting for now and let thread management happen
4195 return NULL;
4196 }
4197 }
4198
4199 if (nextRequest == NULL) {
4200 // Don't have a repeating request already in hand, so queue
4201 // must have an entry now.
4202 RequestList::iterator firstRequest =
4203 mRequestQueue.begin();
4204 nextRequest = *firstRequest;
4205 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004206 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4207 sp<NotificationListener> listener = mListener.promote();
4208 if (listener != NULL) {
4209 listener->notifyRequestQueueEmpty();
4210 }
4211 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004212 }
4213
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004214 // In case we've been unpaused by setPaused clearing mDoPause, need to
4215 // update internal pause state (capture/setRepeatingRequest unpause
4216 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004218 if (mPaused) {
4219 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4220 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4221 if (statusTracker != 0) {
4222 statusTracker->markComponentActive(mStatusId);
4223 }
4224 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004225 mPaused = false;
4226
4227 // Check if we've reconfigured since last time, and reset the preview
4228 // request if so. Can't use 'NULL request == repeat' across configure calls.
4229 if (mReconfigured) {
4230 mPrevRequest.clear();
4231 mReconfigured = false;
4232 }
4233
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004234 if (nextRequest != NULL) {
4235 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004236 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4237 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004238
4239 // Since RequestThread::clear() removes buffers from the input stream,
4240 // get the right buffer here before unlocking mRequestLock
4241 if (nextRequest->mInputStream != NULL) {
4242 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4243 if (res != OK) {
4244 // Can't get input buffer from gralloc queue - this could be due to
4245 // disconnected queue or other producer misbehavior, so not a fatal
4246 // error
4247 ALOGE("%s: Can't get input buffer, skipping request:"
4248 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004249
4250 sp<NotificationListener> listener = mListener.promote();
4251 if (listener != NULL) {
4252 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004253 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004254 nextRequest->mResultExtras);
4255 }
4256 return NULL;
4257 }
4258 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004259 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004260
4261 handleAePrecaptureCancelRequest(nextRequest);
4262
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004263 return nextRequest;
4264}
4265
4266bool Camera3Device::RequestThread::waitIfPaused() {
4267 status_t res;
4268 Mutex::Autolock l(mPauseLock);
4269 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004270 if (mPaused == false) {
4271 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004272 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4273 // Let the tracker know
4274 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4275 if (statusTracker != 0) {
4276 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4277 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004278 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004279
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004280 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004281 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004282 return true;
4283 }
4284 }
4285 // We don't set mPaused to false here, because waitForNextRequest needs
4286 // to further manage the paused state in case of starvation.
4287 return false;
4288}
4289
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004290void Camera3Device::RequestThread::unpauseForNewRequests() {
4291 // With work to do, mark thread as unpaused.
4292 // If paused by request (setPaused), don't resume, to avoid
4293 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004294 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004295 Mutex::Autolock p(mPauseLock);
4296 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4298 if (mPaused) {
4299 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4300 if (statusTracker != 0) {
4301 statusTracker->markComponentActive(mStatusId);
4302 }
4303 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004304 mPaused = false;
4305 }
4306}
4307
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004308void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4309 sp<Camera3Device> parent = mParent.promote();
4310 if (parent != NULL) {
4311 va_list args;
4312 va_start(args, fmt);
4313
4314 parent->setErrorStateV(fmt, args);
4315
4316 va_end(args);
4317 }
4318}
4319
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004320status_t Camera3Device::RequestThread::insertTriggers(
4321 const sp<CaptureRequest> &request) {
4322
4323 Mutex::Autolock al(mTriggerMutex);
4324
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004325 sp<Camera3Device> parent = mParent.promote();
4326 if (parent == NULL) {
4327 CLOGE("RequestThread: Parent is gone");
4328 return DEAD_OBJECT;
4329 }
4330
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004331 CameraMetadata &metadata = request->mSettings;
4332 size_t count = mTriggerMap.size();
4333
4334 for (size_t i = 0; i < count; ++i) {
4335 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004336 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004337
4338 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4339 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4340 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004341 if (isAeTrigger) {
4342 request->mResultExtras.precaptureTriggerId = triggerId;
4343 mCurrentPreCaptureTriggerId = triggerId;
4344 } else {
4345 request->mResultExtras.afTriggerId = triggerId;
4346 mCurrentAfTriggerId = triggerId;
4347 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004348 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4349 continue; // Trigger ID tag is deprecated since device HAL 3.2
4350 }
4351 }
4352
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004353 camera_metadata_entry entry = metadata.find(tag);
4354
4355 if (entry.count > 0) {
4356 /**
4357 * Already has an entry for this trigger in the request.
4358 * Rewrite it with our requested trigger value.
4359 */
4360 RequestTrigger oldTrigger = trigger;
4361
4362 oldTrigger.entryValue = entry.data.u8[0];
4363
4364 mTriggerReplacedMap.add(tag, oldTrigger);
4365 } else {
4366 /**
4367 * More typical, no trigger entry, so we just add it
4368 */
4369 mTriggerRemovedMap.add(tag, trigger);
4370 }
4371
4372 status_t res;
4373
4374 switch (trigger.getTagType()) {
4375 case TYPE_BYTE: {
4376 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4377 res = metadata.update(tag,
4378 &entryValue,
4379 /*count*/1);
4380 break;
4381 }
4382 case TYPE_INT32:
4383 res = metadata.update(tag,
4384 &trigger.entryValue,
4385 /*count*/1);
4386 break;
4387 default:
4388 ALOGE("%s: Type not supported: 0x%x",
4389 __FUNCTION__,
4390 trigger.getTagType());
4391 return INVALID_OPERATION;
4392 }
4393
4394 if (res != OK) {
4395 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4396 ", value %d", __FUNCTION__, trigger.getTagName(),
4397 trigger.entryValue);
4398 return res;
4399 }
4400
4401 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4402 trigger.getTagName(),
4403 trigger.entryValue);
4404 }
4405
4406 mTriggerMap.clear();
4407
4408 return count;
4409}
4410
4411status_t Camera3Device::RequestThread::removeTriggers(
4412 const sp<CaptureRequest> &request) {
4413 Mutex::Autolock al(mTriggerMutex);
4414
4415 CameraMetadata &metadata = request->mSettings;
4416
4417 /**
4418 * Replace all old entries with their old values.
4419 */
4420 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4421 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4422
4423 status_t res;
4424
4425 uint32_t tag = trigger.metadataTag;
4426 switch (trigger.getTagType()) {
4427 case TYPE_BYTE: {
4428 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4429 res = metadata.update(tag,
4430 &entryValue,
4431 /*count*/1);
4432 break;
4433 }
4434 case TYPE_INT32:
4435 res = metadata.update(tag,
4436 &trigger.entryValue,
4437 /*count*/1);
4438 break;
4439 default:
4440 ALOGE("%s: Type not supported: 0x%x",
4441 __FUNCTION__,
4442 trigger.getTagType());
4443 return INVALID_OPERATION;
4444 }
4445
4446 if (res != OK) {
4447 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4448 ", trigger value %d", __FUNCTION__,
4449 trigger.getTagName(), trigger.entryValue);
4450 return res;
4451 }
4452 }
4453 mTriggerReplacedMap.clear();
4454
4455 /**
4456 * Remove all new entries.
4457 */
4458 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4459 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4460 status_t res = metadata.erase(trigger.metadataTag);
4461
4462 if (res != OK) {
4463 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4464 ", trigger value %d", __FUNCTION__,
4465 trigger.getTagName(), trigger.entryValue);
4466 return res;
4467 }
4468 }
4469 mTriggerRemovedMap.clear();
4470
4471 return OK;
4472}
4473
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004474status_t Camera3Device::RequestThread::addDummyTriggerIds(
4475 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004476 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004477 static const int32_t dummyTriggerId = 1;
4478 status_t res;
4479
4480 CameraMetadata &metadata = request->mSettings;
4481
4482 // If AF trigger is active, insert a dummy AF trigger ID if none already
4483 // exists
4484 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4485 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4486 if (afTrigger.count > 0 &&
4487 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4488 afId.count == 0) {
4489 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4490 if (res != OK) return res;
4491 }
4492
4493 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4494 // if none already exists
4495 camera_metadata_entry pcTrigger =
4496 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4497 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4498 if (pcTrigger.count > 0 &&
4499 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4500 pcId.count == 0) {
4501 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4502 &dummyTriggerId, 1);
4503 if (res != OK) return res;
4504 }
4505
4506 return OK;
4507}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004508
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004509/**
4510 * PreparerThread inner class methods
4511 */
4512
4513Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004514 Thread(/*canCallJava*/false), mListener(nullptr),
4515 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004516}
4517
4518Camera3Device::PreparerThread::~PreparerThread() {
4519 Thread::requestExitAndWait();
4520 if (mCurrentStream != nullptr) {
4521 mCurrentStream->cancelPrepare();
4522 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4523 mCurrentStream.clear();
4524 }
4525 clear();
4526}
4527
Ruben Brunkc78ac262015-08-13 17:58:46 -07004528status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004529 status_t res;
4530
4531 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004532 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004533
Ruben Brunkc78ac262015-08-13 17:58:46 -07004534 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004535 if (res == OK) {
4536 // No preparation needed, fire listener right off
4537 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004538 if (listener != NULL) {
4539 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004540 }
4541 return OK;
4542 } else if (res != NOT_ENOUGH_DATA) {
4543 return res;
4544 }
4545
4546 // Need to prepare, start up thread if necessary
4547 if (!mActive) {
4548 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4549 // isn't running
4550 Thread::requestExitAndWait();
4551 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4552 if (res != OK) {
4553 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004554 if (listener != NULL) {
4555 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004556 }
4557 return res;
4558 }
4559 mCancelNow = false;
4560 mActive = true;
4561 ALOGV("%s: Preparer stream started", __FUNCTION__);
4562 }
4563
4564 // queue up the work
4565 mPendingStreams.push_back(stream);
4566 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4567
4568 return OK;
4569}
4570
4571status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004572 Mutex::Autolock l(mLock);
4573
4574 for (const auto& stream : mPendingStreams) {
4575 stream->cancelPrepare();
4576 }
4577 mPendingStreams.clear();
4578 mCancelNow = true;
4579
4580 return OK;
4581}
4582
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004583void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004584 Mutex::Autolock l(mLock);
4585 mListener = listener;
4586}
4587
4588bool Camera3Device::PreparerThread::threadLoop() {
4589 status_t res;
4590 {
4591 Mutex::Autolock l(mLock);
4592 if (mCurrentStream == nullptr) {
4593 // End thread if done with work
4594 if (mPendingStreams.empty()) {
4595 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4596 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4597 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4598 mActive = false;
4599 return false;
4600 }
4601
4602 // Get next stream to prepare
4603 auto it = mPendingStreams.begin();
4604 mCurrentStream = *it;
4605 mPendingStreams.erase(it);
4606 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4607 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4608 } else if (mCancelNow) {
4609 mCurrentStream->cancelPrepare();
4610 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4611 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4612 mCurrentStream.clear();
4613 mCancelNow = false;
4614 return true;
4615 }
4616 }
4617
4618 res = mCurrentStream->prepareNextBuffer();
4619 if (res == NOT_ENOUGH_DATA) return true;
4620 if (res != OK) {
4621 // Something bad happened; try to recover by cancelling prepare and
4622 // signalling listener anyway
4623 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4624 mCurrentStream->getId(), res, strerror(-res));
4625 mCurrentStream->cancelPrepare();
4626 }
4627
4628 // This stream has finished, notify listener
4629 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004630 sp<NotificationListener> listener = mListener.promote();
4631 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004632 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4633 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004634 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004635 }
4636
4637 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4638 mCurrentStream.clear();
4639
4640 return true;
4641}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004642
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004643/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004644 * Static callback forwarding methods from HAL to instance
4645 */
4646
4647void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4648 const camera3_capture_result *result) {
4649 Camera3Device *d =
4650 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004651
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004652 d->processCaptureResult(result);
4653}
4654
4655void Camera3Device::sNotify(const camera3_callback_ops *cb,
4656 const camera3_notify_msg *msg) {
4657 Camera3Device *d =
4658 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4659 d->notify(msg);
4660}
4661
4662}; // namespace android