blob: 1675584dcdb279f28d9d197ba5db5984b23c61b7 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
54#include "device3/Camera3ZslStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070055#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070056#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070057#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080058
59using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080060using namespace android::hardware::camera;
61using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080062
63namespace android {
64
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080065Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080066 mId(id),
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
518StreamConfigurationMode Camera3Device::mapToStreamConfigurationMode(
519 camera3_stream_configuration_mode_t operationMode) {
520 switch(operationMode) {
521 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
522 return StreamConfigurationMode::NORMAL_MODE;
523 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
524 return StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
525 case CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START:
526 // Needs to be mapped by vendor extensions
527 break;
528 }
529 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
530 return StreamConfigurationMode::NORMAL_MODE;
531}
532
533camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
534 switch (status) {
535 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
536 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
537 }
538 return CAMERA3_BUFFER_STATUS_ERROR;
539}
540
541int Camera3Device::mapToFrameworkFormat(
542 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
543 return static_cast<uint32_t>(pixelFormat);
544}
545
546uint32_t Camera3Device::mapConsumerToFrameworkUsage(
547 ConsumerUsageFlags usage) {
548 return usage;
549}
550
551uint32_t Camera3Device::mapProducerToFrameworkUsage(
552 ProducerUsageFlags usage) {
553 return usage;
554}
555
Zhijun Hef7da0962014-04-24 13:27:56 -0700556ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700557 // Get max jpeg size (area-wise).
558 Size maxJpegResolution = getMaxJpegResolution();
559 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
561 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700562 return BAD_VALUE;
563 }
564
Zhijun Hef7da0962014-04-24 13:27:56 -0700565 // Get max jpeg buffer size
566 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700567 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
568 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800569 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
570 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700571 return BAD_VALUE;
572 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700573 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800574 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700575
576 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700577 float scaleFactor = ((float) (width * height)) /
578 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800579 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
580 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 if (jpegBufferSize > maxJpegBufferSize) {
582 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700583 }
584
585 return jpegBufferSize;
586}
587
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700588ssize_t Camera3Device::getPointCloudBufferSize() const {
589 const int FLOATS_PER_POINT=4;
590 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
591 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800592 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
593 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700594 return BAD_VALUE;
595 }
596 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
597 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
598 return maxBytesForPointCloud;
599}
600
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800602 const int PER_CONFIGURATION_SIZE = 3;
603 const int WIDTH_OFFSET = 0;
604 const int HEIGHT_OFFSET = 1;
605 const int SIZE_OFFSET = 2;
606 camera_metadata_ro_entry rawOpaqueSizes =
607 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800608 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800609 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800610 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
611 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800612 return BAD_VALUE;
613 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700614
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800615 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
616 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
617 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
618 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
619 }
620 }
621
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800622 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
623 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800624 return BAD_VALUE;
625}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700626
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800627status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
628 ATRACE_CALL();
629 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700630
631 // Try to lock, but continue in case of failure (to avoid blocking in
632 // deadlocks)
633 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
634 bool gotLock = tryLockSpinRightRound(mLock);
635
636 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
638 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700639 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
641 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700642
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800643 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700644
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800645 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700646 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800647 int n = args.size();
648 for (int i = 0; i < n; i++) {
649 if (args[i] == templatesOption) {
650 dumpTemplates = true;
651 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700652 if (args[i] == monitorOption) {
653 if (i + 1 < n) {
654 String8 monitorTags = String8(args[i + 1]);
655 if (monitorTags == "off") {
656 mTagMonitor.disableMonitoring();
657 } else {
658 mTagMonitor.parseTagsToMonitor(monitorTags);
659 }
660 } else {
661 mTagMonitor.disableMonitoring();
662 }
663 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800664 }
665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800666 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 const char *status =
669 mStatus == STATUS_ERROR ? "ERROR" :
670 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700671 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
672 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800673 mStatus == STATUS_ACTIVE ? "ACTIVE" :
674 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700675
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800676 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700677 if (mStatus == STATUS_ERROR) {
678 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
679 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680 lines.appendFormat(" Stream configuration:\n");
Zhijun He1fa89992015-06-01 15:44:31 -0700681 lines.appendFormat(" Operation mode: %s \n", mIsConstrainedHighSpeedConfiguration ?
Eino-Ville Talvala9a179412015-06-09 13:15:16 -0700682 "CONSTRAINED HIGH SPEED VIDEO" : "NORMAL");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800683
684 if (mInputStream != NULL) {
685 write(fd, lines.string(), lines.size());
686 mInputStream->dump(fd, args);
687 } else {
688 lines.appendFormat(" No input stream.\n");
689 write(fd, lines.string(), lines.size());
690 }
691 for (size_t i = 0; i < mOutputStreams.size(); i++) {
692 mOutputStreams[i]->dump(fd,args);
693 }
694
Zhijun He431503c2016-03-07 17:30:16 -0800695 if (mBufferManager != NULL) {
696 lines = String8(" Camera3 Buffer Manager:\n");
697 write(fd, lines.string(), lines.size());
698 mBufferManager->dump(fd, args);
699 }
Zhijun He125684a2015-12-26 15:07:30 -0800700
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700701 lines = String8(" In-flight requests:\n");
702 if (mInFlightMap.size() == 0) {
703 lines.append(" None\n");
704 } else {
705 for (size_t i = 0; i < mInFlightMap.size(); i++) {
706 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700707 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700708 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800709 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700710 r.numBuffersLeft);
711 }
712 }
713 write(fd, lines.string(), lines.size());
714
Igor Murashkin1e479c02013-09-06 16:55:14 -0700715 {
716 lines = String8(" Last request sent:\n");
717 write(fd, lines.string(), lines.size());
718
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700720 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
721 }
722
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800723 if (dumpTemplates) {
724 const char *templateNames[] = {
725 "TEMPLATE_PREVIEW",
726 "TEMPLATE_STILL_CAPTURE",
727 "TEMPLATE_VIDEO_RECORD",
728 "TEMPLATE_VIDEO_SNAPSHOT",
729 "TEMPLATE_ZERO_SHUTTER_LAG",
730 "TEMPLATE_MANUAL"
731 };
732
733 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800734 camera_metadata_t *templateRequest = nullptr;
735 mInterface->constructDefaultRequestSettings(
736 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800737 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800738 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800739 lines.append(" Not supported\n");
740 write(fd, lines.string(), lines.size());
741 } else {
742 write(fd, lines.string(), lines.size());
743 dump_indented_camera_metadata(templateRequest,
744 fd, /*verbosity*/2, /*indentation*/8);
745 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800746 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800747 }
748 }
749
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700750 mTagMonitor.dumpMonitoredMetadata(fd);
751
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 if (mInterface->valid()) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800755 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700758 if (gotLock) mLock.unlock();
759 if (gotInterfaceLock) mInterfaceLock.unlock();
760
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761 return OK;
762}
763
764const CameraMetadata& Camera3Device::info() const {
765 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800766 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
767 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700768 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800769 mStatus == STATUS_ERROR ?
770 "when in error state" : "before init");
771 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772 return mDeviceInfo;
773}
774
Jianing Wei90e59c92014-03-12 18:29:36 -0700775status_t Camera3Device::checkStatusOkToCaptureLocked() {
776 switch (mStatus) {
777 case STATUS_ERROR:
778 CLOGE("Device has encountered a serious error");
779 return INVALID_OPERATION;
780 case STATUS_UNINITIALIZED:
781 CLOGE("Device not initialized");
782 return INVALID_OPERATION;
783 case STATUS_UNCONFIGURED:
784 case STATUS_CONFIGURED:
785 case STATUS_ACTIVE:
786 // OK
787 break;
788 default:
789 SET_ERR_L("Unexpected status: %d", mStatus);
790 return INVALID_OPERATION;
791 }
792 return OK;
793}
794
795status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 const List<const CameraMetadata> &metadataList,
797 const std::list<const SurfaceMap> &surfaceMaps,
798 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700799 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700800 if (requestList == NULL) {
801 CLOGE("requestList cannot be NULL.");
802 return BAD_VALUE;
803 }
804
Jianing Weicb0652e2014-03-12 18:29:36 -0700805 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
807 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
808 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
809 ++metadataIt, ++surfaceMapIt) {
810 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 if (newRequest == 0) {
812 CLOGE("Can't create capture request");
813 return BAD_VALUE;
814 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700815
Shuzhen Wang9d066012016-09-30 11:30:20 -0700816 newRequest->mRepeating = repeating;
817
Jianing Weicb0652e2014-03-12 18:29:36 -0700818 // Setup burst Id and request Id
819 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
821 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700822 CLOGE("RequestID entry exists; but must not be empty in metadata");
823 return BAD_VALUE;
824 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700825 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700826 } else {
827 CLOGE("RequestID does not exist in metadata");
828 return BAD_VALUE;
829 }
830
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700832
833 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
836 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
837 return BAD_VALUE;
838 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700839
840 // Setup batch size if this is a high speed video recording request.
841 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
842 auto firstRequest = requestList->begin();
843 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
844 if (outputStream->isVideoStream()) {
845 (*firstRequest)->mBatchSize = requestList->size();
846 break;
847 }
848 }
849 }
850
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 return OK;
852}
853
Jianing Weicb0652e2014-03-12 18:29:36 -0700854status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700857 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
859 convertToRequestList(requests, surfaceMaps, request);
860
861 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
862}
863
864void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
865 std::list<const SurfaceMap>& surfaceMaps,
866 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700867 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868
869 SurfaceMap surfaceMap;
870 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
871 // With no surface list passed in, stream and surface will have 1-to-1
872 // mapping. So the surface index is 0 for each stream in the surfaceMap.
873 for (size_t i = 0; i < streams.count; i++) {
874 surfaceMap[streams.data.i32[i]].push_back(0);
875 }
876 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877}
878
Jianing Wei90e59c92014-03-12 18:29:36 -0700879status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700880 const List<const CameraMetadata> &requests,
881 const std::list<const SurfaceMap> &surfaceMaps,
882 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700883 /*out*/
884 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 ATRACE_CALL();
886 Mutex::Autolock il(mInterfaceLock);
887 Mutex::Autolock l(mLock);
888
889 status_t res = checkStatusOkToCaptureLocked();
890 if (res != OK) {
891 // error logged by previous call
892 return res;
893 }
894
895 RequestList requestList;
896
Shuzhen Wang0129d522016-10-30 22:43:41 -0700897 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
898 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 if (res != OK) {
900 // error logged by previous call
901 return res;
902 }
903
904 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700905 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700906 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700907 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700908 }
909
910 if (res == OK) {
911 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
912 if (res != OK) {
913 SET_ERR_L("Can't transition to active in %f seconds!",
914 kActiveTimeout/1e9);
915 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800916 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700917 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 } else {
919 CLOGE("Cannot queue request. Impossible.");
920 return BAD_VALUE;
921 }
922
923 return res;
924}
925
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926hardware::Return<void> Camera3Device::processCaptureResult(
927 const device::V3_2::CaptureResult& result) {
928 camera3_capture_result r;
929 status_t res;
930 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800931 if (result.result.size() != 0) {
932 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
933 size_t expected_metadata_size = result.result.size();
934 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
935 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
936 __FUNCTION__, result.frameNumber, strerror(-res), res);
937 return hardware::Void();
938 }
939 } else {
940 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800941 }
942
943 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
944 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
945 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
946 auto& bDst = outputBuffers[i];
947 const StreamBuffer &bSrc = result.outputBuffers[i];
948
949 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
950 if (idx == -1) {
951 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
952 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
953 return hardware::Void();
954 }
955 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
956
957 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800958 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800959 if (res != OK) {
960 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
961 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
962 return hardware::Void();
963 }
964 bDst.buffer = buffer;
965 bDst.status = mapHidlBufferStatus(bSrc.status);
966 bDst.acquire_fence = -1;
967 if (bSrc.releaseFence == nullptr) {
968 bDst.release_fence = -1;
969 } else if (bSrc.releaseFence->numFds == 1) {
970 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
971 } else {
972 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
973 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
974 return hardware::Void();
975 }
976 }
977 r.num_output_buffers = outputBuffers.size();
978 r.output_buffers = outputBuffers.data();
979
980 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800981 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800982 r.input_buffer = nullptr;
983 } else {
984 if (mInputStream->getId() != result.inputBuffer.streamId) {
985 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
986 result.frameNumber, result.inputBuffer.streamId);
987 return hardware::Void();
988 }
989 inputBuffer.stream = mInputStream->asHalStream();
990 buffer_handle_t *buffer;
991 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
992 &buffer);
993 if (res != OK) {
994 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
995 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
996 return hardware::Void();
997 }
998 inputBuffer.buffer = buffer;
999 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1000 inputBuffer.acquire_fence = -1;
1001 if (result.inputBuffer.releaseFence == nullptr) {
1002 inputBuffer.release_fence = -1;
1003 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1004 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1005 } else {
1006 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1007 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
1008 return hardware::Void();
1009 }
1010 r.input_buffer = &inputBuffer;
1011 }
1012
1013 r.partial_result = result.partialResult;
1014
1015 processCaptureResult(&r);
1016
1017 return hardware::Void();
1018}
1019
1020hardware::Return<void> Camera3Device::notify(
1021 const NotifyMsg& msg) {
1022 camera3_notify_msg m;
1023 switch (msg.type) {
1024 case MsgType::ERROR:
1025 m.type = CAMERA3_MSG_ERROR;
1026 m.message.error.frame_number = msg.msg.error.frameNumber;
1027 if (msg.msg.error.errorStreamId >= 0) {
1028 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
1029 if (idx == -1) {
1030 ALOGE("%s: Frame %d: Invalid error stream id %d",
1031 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1032 return hardware::Void();
1033 }
1034 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1035 } else {
1036 m.message.error.error_stream = nullptr;
1037 }
1038 switch (msg.msg.error.errorCode) {
1039 case ErrorCode::ERROR_DEVICE:
1040 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1041 break;
1042 case ErrorCode::ERROR_REQUEST:
1043 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1044 break;
1045 case ErrorCode::ERROR_RESULT:
1046 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1047 break;
1048 case ErrorCode::ERROR_BUFFER:
1049 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1050 break;
1051 }
1052 break;
1053 case MsgType::SHUTTER:
1054 m.type = CAMERA3_MSG_SHUTTER;
1055 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1056 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1057 break;
1058 }
1059 notify(&m);
1060
1061 return hardware::Void();
1062}
1063
Jianing Weicb0652e2014-03-12 18:29:36 -07001064status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001065 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001066 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001067 ATRACE_CALL();
1068
Shuzhen Wang0129d522016-10-30 22:43:41 -07001069 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001070}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001071
Jianing Weicb0652e2014-03-12 18:29:36 -07001072status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1073 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001074 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001075
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001076 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 std::list<const SurfaceMap> surfaceMaps;
1078 convertToRequestList(requests, surfaceMaps, request);
1079
1080 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1081 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001082}
1083
Jianing Weicb0652e2014-03-12 18:29:36 -07001084status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001085 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001086 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001087 ATRACE_CALL();
1088
Shuzhen Wang0129d522016-10-30 22:43:41 -07001089 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001090}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001091
1092sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001093 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001094 status_t res;
1095
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001096 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001097 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001098 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001099 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001100 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001101 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001102 } else if (mStatus == STATUS_UNCONFIGURED) {
1103 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001104 CLOGE("No streams configured");
1105 return NULL;
1106 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001107 }
1108
Shuzhen Wang0129d522016-10-30 22:43:41 -07001109 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001110 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001111}
1112
Jianing Weicb0652e2014-03-12 18:29:36 -07001113status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001114 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001115 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001116 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001117
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 switch (mStatus) {
1119 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001120 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 return INVALID_OPERATION;
1122 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001123 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001124 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001125 case STATUS_UNCONFIGURED:
1126 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001127 case STATUS_ACTIVE:
1128 // OK
1129 break;
1130 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001131 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 return INVALID_OPERATION;
1133 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001134 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001135
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001136 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001137}
1138
1139status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1140 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001141 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001142
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001143 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001144}
1145
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001146status_t Camera3Device::createInputStream(
1147 uint32_t width, uint32_t height, int format, int *id) {
1148 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001149 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001150 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001151 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1152 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001153
1154 status_t res;
1155 bool wasActive = false;
1156
1157 switch (mStatus) {
1158 case STATUS_ERROR:
1159 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1160 return INVALID_OPERATION;
1161 case STATUS_UNINITIALIZED:
1162 ALOGE("%s: Device not initialized", __FUNCTION__);
1163 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001164 case STATUS_UNCONFIGURED:
1165 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001166 // OK
1167 break;
1168 case STATUS_ACTIVE:
1169 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001170 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001171 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001173 return res;
1174 }
1175 wasActive = true;
1176 break;
1177 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001178 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001179 return INVALID_OPERATION;
1180 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001181 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001182
1183 if (mInputStream != 0) {
1184 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1185 return INVALID_OPERATION;
1186 }
1187
1188 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1189 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001190 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001191
1192 mInputStream = newStream;
1193
1194 *id = mNextStreamId++;
1195
1196 // Continue captures if active at start
1197 if (wasActive) {
1198 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1199 res = configureStreamsLocked();
1200 if (res != OK) {
1201 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1202 __FUNCTION__, mNextStreamId, strerror(-res), res);
1203 return res;
1204 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001205 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001206 }
1207
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001208 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001209 return OK;
1210}
1211
Igor Murashkin2fba5842013-04-22 14:03:54 -07001212
1213status_t Camera3Device::createZslStream(
1214 uint32_t width, uint32_t height,
1215 int depth,
1216 /*out*/
1217 int *id,
1218 sp<Camera3ZslStream>* zslStream) {
1219 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001221 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001222 ALOGV("Camera %s: Creating ZSL stream %d: %d x %d, depth %d",
1223 mId.string(), mNextStreamId, width, height, depth);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001224
1225 status_t res;
1226 bool wasActive = false;
1227
1228 switch (mStatus) {
1229 case STATUS_ERROR:
1230 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1231 return INVALID_OPERATION;
1232 case STATUS_UNINITIALIZED:
1233 ALOGE("%s: Device not initialized", __FUNCTION__);
1234 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 case STATUS_UNCONFIGURED:
1236 case STATUS_CONFIGURED:
Igor Murashkin2fba5842013-04-22 14:03:54 -07001237 // OK
1238 break;
1239 case STATUS_ACTIVE:
1240 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001241 res = internalPauseAndWaitLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001242 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin2fba5842013-04-22 14:03:54 -07001244 return res;
1245 }
1246 wasActive = true;
1247 break;
1248 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 SET_ERR_L("Unexpected status: %d", mStatus);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001250 return INVALID_OPERATION;
1251 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001253
1254 if (mInputStream != 0) {
1255 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1256 return INVALID_OPERATION;
1257 }
1258
1259 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
1260 width, height, depth);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001262
1263 res = mOutputStreams.add(mNextStreamId, newStream);
1264 if (res < 0) {
1265 ALOGE("%s: Can't add new stream to set: %s (%d)",
1266 __FUNCTION__, strerror(-res), res);
1267 return res;
1268 }
1269 mInputStream = newStream;
1270
Yuvraj Pasie5e3d082014-04-15 18:37:45 +05301271 mNeedConfig = true;
1272
Igor Murashkin2fba5842013-04-22 14:03:54 -07001273 *id = mNextStreamId++;
1274 *zslStream = newStream;
1275
1276 // Continue captures if active at start
1277 if (wasActive) {
1278 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1279 res = configureStreamsLocked();
1280 if (res != OK) {
1281 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1282 __FUNCTION__, mNextStreamId, strerror(-res), res);
1283 return res;
1284 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001285 internalResumeLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001286 }
1287
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001288 ALOGV("Camera %s: Created ZSL stream", mId.string());
Igor Murashkin2fba5842013-04-22 14:03:54 -07001289 return OK;
1290}
1291
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001292status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001293 uint32_t width, uint32_t height, int format,
1294 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
1295 int streamSetId, uint32_t consumerUsage) {
1296 ATRACE_CALL();
1297
1298 if (consumer == nullptr) {
1299 ALOGE("%s: consumer must not be null", __FUNCTION__);
1300 return BAD_VALUE;
1301 }
1302
1303 std::vector<sp<Surface>> consumers;
1304 consumers.push_back(consumer);
1305
1306 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
1307 format, dataSpace, rotation, id, streamSetId, consumerUsage);
1308}
1309
1310status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1311 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1312 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
1313 int streamSetId, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001314 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001316 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001317 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
1318 " consumer usage 0x%x", mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Zhijun He5d677d12016-05-29 16:52:39 -07001319 consumerUsage);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001320
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001321 status_t res;
1322 bool wasActive = false;
1323
1324 switch (mStatus) {
1325 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001326 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001327 return INVALID_OPERATION;
1328 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001329 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001330 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001331 case STATUS_UNCONFIGURED:
1332 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333 // OK
1334 break;
1335 case STATUS_ACTIVE:
1336 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001337 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001339 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001340 return res;
1341 }
1342 wasActive = true;
1343 break;
1344 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001345 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001346 return INVALID_OPERATION;
1347 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001348 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001349
1350 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001351 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001352 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001353 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001354 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1355 }
Zhijun He5d677d12016-05-29 16:52:39 -07001356
Shuzhen Wang0129d522016-10-30 22:43:41 -07001357 if (consumers.size() == 0 && !hasDeferredConsumer) {
1358 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1359 return BAD_VALUE;
1360 }
Zhijun He5d677d12016-05-29 16:52:39 -07001361 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1362 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001363 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001364 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1365 return BAD_VALUE;
1366 }
1367
Shuzhen Wang0129d522016-10-30 22:43:41 -07001368 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001369 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1370 return BAD_VALUE;
1371 }
1372
Shuzhen Wang0129d522016-10-30 22:43:41 -07001373 bool streamSharing = consumers.size() > 1 || (consumers.size() > 0 && hasDeferredConsumer);
1374
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001375 // Use legacy dataspace values for older HALs
1376 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1377 dataSpace = mapToLegacyDataspace(dataSpace);
1378 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001380 ssize_t blobBufferSize;
1381 if (dataSpace != HAL_DATASPACE_DEPTH) {
1382 blobBufferSize = getJpegBufferSize(width, height);
1383 if (blobBufferSize <= 0) {
1384 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1385 return BAD_VALUE;
1386 }
1387 } else {
1388 blobBufferSize = getPointCloudBufferSize();
1389 if (blobBufferSize <= 0) {
1390 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1391 return BAD_VALUE;
1392 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001393 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001394 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001395 width, height, blobBufferSize, format, dataSpace, rotation,
1396 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001397 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1398 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1399 if (rawOpaqueBufferSize <= 0) {
1400 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1401 return BAD_VALUE;
1402 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001403 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001404 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1405 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001406 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001407 newStream = new Camera3OutputStream(mNextStreamId,
1408 width, height, format, consumerUsage, dataSpace, rotation,
1409 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001410 } else if (streamSharing) {
1411 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1412 hasDeferredConsumer, width, height, format, consumerUsage,
1413 dataSpace, rotation, mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001415 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001416 width, height, format, dataSpace, rotation,
1417 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001419 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420
Zhijun He125684a2015-12-26 15:07:30 -08001421 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001422 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1423 * requires buffers to be statically allocated for internal static buffer registration, while
1424 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1425 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001426 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001427 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001428 newStream->setBufferManager(mBufferManager);
1429 }
1430
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001431 res = mOutputStreams.add(mNextStreamId, newStream);
1432 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001433 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 return res;
1435 }
1436
1437 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001438 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439
1440 // Continue captures if active at start
1441 if (wasActive) {
1442 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1443 res = configureStreamsLocked();
1444 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1446 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 return res;
1448 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001451 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001453}
1454
1455status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1456 ATRACE_CALL();
1457 (void)outputId; (void)id;
1458
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001460 return INVALID_OPERATION;
1461}
1462
1463
1464status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001465 uint32_t *width, uint32_t *height,
1466 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001468 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001470
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 switch (mStatus) {
1472 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001473 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return INVALID_OPERATION;
1475 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001476 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478 case STATUS_UNCONFIGURED:
1479 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 case STATUS_ACTIVE:
1481 // OK
1482 break;
1483 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001484 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 return INVALID_OPERATION;
1486 }
1487
1488 ssize_t idx = mOutputStreams.indexOfKey(id);
1489 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return idx;
1492 }
1493
1494 if (width) *width = mOutputStreams[idx]->getWidth();
1495 if (height) *height = mOutputStreams[idx]->getHeight();
1496 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001497 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499}
1500
1501status_t Camera3Device::setStreamTransform(int id,
1502 int transform) {
1503 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001506
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 switch (mStatus) {
1508 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return INVALID_OPERATION;
1511 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001512 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 case STATUS_UNCONFIGURED:
1515 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 case STATUS_ACTIVE:
1517 // OK
1518 break;
1519 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return INVALID_OPERATION;
1522 }
1523
1524 ssize_t idx = mOutputStreams.indexOfKey(id);
1525 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 CLOGE("Stream %d does not exist",
1527 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return BAD_VALUE;
1529 }
1530
1531 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001532}
1533
1534status_t Camera3Device::deleteStream(int id) {
1535 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 Mutex::Autolock l(mLock);
1538 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001539
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001540 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 // CameraDevice semantics require device to already be idle before
1543 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001545 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001546 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 }
1548
Igor Murashkin2fba5842013-04-22 14:03:54 -07001549 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001550 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 if (mInputStream != NULL && id == mInputStream->getId()) {
1552 deletedStream = mInputStream;
1553 mInputStream.clear();
1554 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001555 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return BAD_VALUE;
1558 }
Zhijun He5f446352014-01-22 09:49:33 -08001559 }
1560
1561 // Delete output stream or the output part of a bi-directional stream.
1562 if (outputStreamIdx != NAME_NOT_FOUND) {
1563 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 mOutputStreams.removeItem(id);
1565 }
1566
1567 // Free up the stream endpoint so that it can be used by some other stream
1568 res = deletedStream->disconnect();
1569 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001570 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 // fall through since we want to still list the stream as deleted.
1572 }
1573 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001574 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575
1576 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577}
1578
1579status_t Camera3Device::deleteReprocessStream(int id) {
1580 ATRACE_CALL();
1581 (void)id;
1582
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001583 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001584 return INVALID_OPERATION;
1585}
1586
Zhijun He1fa89992015-06-01 15:44:31 -07001587status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001588 ATRACE_CALL();
1589 ALOGV("%s: E", __FUNCTION__);
1590
1591 Mutex::Autolock il(mInterfaceLock);
1592 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001593
1594 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) {
1595 mNeedConfig = true;
1596 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
1597 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001598
1599 return configureStreamsLocked();
1600}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001601
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001602status_t Camera3Device::getInputBufferProducer(
1603 sp<IGraphicBufferProducer> *producer) {
1604 Mutex::Autolock il(mInterfaceLock);
1605 Mutex::Autolock l(mLock);
1606
1607 if (producer == NULL) {
1608 return BAD_VALUE;
1609 } else if (mInputStream == NULL) {
1610 return INVALID_OPERATION;
1611 }
1612
1613 return mInputStream->getInputBufferProducer(producer);
1614}
1615
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616status_t Camera3Device::createDefaultRequest(int templateId,
1617 CameraMetadata *request) {
1618 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001619 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001620
1621 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1622 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1623 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1624 return BAD_VALUE;
1625 }
1626
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628 Mutex::Autolock l(mLock);
1629
1630 switch (mStatus) {
1631 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001632 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 return INVALID_OPERATION;
1634 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001635 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 case STATUS_UNCONFIGURED:
1638 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 case STATUS_ACTIVE:
1640 // OK
1641 break;
1642 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001643 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001644 return INVALID_OPERATION;
1645 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646
Zhijun Hea1530f12014-09-14 12:44:20 -07001647 if (!mRequestTemplateCache[templateId].isEmpty()) {
1648 *request = mRequestTemplateCache[templateId];
1649 return OK;
1650 }
1651
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001652 camera_metadata_t *rawRequest;
1653 status_t res = mInterface->constructDefaultRequestSettings(
1654 (camera3_request_template_t) templateId, &rawRequest);
1655 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001656 ALOGI("%s: template %d is not supported on this camera device",
1657 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001658 return res;
1659 } else if (res != OK) {
1660 CLOGE("Unable to construct request template %d: %s (%d)",
1661 templateId, strerror(-res), res);
1662 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001663 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001664
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001665 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001666
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001667 // Derive some new keys for backward compatibility
1668 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1669 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1670 int32_t defaultBoost[1] = {100};
1671 mRequestTemplateCache[templateId].update(
1672 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1673 defaultBoost, 1);
1674 }
1675
1676 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677 return OK;
1678}
1679
1680status_t Camera3Device::waitUntilDrained() {
1681 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001682 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001683 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001684
Zhijun He69a37482014-03-23 18:44:49 -07001685 return waitUntilDrainedLocked();
1686}
1687
1688status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001689 switch (mStatus) {
1690 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001692 ALOGV("%s: Already idle", __FUNCTION__);
1693 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001694 case STATUS_CONFIGURED:
1695 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001696 case STATUS_ERROR:
1697 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001698 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001699 break;
1700 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001701 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001702 return INVALID_OPERATION;
1703 }
1704
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001705 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001707 if (res != OK) {
1708 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1709 res);
1710 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001711 return res;
1712}
1713
Ruben Brunk183f0562015-08-12 12:55:02 -07001714
1715void Camera3Device::internalUpdateStatusLocked(Status status) {
1716 mStatus = status;
1717 mRecentStatusUpdates.add(mStatus);
1718 mStatusChanged.broadcast();
1719}
1720
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001721// Pause to reconfigure
1722status_t Camera3Device::internalPauseAndWaitLocked() {
1723 mRequestThread->setPaused(true);
1724 mPauseStateNotify = true;
1725
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001726 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1728 if (res != OK) {
1729 SET_ERR_L("Can't idle device in %f seconds!",
1730 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001731 }
1732
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001733 return res;
1734}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001735
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001736// Resume after internalPauseAndWaitLocked
1737status_t Camera3Device::internalResumeLocked() {
1738 status_t res;
1739
1740 mRequestThread->setPaused(false);
1741
1742 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1743 if (res != OK) {
1744 SET_ERR_L("Can't transition to active in %f seconds!",
1745 kActiveTimeout/1e9);
1746 }
1747 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749}
1750
Ruben Brunk183f0562015-08-12 12:55:02 -07001751status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001752 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001753
1754 size_t startIndex = 0;
1755 if (mStatusWaiters == 0) {
1756 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1757 // this status list
1758 mRecentStatusUpdates.clear();
1759 } else {
1760 // If other threads are waiting on updates to this status list, set the position of the
1761 // first element that this list will check rather than clearing the list.
1762 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001763 }
1764
Ruben Brunk183f0562015-08-12 12:55:02 -07001765 mStatusWaiters++;
1766
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001767 bool stateSeen = false;
1768 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001769 if (active == (mStatus == STATUS_ACTIVE)) {
1770 // Desired state is current
1771 break;
1772 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773
1774 res = mStatusChanged.waitRelative(mLock, timeout);
1775 if (res != OK) break;
1776
Ruben Brunk183f0562015-08-12 12:55:02 -07001777 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1778 // transitions.
1779 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1780 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1781 __FUNCTION__);
1782
1783 // Encountered desired state since we began waiting
1784 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1786 stateSeen = true;
1787 break;
1788 }
1789 }
1790 } while (!stateSeen);
1791
Ruben Brunk183f0562015-08-12 12:55:02 -07001792 mStatusWaiters--;
1793
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001794 return res;
1795}
1796
1797
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001798status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001799 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001800 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001801
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001802 if (listener != NULL && mListener != NULL) {
1803 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1804 }
1805 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001806 mRequestThread->setNotificationListener(listener);
1807 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001808
1809 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001810}
1811
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001812bool Camera3Device::willNotify3A() {
1813 return false;
1814}
1815
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001816status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001817 status_t res;
1818 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001819
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001820 while (mResultQueue.empty()) {
1821 res = mResultSignal.waitRelative(mOutputLock, timeout);
1822 if (res == TIMED_OUT) {
1823 return res;
1824 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001825 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1826 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001827 return res;
1828 }
1829 }
1830 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001831}
1832
Jianing Weicb0652e2014-03-12 18:29:36 -07001833status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001834 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001835 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001837 if (mResultQueue.empty()) {
1838 return NOT_ENOUGH_DATA;
1839 }
1840
Jianing Weicb0652e2014-03-12 18:29:36 -07001841 if (frame == NULL) {
1842 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1843 return BAD_VALUE;
1844 }
1845
1846 CaptureResult &result = *(mResultQueue.begin());
1847 frame->mResultExtras = result.mResultExtras;
1848 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001849 mResultQueue.erase(mResultQueue.begin());
1850
1851 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001852}
1853
1854status_t Camera3Device::triggerAutofocus(uint32_t id) {
1855 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001857
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001858 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1859 // Mix-in this trigger into the next request and only the next request.
1860 RequestTrigger trigger[] = {
1861 {
1862 ANDROID_CONTROL_AF_TRIGGER,
1863 ANDROID_CONTROL_AF_TRIGGER_START
1864 },
1865 {
1866 ANDROID_CONTROL_AF_TRIGGER_ID,
1867 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001868 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001869 };
1870
1871 return mRequestThread->queueTrigger(trigger,
1872 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001873}
1874
1875status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1876 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001878
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001879 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1880 // Mix-in this trigger into the next request and only the next request.
1881 RequestTrigger trigger[] = {
1882 {
1883 ANDROID_CONTROL_AF_TRIGGER,
1884 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1885 },
1886 {
1887 ANDROID_CONTROL_AF_TRIGGER_ID,
1888 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001889 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001890 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001891
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001892 return mRequestThread->queueTrigger(trigger,
1893 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894}
1895
1896status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1897 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001900 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1901 // Mix-in this trigger into the next request and only the next request.
1902 RequestTrigger trigger[] = {
1903 {
1904 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1905 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1906 },
1907 {
1908 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1909 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001910 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001911 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001912
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001913 return mRequestThread->queueTrigger(trigger,
1914 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001915}
1916
1917status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1918 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1919 ATRACE_CALL();
1920 (void)reprocessStreamId; (void)buffer; (void)listener;
1921
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001922 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923 return INVALID_OPERATION;
1924}
1925
Jianing Weicb0652e2014-03-12 18:29:36 -07001926status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001927 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001928 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001930
Zhijun He7ef20392014-04-21 16:04:17 -07001931 {
1932 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001933 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001934 }
1935
Zhijun He491e3412013-12-27 10:57:44 -08001936 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001937 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001938 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001939 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001940 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001941 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001942 }
1943
1944 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001945}
1946
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001947status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001948 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1949}
1950
1951status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001952 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001953 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001954 Mutex::Autolock il(mInterfaceLock);
1955 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001956
1957 sp<Camera3StreamInterface> stream;
1958 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1959 if (outputStreamIdx == NAME_NOT_FOUND) {
1960 CLOGE("Stream %d does not exist", streamId);
1961 return BAD_VALUE;
1962 }
1963
1964 stream = mOutputStreams.editValueAt(outputStreamIdx);
1965
1966 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001967 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001968 return BAD_VALUE;
1969 }
1970
1971 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001972 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001973 return BAD_VALUE;
1974 }
1975
Ruben Brunkc78ac262015-08-13 17:58:46 -07001976 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001977}
1978
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001979status_t Camera3Device::tearDown(int streamId) {
1980 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001981 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001982 Mutex::Autolock il(mInterfaceLock);
1983 Mutex::Autolock l(mLock);
1984
1985 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1986 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001987 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001988 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001989 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001990 return NO_INIT;
1991 }
1992
1993 sp<Camera3StreamInterface> stream;
1994 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1995 if (outputStreamIdx == NAME_NOT_FOUND) {
1996 CLOGE("Stream %d does not exist", streamId);
1997 return BAD_VALUE;
1998 }
1999
2000 stream = mOutputStreams.editValueAt(outputStreamIdx);
2001
2002 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2003 CLOGE("Stream %d is a target of a in-progress request", streamId);
2004 return BAD_VALUE;
2005 }
2006
2007 return stream->tearDown();
2008}
2009
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002010status_t Camera3Device::addBufferListenerForStream(int streamId,
2011 wp<Camera3StreamBufferListener> listener) {
2012 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002013 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002014 Mutex::Autolock il(mInterfaceLock);
2015 Mutex::Autolock l(mLock);
2016
2017 sp<Camera3StreamInterface> stream;
2018 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2019 if (outputStreamIdx == NAME_NOT_FOUND) {
2020 CLOGE("Stream %d does not exist", streamId);
2021 return BAD_VALUE;
2022 }
2023
2024 stream = mOutputStreams.editValueAt(outputStreamIdx);
2025 stream->addBufferListener(listener);
2026
2027 return OK;
2028}
2029
Zhijun He204e3292014-07-14 17:09:23 -07002030uint32_t Camera3Device::getDeviceVersion() {
2031 ATRACE_CALL();
2032 Mutex::Autolock il(mInterfaceLock);
2033 return mDeviceVersion;
2034}
2035
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002036/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002037 * Methods called by subclasses
2038 */
2039
2040void Camera3Device::notifyStatus(bool idle) {
2041 {
2042 // Need mLock to safely update state and synchronize to current
2043 // state of methods in flight.
2044 Mutex::Autolock l(mLock);
2045 // We can get various system-idle notices from the status tracker
2046 // while starting up. Only care about them if we've actually sent
2047 // in some requests recently.
2048 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2049 return;
2050 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002051 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002052 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07002053 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002054
2055 // Skip notifying listener if we're doing some user-transparent
2056 // state changes
2057 if (mPauseStateNotify) return;
2058 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002059
2060 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002061 {
2062 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002063 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002064 }
2065 if (idle && listener != NULL) {
2066 listener->notifyIdle();
2067 }
2068}
2069
Zhijun He5d677d12016-05-29 16:52:39 -07002070status_t Camera3Device::setConsumerSurface(int streamId, sp<Surface> consumer) {
2071 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002072 ALOGV("%s: Camera %s: set consumer surface for stream %d", __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002073 Mutex::Autolock il(mInterfaceLock);
2074 Mutex::Autolock l(mLock);
2075
2076 if (consumer == nullptr) {
2077 CLOGE("Null consumer is passed!");
2078 return BAD_VALUE;
2079 }
2080
2081 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2082 if (idx == NAME_NOT_FOUND) {
2083 CLOGE("Stream %d is unknown", streamId);
2084 return idx;
2085 }
2086 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2087 status_t res = stream->setConsumer(consumer);
2088 if (res != OK) {
2089 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2090 return res;
2091 }
2092
Shuzhen Wang0129d522016-10-30 22:43:41 -07002093 if (stream->isConsumerConfigurationDeferred()) {
2094 if (!stream->isConfiguring()) {
2095 CLOGE("Stream %d was already fully configured.", streamId);
2096 return INVALID_OPERATION;
2097 }
Zhijun He5d677d12016-05-29 16:52:39 -07002098
Shuzhen Wang0129d522016-10-30 22:43:41 -07002099 res = stream->finishConfiguration();
2100 if (res != OK) {
2101 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2102 stream->getId(), strerror(-res), res);
2103 return res;
2104 }
Zhijun He5d677d12016-05-29 16:52:39 -07002105 }
2106
2107 return OK;
2108}
2109
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002111 * Camera3Device private methods
2112 */
2113
2114sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002115 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 ATRACE_CALL();
2117 status_t res;
2118
2119 sp<CaptureRequest> newRequest = new CaptureRequest;
2120 newRequest->mSettings = request;
2121
2122 camera_metadata_entry_t inputStreams =
2123 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2124 if (inputStreams.count > 0) {
2125 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002126 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002127 CLOGE("Request references unknown input stream %d",
2128 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 return NULL;
2130 }
2131 // Lazy completion of stream configuration (allocation/registration)
2132 // on first use
2133 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002134 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002136 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002137 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002138 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139 return NULL;
2140 }
2141 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002142 // Check if stream is being prepared
2143 if (mInputStream->isPreparing()) {
2144 CLOGE("Request references an input stream that's being prepared!");
2145 return NULL;
2146 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002147
2148 newRequest->mInputStream = mInputStream;
2149 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2150 }
2151
2152 camera_metadata_entry_t streams =
2153 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2154 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002155 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156 return NULL;
2157 }
2158
2159 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002160 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002161 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002162 CLOGE("Request references unknown stream %d",
2163 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164 return NULL;
2165 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002166 sp<Camera3OutputStreamInterface> stream =
2167 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002168
Zhijun He5d677d12016-05-29 16:52:39 -07002169 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002170 auto iter = surfaceMap.find(streams.data.i32[i]);
2171 if (iter != surfaceMap.end()) {
2172 const std::vector<size_t>& surfaces = iter->second;
2173 for (const auto& surface : surfaces) {
2174 if (stream->isConsumerConfigurationDeferred(surface)) {
2175 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2176 "due to deferred consumer", stream->getId(), surface);
2177 return NULL;
2178 }
2179 }
2180 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002181 }
2182
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002183 // Lazy completion of stream configuration (allocation/registration)
2184 // on first use
2185 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002186 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002187 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002188 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2189 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002190 return NULL;
2191 }
2192 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002193 // Check if stream is being prepared
2194 if (stream->isPreparing()) {
2195 CLOGE("Request references an output stream that's being prepared!");
2196 return NULL;
2197 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198
2199 newRequest->mOutputStreams.push(stream);
2200 }
2201 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002202 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002203
2204 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002205}
2206
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002207bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2208 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2209 Size size = mSupportedOpaqueInputSizes[i];
2210 if (size.width == width && size.height == height) {
2211 return true;
2212 }
2213 }
2214
2215 return false;
2216}
2217
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002218void Camera3Device::cancelStreamsConfigurationLocked() {
2219 int res = OK;
2220 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2221 res = mInputStream->cancelConfiguration();
2222 if (res != OK) {
2223 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2224 mInputStream->getId(), strerror(-res), res);
2225 }
2226 }
2227
2228 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2229 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2230 if (outputStream->isConfiguring()) {
2231 res = outputStream->cancelConfiguration();
2232 if (res != OK) {
2233 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2234 outputStream->getId(), strerror(-res), res);
2235 }
2236 }
2237 }
2238
2239 // Return state to that at start of call, so that future configures
2240 // properly clean things up
2241 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2242 mNeedConfig = true;
2243}
2244
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245status_t Camera3Device::configureStreamsLocked() {
2246 ATRACE_CALL();
2247 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002248
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002249 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002250 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002251 return INVALID_OPERATION;
2252 }
2253
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002254 if (!mNeedConfig) {
2255 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2256 return OK;
2257 }
2258
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002259 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2260 // adding a dummy stream instead.
2261 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2262 if (mOutputStreams.size() == 0) {
2263 addDummyStreamLocked();
2264 } else {
2265 tryRemoveDummyStreamLocked();
2266 }
2267
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002269 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270
2271 camera3_stream_configuration config;
Zhijun He1fa89992015-06-01 15:44:31 -07002272 config.operation_mode = mIsConstrainedHighSpeedConfiguration ?
2273 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE :
2274 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2276
2277 Vector<camera3_stream_t*> streams;
2278 streams.setCapacity(config.num_streams);
2279
2280 if (mInputStream != NULL) {
2281 camera3_stream_t *inputStream;
2282 inputStream = mInputStream->startConfiguration();
2283 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002284 CLOGE("Can't start input stream configuration");
2285 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002286 return INVALID_OPERATION;
2287 }
2288 streams.add(inputStream);
2289 }
2290
2291 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002292
2293 // Don't configure bidi streams twice, nor add them twice to the list
2294 if (mOutputStreams[i].get() ==
2295 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2296
2297 config.num_streams--;
2298 continue;
2299 }
2300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 camera3_stream_t *outputStream;
2302 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2303 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002304 CLOGE("Can't start output stream configuration");
2305 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 return INVALID_OPERATION;
2307 }
2308 streams.add(outputStream);
2309 }
2310
2311 config.streams = streams.editArray();
2312
2313 // Do the HAL configuration; will potentially touch stream
2314 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002315
2316 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002318 if (res == BAD_VALUE) {
2319 // HAL rejected this set of streams as unsupported, clean up config
2320 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002321 CLOGE("Set of requested inputs/outputs not supported by HAL");
2322 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002323 return BAD_VALUE;
2324 } else if (res != OK) {
2325 // Some other kind of error from configure_streams - this is not
2326 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002327 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2328 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002329 return res;
2330 }
2331
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002332 // Finish all stream configuration immediately.
2333 // TODO: Try to relax this later back to lazy completion, which should be
2334 // faster
2335
Igor Murashkin073f8572013-05-02 14:59:28 -07002336 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002337 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002338 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002339 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002340 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002341 cancelStreamsConfigurationLocked();
2342 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002343 }
2344 }
2345
2346 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002347 sp<Camera3OutputStreamInterface> outputStream =
2348 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002349 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002350 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002351 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002352 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002353 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002354 cancelStreamsConfigurationLocked();
2355 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002356 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002357 }
2358 }
2359
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 // Request thread needs to know to avoid using repeat-last-settings protocol
2361 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002362 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363
Zhijun He90f7c372016-08-16 16:19:43 -07002364 char value[PROPERTY_VALUE_MAX];
2365 property_get("camera.fifo.disable", value, "0");
2366 int32_t disableFifo = atoi(value);
2367 if (disableFifo != 1) {
2368 // Boost priority of request thread to SCHED_FIFO.
2369 pid_t requestThreadTid = mRequestThread->getTid();
2370 res = requestPriority(getpid(), requestThreadTid,
2371 kRequestThreadPriority, /*asynchronous*/ false);
2372 if (res != OK) {
2373 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2374 strerror(-res), res);
2375 } else {
2376 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2377 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002378 }
2379
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002380 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002382 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383
Ruben Brunk183f0562015-08-12 12:55:02 -07002384 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2385 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002386
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002387 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002388
Zhijun He0a210512014-07-24 13:45:15 -07002389 // tear down the deleted streams after configure streams.
2390 mDeletedStreams.clear();
2391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002393}
2394
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002395status_t Camera3Device::addDummyStreamLocked() {
2396 ATRACE_CALL();
2397 status_t res;
2398
2399 if (mDummyStreamId != NO_STREAM) {
2400 // Should never be adding a second dummy stream when one is already
2401 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002402 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2403 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002404 return INVALID_OPERATION;
2405 }
2406
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002407 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002408
2409 sp<Camera3OutputStreamInterface> dummyStream =
2410 new Camera3DummyStream(mNextStreamId);
2411
2412 res = mOutputStreams.add(mNextStreamId, dummyStream);
2413 if (res < 0) {
2414 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2415 return res;
2416 }
2417
2418 mDummyStreamId = mNextStreamId;
2419 mNextStreamId++;
2420
2421 return OK;
2422}
2423
2424status_t Camera3Device::tryRemoveDummyStreamLocked() {
2425 ATRACE_CALL();
2426 status_t res;
2427
2428 if (mDummyStreamId == NO_STREAM) return OK;
2429 if (mOutputStreams.size() == 1) return OK;
2430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002431 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002432
2433 // Ok, have a dummy stream and there's at least one other output stream,
2434 // so remove the dummy
2435
2436 sp<Camera3StreamInterface> deletedStream;
2437 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2438 if (outputStreamIdx == NAME_NOT_FOUND) {
2439 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2440 return INVALID_OPERATION;
2441 }
2442
2443 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2444 mOutputStreams.removeItemsAt(outputStreamIdx);
2445
2446 // Free up the stream endpoint so that it can be used by some other stream
2447 res = deletedStream->disconnect();
2448 if (res != OK) {
2449 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2450 // fall through since we want to still list the stream as deleted.
2451 }
2452 mDeletedStreams.add(deletedStream);
2453 mDummyStreamId = NO_STREAM;
2454
2455 return res;
2456}
2457
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002458void Camera3Device::setErrorState(const char *fmt, ...) {
2459 Mutex::Autolock l(mLock);
2460 va_list args;
2461 va_start(args, fmt);
2462
2463 setErrorStateLockedV(fmt, args);
2464
2465 va_end(args);
2466}
2467
2468void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2469 Mutex::Autolock l(mLock);
2470 setErrorStateLockedV(fmt, args);
2471}
2472
2473void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2474 va_list args;
2475 va_start(args, fmt);
2476
2477 setErrorStateLockedV(fmt, args);
2478
2479 va_end(args);
2480}
2481
2482void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002483 // Print out all error messages to log
2484 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002485 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002486
2487 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002488 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002489
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002490 mErrorCause = errorCause;
2491
2492 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002493 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002494
2495 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002496 sp<NotificationListener> listener = mListener.promote();
2497 if (listener != NULL) {
2498 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002499 CaptureResultExtras());
2500 }
2501
2502 // Save stack trace. View by dumping it later.
2503 CameraTraces::saveTrace();
2504 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506
2507/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002508 * In-flight request management
2509 */
2510
Jianing Weicb0652e2014-03-12 18:29:36 -07002511status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002512 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2513 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002514 ATRACE_CALL();
2515 Mutex::Autolock l(mInFlightLock);
2516
2517 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002518 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2519 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002520 if (res < 0) return res;
2521
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002522 if (mInFlightMap.size() == 1) {
2523 mStatusTracker->markComponentActive(mInFlightStatusId);
2524 }
2525
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002526 return OK;
2527}
2528
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002529void Camera3Device::returnOutputBuffers(
2530 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2531 nsecs_t timestamp) {
2532 for (size_t i = 0; i < numBuffers; i++)
2533 {
2534 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2535 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2536 // Note: stream may be deallocated at this point, if this buffer was
2537 // the last reference to it.
2538 if (res != OK) {
2539 ALOGE("Can't return buffer to its stream: %s (%d)",
2540 strerror(-res), res);
2541 }
2542 }
2543}
2544
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002545void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2546 mInFlightMap.removeItemsAt(idx, 1);
2547
2548 // Indicate idle inFlightMap to the status tracker
2549 if (mInFlightMap.size() == 0) {
2550 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2551 }
2552}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002553
2554void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2555
2556 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2557 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2558
2559 nsecs_t sensorTimestamp = request.sensorTimestamp;
2560 nsecs_t shutterTimestamp = request.shutterTimestamp;
2561
2562 // Check if it's okay to remove the request from InFlightMap:
2563 // In the case of a successful request:
2564 // all input and output buffers, all result metadata, shutter callback
2565 // arrived.
2566 // In the case of a unsuccessful request:
2567 // all input and output buffers arrived.
2568 if (request.numBuffersLeft == 0 &&
2569 (request.requestStatus != OK ||
2570 (request.haveResultMetadata && shutterTimestamp != 0))) {
2571 ATRACE_ASYNC_END("frame capture", frameNumber);
2572
2573 // Sanity check - if sensor timestamp matches shutter timestamp
2574 if (request.requestStatus == OK &&
2575 sensorTimestamp != shutterTimestamp) {
2576 SET_ERR("sensor timestamp (%" PRId64
2577 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2578 sensorTimestamp, frameNumber, shutterTimestamp);
2579 }
2580
2581 // for an unsuccessful request, it may have pending output buffers to
2582 // return.
2583 assert(request.requestStatus != OK ||
2584 request.pendingOutputBuffers.size() == 0);
2585 returnOutputBuffers(request.pendingOutputBuffers.array(),
2586 request.pendingOutputBuffers.size(), 0);
2587
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002588 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002589 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2590 }
2591
2592 // Sanity check - if we have too many in-flight frames, something has
2593 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002594 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002595 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002596 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2597 kInFlightWarnLimitHighSpeed) {
2598 CLOGE("In-flight list too large for high speed configuration: %zu",
2599 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002600 }
2601}
2602
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002603void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2604 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2605 if (result == nullptr) return;
2606
2607 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2608 (int32_t*)&frameNumber, 1) != OK) {
2609 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2610 return;
2611 }
2612
2613 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2614 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2615 return;
2616 }
2617
2618 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2619
2620 // Valid result, insert into queue
2621 List<CaptureResult>::iterator queuedResult =
2622 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2623 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2624 ", burstId = %" PRId32, __FUNCTION__,
2625 queuedResult->mResultExtras.requestId,
2626 queuedResult->mResultExtras.frameNumber,
2627 queuedResult->mResultExtras.burstId);
2628
2629 mResultSignal.signal();
2630}
2631
2632
2633void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2634 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2635 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2636 Mutex::Autolock l(mOutputLock);
2637
2638 CaptureResult captureResult;
2639 captureResult.mResultExtras = resultExtras;
2640 captureResult.mMetadata = partialResult;
2641
2642 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2643}
2644
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002645
2646void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2647 CaptureResultExtras &resultExtras,
2648 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002649 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002650 bool reprocess,
2651 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002652 if (pendingMetadata.isEmpty())
2653 return;
2654
2655 Mutex::Autolock l(mOutputLock);
2656
2657 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002658 if (reprocess) {
2659 if (frameNumber < mNextReprocessResultFrameNumber) {
2660 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002661 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002662 frameNumber, mNextReprocessResultFrameNumber);
2663 return;
2664 }
2665 mNextReprocessResultFrameNumber = frameNumber + 1;
2666 } else {
2667 if (frameNumber < mNextResultFrameNumber) {
2668 SET_ERR("Out-of-order capture result metadata submitted! "
2669 "(got frame number %d, expecting %d)",
2670 frameNumber, mNextResultFrameNumber);
2671 return;
2672 }
2673 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002674 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002675
2676 CaptureResult captureResult;
2677 captureResult.mResultExtras = resultExtras;
2678 captureResult.mMetadata = pendingMetadata;
2679
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002680 // Append any previous partials to form a complete result
2681 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2682 captureResult.mMetadata.append(collectedPartialResult);
2683 }
2684
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002685 // Derive some new keys for backward compaibility
2686 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2687 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2688 int32_t defaultBoost[1] = {100};
2689 captureResult.mMetadata.update(
2690 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2691 defaultBoost, 1);
2692 }
2693
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002694 captureResult.mMetadata.sort();
2695
2696 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002697 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2698 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002699 SET_ERR("No timestamp provided by HAL for frame %d!",
2700 frameNumber);
2701 return;
2702 }
2703
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002704 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2705 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2706
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002707 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002708}
2709
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002710/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711 * Camera HAL device callback methods
2712 */
2713
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002714void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002715 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002716
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002717 status_t res;
2718
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002719 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002720 if (result->result == NULL && result->num_output_buffers == 0 &&
2721 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002722 SET_ERR("No result data provided by HAL for frame %d",
2723 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002724 return;
2725 }
Zhijun He204e3292014-07-14 17:09:23 -07002726
2727 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2728 // partial_result to 1 when metadata is included in this result.
2729 if (!mUsePartialResult &&
2730 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2731 result->result != NULL &&
2732 result->partial_result != 1) {
2733 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2734 " if partial result is not supported",
2735 frameNumber, result->partial_result);
2736 return;
2737 }
2738
2739 bool isPartialResult = false;
2740 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002741 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002742 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002743
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002744 // Get shutter timestamp and resultExtras from list of in-flight requests,
2745 // where it was added by the shutter notification for this frame. If the
2746 // shutter timestamp isn't received yet, append the output buffers to the
2747 // in-flight request and they will be returned when the shutter timestamp
2748 // arrives. Update the in-flight status and remove the in-flight entry if
2749 // all result data and shutter timestamp have been received.
2750 nsecs_t shutterTimestamp = 0;
2751
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002752 {
2753 Mutex::Autolock l(mInFlightLock);
2754 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2755 if (idx == NAME_NOT_FOUND) {
2756 SET_ERR("Unknown frame number for capture result: %d",
2757 frameNumber);
2758 return;
2759 }
2760 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002761 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2762 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2763 ", partialResultCount = %d",
2764 __FUNCTION__, request.resultExtras.requestId,
2765 request.resultExtras.frameNumber, request.resultExtras.burstId,
2766 result->partial_result);
2767 // Always update the partial count to the latest one if it's not 0
2768 // (buffers only). When framework aggregates adjacent partial results
2769 // into one, the latest partial count will be used.
2770 if (result->partial_result != 0)
2771 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002772
2773 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002774 if (mUsePartialResult && result->result != NULL) {
2775 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2776 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2777 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2778 " the range of [1, %d] when metadata is included in the result",
2779 frameNumber, result->partial_result, mNumPartialResults);
2780 return;
2781 }
2782 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002783 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002784 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002785 }
Zhijun He204e3292014-07-14 17:09:23 -07002786 } else {
2787 camera_metadata_ro_entry_t partialResultEntry;
2788 res = find_camera_metadata_ro_entry(result->result,
2789 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2790 if (res != NAME_NOT_FOUND &&
2791 partialResultEntry.count > 0 &&
2792 partialResultEntry.data.u8[0] ==
2793 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2794 // A partial result. Flag this as such, and collect this
2795 // set of metadata into the in-flight entry.
2796 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002797 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002798 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002799 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002800 ANDROID_QUIRKS_PARTIAL_RESULT);
2801 }
2802 }
2803
2804 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002805 // Send partial capture result
2806 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2807 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002808 }
2809 }
2810
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002811 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002812 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002813
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002814 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002815 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002816 if (request.haveResultMetadata) {
2817 SET_ERR("Called multiple times with metadata for frame %d",
2818 frameNumber);
2819 return;
2820 }
Zhijun He204e3292014-07-14 17:09:23 -07002821 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002822 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002823 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002824 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002825 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002826 request.haveResultMetadata = true;
2827 }
2828
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002829 uint32_t numBuffersReturned = result->num_output_buffers;
2830 if (result->input_buffer != NULL) {
2831 if (hasInputBufferInRequest) {
2832 numBuffersReturned += 1;
2833 } else {
2834 ALOGW("%s: Input buffer should be NULL if there is no input"
2835 " buffer sent in the request",
2836 __FUNCTION__);
2837 }
2838 }
2839 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002840 if (request.numBuffersLeft < 0) {
2841 SET_ERR("Too many buffers returned for frame %d",
2842 frameNumber);
2843 return;
2844 }
2845
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002846 camera_metadata_ro_entry_t entry;
2847 res = find_camera_metadata_ro_entry(result->result,
2848 ANDROID_SENSOR_TIMESTAMP, &entry);
2849 if (res == OK && entry.count == 1) {
2850 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002851 }
2852
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002853 // If shutter event isn't received yet, append the output buffers to
2854 // the in-flight request. Otherwise, return the output buffers to
2855 // streams.
2856 if (shutterTimestamp == 0) {
2857 request.pendingOutputBuffers.appendArray(result->output_buffers,
2858 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002859 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002860 returnOutputBuffers(result->output_buffers,
2861 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002862 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002863
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002864 if (result->result != NULL && !isPartialResult) {
2865 if (shutterTimestamp == 0) {
2866 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002867 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002868 } else {
2869 CameraMetadata metadata;
2870 metadata = result->result;
2871 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002872 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2873 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002874 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002875 }
2876
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002877 removeInFlightRequestIfReadyLocked(idx);
2878 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002879
Zhijun Hef0d962a2014-06-30 10:24:11 -07002880 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002881 if (hasInputBufferInRequest) {
2882 Camera3Stream *stream =
2883 Camera3Stream::cast(result->input_buffer->stream);
2884 res = stream->returnInputBuffer(*(result->input_buffer));
2885 // Note: stream may be deallocated at this point, if this buffer was the
2886 // last reference to it.
2887 if (res != OK) {
2888 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2889 " its stream:%s (%d)", __FUNCTION__,
2890 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002891 }
2892 } else {
2893 ALOGW("%s: Input buffer should be NULL if there is no input"
2894 " buffer sent in the request, skipping input buffer return.",
2895 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002896 }
2897 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002898}
2899
2900void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002901 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002902 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002903 {
2904 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002905 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002906 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002907
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002908 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002909 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002910 return;
2911 }
2912
2913 switch (msg->type) {
2914 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002915 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002916 break;
2917 }
2918 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002919 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002920 break;
2921 }
2922 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002923 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002924 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002925 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002926}
2927
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002928void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002929 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002930
2931 // Map camera HAL error codes to ICameraDeviceCallback error codes
2932 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002933 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002934 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002935 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002936 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002937 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002938 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002939 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002940 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002941 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002942 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002943 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002944 };
2945
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002946 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002947 ((msg.error_code >= 0) &&
2948 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2949 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002950 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002951
2952 int streamId = 0;
2953 if (msg.error_stream != NULL) {
2954 Camera3Stream *stream =
2955 Camera3Stream::cast(msg.error_stream);
2956 streamId = stream->getId();
2957 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002958 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2959 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002960 streamId, msg.error_code);
2961
2962 CaptureResultExtras resultExtras;
2963 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002964 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965 // SET_ERR calls notifyError
2966 SET_ERR("Camera HAL reported serious device error");
2967 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002968 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2969 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2970 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002971 {
2972 Mutex::Autolock l(mInFlightLock);
2973 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2974 if (idx >= 0) {
2975 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2976 r.requestStatus = msg.error_code;
2977 resultExtras = r.resultExtras;
2978 } else {
2979 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002980 ALOGE("Camera %s: %s: cannot find in-flight request on "
2981 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002982 resultExtras.frameNumber);
2983 }
2984 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002985 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002986 if (listener != NULL) {
2987 listener->notifyError(errorCode, resultExtras);
2988 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002989 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002990 }
2991 break;
2992 default:
2993 // SET_ERR calls notifyError
2994 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2995 break;
2996 }
2997}
2998
2999void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003000 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003001 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003002
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003003 // Set timestamp for the request in the in-flight tracking
3004 // and get the request ID to send upstream
3005 {
3006 Mutex::Autolock l(mInFlightLock);
3007 idx = mInFlightMap.indexOfKey(msg.frame_number);
3008 if (idx >= 0) {
3009 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003010
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003011 // Verify ordering of shutter notifications
3012 {
3013 Mutex::Autolock l(mOutputLock);
3014 // TODO: need to track errors for tighter bounds on expected frame number.
3015 if (r.hasInputBuffer) {
3016 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3017 SET_ERR("Shutter notification out-of-order. Expected "
3018 "notification for frame %d, got frame %d",
3019 mNextReprocessShutterFrameNumber, msg.frame_number);
3020 return;
3021 }
3022 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3023 } else {
3024 if (msg.frame_number < mNextShutterFrameNumber) {
3025 SET_ERR("Shutter notification out-of-order. Expected "
3026 "notification for frame %d, got frame %d",
3027 mNextShutterFrameNumber, msg.frame_number);
3028 return;
3029 }
3030 mNextShutterFrameNumber = msg.frame_number + 1;
3031 }
3032 }
3033
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003034 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
3035 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003036 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
3037 // Call listener, if any
3038 if (listener != NULL) {
3039 listener->notifyShutter(r.resultExtras, msg.timestamp);
3040 }
3041
3042 r.shutterTimestamp = msg.timestamp;
3043
3044 // send pending result and buffers
3045 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003046 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003047 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003048 returnOutputBuffers(r.pendingOutputBuffers.array(),
3049 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3050 r.pendingOutputBuffers.clear();
3051
3052 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003053 }
3054 }
3055 if (idx < 0) {
3056 SET_ERR("Shutter notification for non-existent frame number %d",
3057 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003058 }
3059}
3060
3061
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003062CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003063 ALOGV("%s", __FUNCTION__);
3064
Igor Murashkin1e479c02013-09-06 16:55:14 -07003065 CameraMetadata retVal;
3066
3067 if (mRequestThread != NULL) {
3068 retVal = mRequestThread->getLatestRequest();
3069 }
3070
Igor Murashkin1e479c02013-09-06 16:55:14 -07003071 return retVal;
3072}
3073
Jianing Weicb0652e2014-03-12 18:29:36 -07003074
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003075void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3076 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3077 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3078}
3079
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003080/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003081 * HalInterface inner class methods
3082 */
3083
3084Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3085 mHal3Device(device) {}
3086
3087Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3088 mHal3Device(nullptr),
3089 mHidlSession(session) {}
3090
3091Camera3Device::HalInterface::HalInterface() :
3092 mHal3Device(nullptr) {}
3093
3094Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3095 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3096
3097bool Camera3Device::HalInterface::valid() {
3098 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3099}
3100
3101void Camera3Device::HalInterface::clear() {
3102 mHal3Device = nullptr;
3103 mHidlSession.clear();
3104}
3105
3106status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3107 camera3_request_template_t templateId,
3108 /*out*/ camera_metadata_t **requestTemplate) {
3109 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3110 if (!valid()) return INVALID_OPERATION;
3111 status_t res = OK;
3112
3113 if (mHal3Device != nullptr) {
3114 const camera_metadata *r;
3115 r = mHal3Device->ops->construct_default_request_settings(
3116 mHal3Device, templateId);
3117 if (r == nullptr) return BAD_VALUE;
3118 *requestTemplate = clone_camera_metadata(r);
3119 if (requestTemplate == nullptr) {
3120 ALOGE("%s: Unable to clone camera metadata received from HAL",
3121 __FUNCTION__);
3122 return INVALID_OPERATION;
3123 }
3124 } else {
3125 common::V1_0::Status status;
3126 RequestTemplate id;
3127 switch (templateId) {
3128 case CAMERA3_TEMPLATE_PREVIEW:
3129 id = RequestTemplate::PREVIEW;
3130 break;
3131 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3132 id = RequestTemplate::STILL_CAPTURE;
3133 break;
3134 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3135 id = RequestTemplate::VIDEO_RECORD;
3136 break;
3137 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3138 id = RequestTemplate::VIDEO_SNAPSHOT;
3139 break;
3140 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3141 id = RequestTemplate::ZERO_SHUTTER_LAG;
3142 break;
3143 case CAMERA3_TEMPLATE_MANUAL:
3144 id = RequestTemplate::MANUAL;
3145 break;
3146 default:
3147 // Unknown template ID
3148 return BAD_VALUE;
3149 }
3150 mHidlSession->constructDefaultRequestSettings(id,
3151 [&status, &requestTemplate]
3152 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3153 status = s;
3154 if (status == common::V1_0::Status::OK) {
3155 const camera_metadata *r =
3156 reinterpret_cast<const camera_metadata_t*>(request.data());
3157 size_t expectedSize = request.size();
3158 int ret = validate_camera_metadata_structure(r, &expectedSize);
3159 if (ret == OK) {
3160 *requestTemplate = clone_camera_metadata(r);
3161 if (*requestTemplate == nullptr) {
3162 ALOGE("%s: Unable to clone camera metadata received from HAL",
3163 __FUNCTION__);
3164 status = common::V1_0::Status::INTERNAL_ERROR;
3165 }
3166 } else {
3167 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3168 status = common::V1_0::Status::INTERNAL_ERROR;
3169 }
3170 }
3171 });
3172 res = CameraProviderManager::mapToStatusT(status);
3173 }
3174 return res;
3175}
3176
3177status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3178 ATRACE_NAME("CameraHal::configureStreams");
3179 if (!valid()) return INVALID_OPERATION;
3180 status_t res = OK;
3181
3182 if (mHal3Device != nullptr) {
3183 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3184 } else {
3185 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003186 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003187 StreamConfiguration requestedConfiguration;
3188 requestedConfiguration.streams.resize(config->num_streams);
3189 for (size_t i = 0; i < config->num_streams; i++) {
3190 Stream &dst = requestedConfiguration.streams[i];
3191 camera3_stream_t *src = config->streams[i];
3192
3193 int streamId = Camera3Stream::cast(src)->getId();
3194 StreamType streamType;
3195 switch (src->stream_type) {
3196 case CAMERA3_STREAM_OUTPUT:
3197 streamType = StreamType::OUTPUT;
3198 break;
3199 case CAMERA3_STREAM_INPUT:
3200 streamType = StreamType::INPUT;
3201 break;
3202 default:
3203 ALOGE("%s: Stream %d: Unsupported stream type %d",
3204 __FUNCTION__, streamId, config->streams[i]->stream_type);
3205 return BAD_VALUE;
3206 }
3207 dst.id = streamId;
3208 dst.streamType = streamType;
3209 dst.width = src->width;
3210 dst.height = src->height;
3211 dst.format = mapToPixelFormat(src->format);
3212 dst.usage = mapToConsumerUsage(src->usage);
3213 dst.dataSpace = mapToHidlDataspace(src->data_space);
3214 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003215
3216 activeStreams.insert(streamId);
3217 // Create Buffer ID map if necessary
3218 if (mBufferIdMaps.count(streamId) == 0) {
3219 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3220 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003221 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003222 // remove BufferIdMap for deleted streams
3223 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3224 int streamId = it->first;
3225 bool active = activeStreams.count(streamId) > 0;
3226 if (!active) {
3227 it = mBufferIdMaps.erase(it);
3228 } else {
3229 ++it;
3230 }
3231 }
3232
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003233 requestedConfiguration.operationMode = mapToStreamConfigurationMode(
3234 (camera3_stream_configuration_mode_t) config->operation_mode);
3235
3236 // Invoke configureStreams
3237
3238 HalStreamConfiguration finalConfiguration;
3239 common::V1_0::Status status;
3240 mHidlSession->configureStreams(requestedConfiguration,
3241 [&status, &finalConfiguration]
3242 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3243 finalConfiguration = halConfiguration;
3244 status = s;
3245 });
3246 if (status != common::V1_0::Status::OK ) {
3247 return CameraProviderManager::mapToStatusT(status);
3248 }
3249
3250 // And convert output stream configuration from HIDL
3251
3252 for (size_t i = 0; i < config->num_streams; i++) {
3253 camera3_stream_t *dst = config->streams[i];
3254 int streamId = Camera3Stream::cast(dst)->getId();
3255
3256 // Start scan at i, with the assumption that the stream order matches
3257 size_t realIdx = i;
3258 bool found = false;
3259 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3260 if (finalConfiguration.streams[realIdx].id == streamId) {
3261 found = true;
3262 break;
3263 }
3264 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3265 }
3266 if (!found) {
3267 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3268 __FUNCTION__, streamId);
3269 return INVALID_OPERATION;
3270 }
3271 HalStream &src = finalConfiguration.streams[realIdx];
3272
3273 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3274 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3275 if (dst->format != overrideFormat) {
3276 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3277 streamId, dst->format);
3278 }
3279 } else {
3280 // Override allowed with IMPLEMENTATION_DEFINED
3281 dst->format = overrideFormat;
3282 }
3283
3284 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3285 if (src.producerUsage != 0) {
3286 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3287 __FUNCTION__, streamId);
3288 return INVALID_OPERATION;
3289 }
3290 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3291 } else {
3292 // OUTPUT
3293 if (src.consumerUsage != 0) {
3294 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3295 __FUNCTION__, streamId);
3296 return INVALID_OPERATION;
3297 }
3298 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3299 }
3300 dst->max_buffers = src.maxBuffers;
3301 }
3302 }
3303 return res;
3304}
3305
3306status_t Camera3Device::HalInterface::processCaptureRequest(
3307 camera3_capture_request_t *request) {
3308 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003309 if (!valid()) return INVALID_OPERATION;
3310 status_t res = OK;
3311
3312 if (mHal3Device != nullptr) {
3313 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3314 } else {
3315 device::V3_2::CaptureRequest captureRequest;
3316 captureRequest.frameNumber = request->frame_number;
3317 std::vector<native_handle_t*> handlesCreated;
3318 // A null request settings maps to a size-0 CameraMetadata
3319 if (request->settings != nullptr) {
3320 captureRequest.settings.setToExternal(
3321 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3322 get_camera_metadata_size(request->settings));
3323 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003324
3325 {
3326 std::lock_guard<std::mutex> lock(mInflightLock);
3327 if (request->input_buffer != nullptr) {
3328 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003329 buffer_handle_t buf = *(request->input_buffer->buffer);
3330 auto pair = getBufferId(buf, streamId);
3331 bool isNewBuffer = pair.first;
3332 uint64_t bufferId = pair.second;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003333 captureRequest.inputBuffer.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003334 captureRequest.inputBuffer.bufferId = bufferId;
3335 captureRequest.inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003336 captureRequest.inputBuffer.status = BufferStatus::OK;
3337 native_handle_t *acquireFence = nullptr;
3338 if (request->input_buffer->acquire_fence != -1) {
3339 acquireFence = native_handle_create(1,0);
3340 acquireFence->data[0] = request->input_buffer->acquire_fence;
3341 handlesCreated.push_back(acquireFence);
3342 }
3343 captureRequest.inputBuffer.acquireFence = acquireFence;
3344 captureRequest.inputBuffer.releaseFence = nullptr;
3345
3346 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003347 request->input_buffer->buffer,
3348 request->input_buffer->acquire_fence);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003349 } else {
3350 captureRequest.inputBuffer.streamId = -1;
3351 captureRequest.inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003352 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003353
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003354 captureRequest.outputBuffers.resize(request->num_output_buffers);
3355 for (size_t i = 0; i < request->num_output_buffers; i++) {
3356 const camera3_stream_buffer_t *src = request->output_buffers + i;
3357 StreamBuffer &dst = captureRequest.outputBuffers[i];
3358 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003359 buffer_handle_t buf = *(src->buffer);
3360 auto pair = getBufferId(buf, streamId);
3361 bool isNewBuffer = pair.first;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003362 dst.streamId = streamId;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003363 dst.bufferId = pair.second;
3364 dst.buffer = isNewBuffer ? buf : nullptr;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003365 dst.status = BufferStatus::OK;
3366 native_handle_t *acquireFence = nullptr;
3367 if (src->acquire_fence != -1) {
3368 acquireFence = native_handle_create(1,0);
3369 acquireFence->data[0] = src->acquire_fence;
3370 handlesCreated.push_back(acquireFence);
3371 }
3372 dst.acquireFence = acquireFence;
3373 dst.releaseFence = nullptr;
3374
3375 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003376 src->buffer, src->acquire_fence);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003377 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003378 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003379 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3380
3381 for (auto& handle : handlesCreated) {
3382 native_handle_delete(handle);
3383 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003384 res = CameraProviderManager::mapToStatusT(status);
3385 }
3386 return res;
3387}
3388
3389status_t Camera3Device::HalInterface::flush() {
3390 ATRACE_NAME("CameraHal::flush");
3391 if (!valid()) return INVALID_OPERATION;
3392 status_t res = OK;
3393
3394 if (mHal3Device != nullptr) {
3395 res = mHal3Device->ops->flush(mHal3Device);
3396 } else {
3397 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3398 }
3399 return res;
3400}
3401
3402status_t Camera3Device::HalInterface::dump(int fd) {
3403 ATRACE_NAME("CameraHal::dump");
3404 if (!valid()) return INVALID_OPERATION;
3405 status_t res = OK;
3406
3407 if (mHal3Device != nullptr) {
3408 mHal3Device->ops->dump(mHal3Device, fd);
3409 } else {
3410 // Handled by CameraProviderManager::dump
3411 }
3412 return res;
3413}
3414
3415status_t Camera3Device::HalInterface::close() {
3416 ATRACE_NAME("CameraHal::close()");
3417 if (!valid()) return INVALID_OPERATION;
3418 status_t res = OK;
3419
3420 if (mHal3Device != nullptr) {
3421 mHal3Device->common.close(&mHal3Device->common);
3422 } else {
3423 mHidlSession->close();
3424 }
3425 return res;
3426}
3427
3428status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003429 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003431 auto pair = std::make_pair(buffer, acquireFence);
3432 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003433 return OK;
3434}
3435
3436status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003437 int32_t frameNumber, int32_t streamId,
3438 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003439 std::lock_guard<std::mutex> lock(mInflightLock);
3440
3441 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3442 auto it = mInflightBufferMap.find(key);
3443 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003444 auto pair = it->second;
3445 *buffer = pair.first;
3446 int acquireFence = pair.second;
3447 if (acquireFence > 0) {
3448 ::close(acquireFence);
3449 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003450 mInflightBufferMap.erase(it);
3451 return OK;
3452}
3453
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003454std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3455 const buffer_handle_t& buf, int streamId) {
3456 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3457
3458 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3459 auto it = bIdMap.find(buf);
3460 if (it == bIdMap.end()) {
3461 bIdMap[buf] = mNextBufferId++;
3462 return std::make_pair(true, mNextBufferId - 1);
3463 } else {
3464 return std::make_pair(false, it->second);
3465 }
3466}
3467
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003468/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003469 * RequestThread inner class methods
3470 */
3471
3472Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003473 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003474 HalInterface* interface,
3475 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003476 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003477 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003478 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003479 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003480 mInterface(interface),
3481 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003482 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003483 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003484 mReconfigured(false),
3485 mDoPause(false),
3486 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003487 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003488 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003489 mCurrentAfTriggerId(0),
3490 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003491 mRepeatingLastFrameNumber(
3492 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003493 mAeLockAvailable(aeLockAvailable),
3494 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003495 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003496}
3497
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003498Camera3Device::RequestThread::~RequestThread() {}
3499
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003500void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003501 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003502 Mutex::Autolock l(mRequestLock);
3503 mListener = listener;
3504}
3505
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003506void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003507 Mutex::Autolock l(mRequestLock);
3508 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003509 // Prepare video stream for high speed recording.
3510 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003511}
3512
Jianing Wei90e59c92014-03-12 18:29:36 -07003513status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003514 List<sp<CaptureRequest> > &requests,
3515 /*out*/
3516 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003517 Mutex::Autolock l(mRequestLock);
3518 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3519 ++it) {
3520 mRequestQueue.push_back(*it);
3521 }
3522
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003523 if (lastFrameNumber != NULL) {
3524 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3525 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3526 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3527 *lastFrameNumber);
3528 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003529
Jianing Wei90e59c92014-03-12 18:29:36 -07003530 unpauseForNewRequests();
3531
3532 return OK;
3533}
3534
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003535
3536status_t Camera3Device::RequestThread::queueTrigger(
3537 RequestTrigger trigger[],
3538 size_t count) {
3539
3540 Mutex::Autolock l(mTriggerMutex);
3541 status_t ret;
3542
3543 for (size_t i = 0; i < count; ++i) {
3544 ret = queueTriggerLocked(trigger[i]);
3545
3546 if (ret != OK) {
3547 return ret;
3548 }
3549 }
3550
3551 return OK;
3552}
3553
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003554const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3555 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003556 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003557 if (d != nullptr) return d->mId;
3558 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003559}
3560
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003561status_t Camera3Device::RequestThread::queueTriggerLocked(
3562 RequestTrigger trigger) {
3563
3564 uint32_t tag = trigger.metadataTag;
3565 ssize_t index = mTriggerMap.indexOfKey(tag);
3566
3567 switch (trigger.getTagType()) {
3568 case TYPE_BYTE:
3569 // fall-through
3570 case TYPE_INT32:
3571 break;
3572 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003573 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3574 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003575 return INVALID_OPERATION;
3576 }
3577
3578 /**
3579 * Collect only the latest trigger, since we only have 1 field
3580 * in the request settings per trigger tag, and can't send more than 1
3581 * trigger per request.
3582 */
3583 if (index != NAME_NOT_FOUND) {
3584 mTriggerMap.editValueAt(index) = trigger;
3585 } else {
3586 mTriggerMap.add(tag, trigger);
3587 }
3588
3589 return OK;
3590}
3591
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003592status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003593 const RequestList &requests,
3594 /*out*/
3595 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003596 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003597 if (lastFrameNumber != NULL) {
3598 *lastFrameNumber = mRepeatingLastFrameNumber;
3599 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003600 mRepeatingRequests.clear();
3601 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3602 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003603
3604 unpauseForNewRequests();
3605
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003607 return OK;
3608}
3609
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003610bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003611 if (mRepeatingRequests.empty()) {
3612 return false;
3613 }
3614 int32_t requestId = requestIn->mResultExtras.requestId;
3615 const RequestList &repeatRequests = mRepeatingRequests;
3616 // All repeating requests are guaranteed to have same id so only check first quest
3617 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3618 return (firstRequest->mResultExtras.requestId == requestId);
3619}
3620
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003621status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003622 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003623 return clearRepeatingRequestsLocked(lastFrameNumber);
3624
3625}
3626
3627status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003628 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003629 if (lastFrameNumber != NULL) {
3630 *lastFrameNumber = mRepeatingLastFrameNumber;
3631 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003632 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003633 return OK;
3634}
3635
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003636status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003638 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003639 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003640
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003641 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003642
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003643 // Send errors for all requests pending in the request queue, including
3644 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003645 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003646 if (listener != NULL) {
3647 for (RequestList::iterator it = mRequestQueue.begin();
3648 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003649 // Abort the input buffers for reprocess requests.
3650 if ((*it)->mInputStream != NULL) {
3651 camera3_stream_buffer_t inputBuffer;
3652 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3653 if (res != OK) {
3654 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3655 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3656 } else {
3657 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3658 if (res != OK) {
3659 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3660 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3661 }
3662 }
3663 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003664 // Set the frame number this request would have had, if it
3665 // had been submitted; this frame number will not be reused.
3666 // The requestId and burstId fields were set when the request was
3667 // submitted originally (in convertMetadataListToRequestListLocked)
3668 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003669 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003670 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003671 }
3672 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003673 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003674
3675 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003676 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003677 if (lastFrameNumber != NULL) {
3678 *lastFrameNumber = mRepeatingLastFrameNumber;
3679 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003680 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003681 return OK;
3682}
3683
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003684status_t Camera3Device::RequestThread::flush() {
3685 ATRACE_CALL();
3686 Mutex::Autolock l(mFlushLock);
3687
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003688 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3689 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003690 }
3691
3692 return -ENOTSUP;
3693}
3694
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003695void Camera3Device::RequestThread::setPaused(bool paused) {
3696 Mutex::Autolock l(mPauseLock);
3697 mDoPause = paused;
3698 mDoPauseSignal.signal();
3699}
3700
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003701status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3702 int32_t requestId, nsecs_t timeout) {
3703 Mutex::Autolock l(mLatestRequestMutex);
3704 status_t res;
3705 while (mLatestRequestId != requestId) {
3706 nsecs_t startTime = systemTime();
3707
3708 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3709 if (res != OK) return res;
3710
3711 timeout -= (systemTime() - startTime);
3712 }
3713
3714 return OK;
3715}
3716
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003717void Camera3Device::RequestThread::requestExit() {
3718 // Call parent to set up shutdown
3719 Thread::requestExit();
3720 // The exit from any possible waits
3721 mDoPauseSignal.signal();
3722 mRequestSignal.signal();
3723}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003724
Chien-Yu Chend196d612015-06-22 19:49:01 -07003725
3726/**
3727 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3728 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3729 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3730 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3731 * request.
3732 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003733void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003734 request->mAeTriggerCancelOverride.applyAeLock = false;
3735 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3736
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003737 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003738 return;
3739 }
3740
3741 camera_metadata_entry_t aePrecaptureTrigger =
3742 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3743 if (aePrecaptureTrigger.count > 0 &&
3744 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3745 // Always override CANCEL to IDLE
3746 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3747 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3748 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3749 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3750 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3751
3752 if (mAeLockAvailable == true) {
3753 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3754 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3755 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3756 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3757 request->mAeTriggerCancelOverride.applyAeLock = true;
3758 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3759 }
3760 }
3761 }
3762}
3763
3764/**
3765 * Override result metadata for cancelling AE precapture trigger applied in
3766 * handleAePrecaptureCancelRequest().
3767 */
3768void Camera3Device::overrideResultForPrecaptureCancel(
3769 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3770 if (aeTriggerCancelOverride.applyAeLock) {
3771 // Only devices <= v3.2 should have this override
3772 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3773 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3774 }
3775
3776 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3777 // Only devices <= v3.2 should have this override
3778 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3779 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3780 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3781 }
3782}
3783
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003784void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003785 bool surfaceAbandoned = false;
3786 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003787 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003788 {
3789 Mutex::Autolock l(mRequestLock);
3790 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3791 // repeating requests.
3792 for (const auto& request : mRepeatingRequests) {
3793 for (const auto& s : request->mOutputStreams) {
3794 if (s->isAbandoned()) {
3795 surfaceAbandoned = true;
3796 clearRepeatingRequestsLocked(&lastFrameNumber);
3797 break;
3798 }
3799 }
3800 if (surfaceAbandoned) {
3801 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003802 }
3803 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003804 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003805 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003806
3807 if (listener != NULL && surfaceAbandoned) {
3808 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003809 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003810}
3811
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003812bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003813 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003814 status_t res;
3815
3816 // Handle paused state.
3817 if (waitIfPaused()) {
3818 return true;
3819 }
3820
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003821 // Wait for the next batch of requests.
3822 waitForNextRequestBatch();
3823 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003824 return true;
3825 }
3826
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003827 // Get the latest request ID, if any
3828 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003829 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003830 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003831 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003832 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003833 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003834 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3835 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003836 }
3837
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003838 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003839 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003840 if (res == TIMED_OUT) {
3841 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003842 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003843 // Check if any stream is abandoned.
3844 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003845 return true;
3846 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003847 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003848 return false;
3849 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003850
Zhijun Hecc27e112013-10-03 16:12:43 -07003851 // Inform waitUntilRequestProcessed thread of a new request ID
3852 {
3853 Mutex::Autolock al(mLatestRequestMutex);
3854
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003855 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003856 mLatestRequestSignal.signal();
3857 }
3858
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003859 // Submit a batch of requests to HAL.
3860 // Use flush lock only when submitting multilple requests in a batch.
3861 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3862 // which may take a long time to finish so synchronizing flush() and
3863 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3864 // For now, only synchronize for high speed recording and we should figure something out for
3865 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003866 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003867
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003868 if (useFlushLock) {
3869 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003870 }
3871
Zhijun Hef0645c12016-08-02 00:58:11 -07003872 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003873 mNextRequests.size());
3874 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003875 // Submit request and block until ready for next one
3876 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003877 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003878
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003879 if (res != OK) {
3880 // Should only get a failure here for malformed requests or device-level
3881 // errors, so consider all errors fatal. Bad metadata failures should
3882 // come through notify.
3883 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3884 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3885 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003886 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003887 if (useFlushLock) {
3888 mFlushLock.unlock();
3889 }
3890 return false;
3891 }
3892
3893 // Mark that the request has be submitted successfully.
3894 nextRequest.submitted = true;
3895
3896 // Update the latest request sent to HAL
3897 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3898 Mutex::Autolock al(mLatestRequestMutex);
3899
3900 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3901 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003902
3903 sp<Camera3Device> parent = mParent.promote();
3904 if (parent != NULL) {
3905 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3906 0, mLatestRequest);
3907 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003908 }
3909
3910 if (nextRequest.halRequest.settings != NULL) {
3911 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3912 }
3913
3914 // Remove any previously queued triggers (after unlock)
3915 res = removeTriggers(mPrevRequest);
3916 if (res != OK) {
3917 SET_ERR("RequestThread: Unable to remove triggers "
3918 "(capture request %d, HAL device: %s (%d)",
3919 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003920 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003921 if (useFlushLock) {
3922 mFlushLock.unlock();
3923 }
3924 return false;
3925 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003926 }
3927
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003928 if (useFlushLock) {
3929 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003930 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003931
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003932 // Unset as current request
3933 {
3934 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003935 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003936 }
3937
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003938 return true;
3939}
3940
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003941status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003942 ATRACE_CALL();
3943
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003944 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003945 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3946 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3947 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3948
3949 // Prepare a request to HAL
3950 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3951
3952 // Insert any queued triggers (before metadata is locked)
3953 status_t res = insertTriggers(captureRequest);
3954
3955 if (res < 0) {
3956 SET_ERR("RequestThread: Unable to insert triggers "
3957 "(capture request %d, HAL device: %s (%d)",
3958 halRequest->frame_number, strerror(-res), res);
3959 return INVALID_OPERATION;
3960 }
3961 int triggerCount = res;
3962 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3963 mPrevTriggers = triggerCount;
3964
3965 // If the request is the same as last, or we had triggers last time
3966 if (mPrevRequest != captureRequest || triggersMixedIn) {
3967 /**
3968 * HAL workaround:
3969 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3970 */
3971 res = addDummyTriggerIds(captureRequest);
3972 if (res != OK) {
3973 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3974 "(capture request %d, HAL device: %s (%d)",
3975 halRequest->frame_number, strerror(-res), res);
3976 return INVALID_OPERATION;
3977 }
3978
3979 /**
3980 * The request should be presorted so accesses in HAL
3981 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3982 */
3983 captureRequest->mSettings.sort();
3984 halRequest->settings = captureRequest->mSettings.getAndLock();
3985 mPrevRequest = captureRequest;
3986 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3987
3988 IF_ALOGV() {
3989 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3990 find_camera_metadata_ro_entry(
3991 halRequest->settings,
3992 ANDROID_CONTROL_AF_TRIGGER,
3993 &e
3994 );
3995 if (e.count > 0) {
3996 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3997 __FUNCTION__,
3998 halRequest->frame_number,
3999 e.data.u8[0]);
4000 }
4001 }
4002 } else {
4003 // leave request.settings NULL to indicate 'reuse latest given'
4004 ALOGVV("%s: Request settings are REUSED",
4005 __FUNCTION__);
4006 }
4007
4008 uint32_t totalNumBuffers = 0;
4009
4010 // Fill in buffers
4011 if (captureRequest->mInputStream != NULL) {
4012 halRequest->input_buffer = &captureRequest->mInputBuffer;
4013 totalNumBuffers += 1;
4014 } else {
4015 halRequest->input_buffer = NULL;
4016 }
4017
4018 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4019 captureRequest->mOutputStreams.size());
4020 halRequest->output_buffers = outputBuffers->array();
4021 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004022 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
4023
4024 // Prepare video buffers for high speed recording on the first video request.
4025 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4026 // Only try to prepare video stream on the first video request.
4027 mPrepareVideoStream = false;
4028
4029 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4030 while (res == NOT_ENOUGH_DATA) {
4031 res = outputStream->prepareNextBuffer();
4032 }
4033 if (res != OK) {
4034 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4035 __FUNCTION__, strerror(-res), res);
4036 outputStream->cancelPrepare();
4037 }
4038 }
4039
4040 res = outputStream->getBuffer(&outputBuffers->editItemAt(i));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004041 if (res != OK) {
4042 // Can't get output buffer from gralloc queue - this could be due to
4043 // abandoned queue or other consumer misbehavior, so not a fatal
4044 // error
4045 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4046 " %s (%d)", strerror(-res), res);
4047
4048 return TIMED_OUT;
4049 }
4050 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004051
4052 res = outputStream->notifyRequestedSurfaces(halRequest->frame_number,
4053 captureRequest->mOutputSurfaces[i]);
4054 if (res != OK) {
4055 ALOGE("RequestThread: Cannot register output surfaces: %s (%d)",
4056 strerror(-res), res);
4057 return INVALID_OPERATION;
4058 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 }
4060 totalNumBuffers += halRequest->num_output_buffers;
4061
4062 // Log request in the in-flight queue
4063 sp<Camera3Device> parent = mParent.promote();
4064 if (parent == NULL) {
4065 // Should not happen, and nowhere to send errors to, so just log it
4066 CLOGE("RequestThread: Parent is gone");
4067 return INVALID_OPERATION;
4068 }
4069 res = parent->registerInFlight(halRequest->frame_number,
4070 totalNumBuffers, captureRequest->mResultExtras,
4071 /*hasInput*/halRequest->input_buffer != NULL,
4072 captureRequest->mAeTriggerCancelOverride);
4073 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4074 ", burstId = %" PRId32 ".",
4075 __FUNCTION__,
4076 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4077 captureRequest->mResultExtras.burstId);
4078 if (res != OK) {
4079 SET_ERR("RequestThread: Unable to register new in-flight request:"
4080 " %s (%d)", strerror(-res), res);
4081 return INVALID_OPERATION;
4082 }
4083 }
4084
4085 return OK;
4086}
4087
Igor Murashkin1e479c02013-09-06 16:55:14 -07004088CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4089 Mutex::Autolock al(mLatestRequestMutex);
4090
4091 ALOGV("RequestThread::%s", __FUNCTION__);
4092
4093 return mLatestRequest;
4094}
4095
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004096bool Camera3Device::RequestThread::isStreamPending(
4097 sp<Camera3StreamInterface>& stream) {
4098 Mutex::Autolock l(mRequestLock);
4099
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004101 if (!nextRequest.submitted) {
4102 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4103 if (stream == s) return true;
4104 }
4105 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004106 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004107 }
4108
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004109 for (const auto& request : mRequestQueue) {
4110 for (const auto& s : request->mOutputStreams) {
4111 if (stream == s) return true;
4112 }
4113 if (stream == request->mInputStream) return true;
4114 }
4115
4116 for (const auto& request : mRepeatingRequests) {
4117 for (const auto& s : request->mOutputStreams) {
4118 if (stream == s) return true;
4119 }
4120 if (stream == request->mInputStream) return true;
4121 }
4122
4123 return false;
4124}
Jianing Weicb0652e2014-03-12 18:29:36 -07004125
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004126void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4127 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004128 return;
4129 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004130
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004131 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132 // Skip the ones that have been submitted successfully.
4133 if (nextRequest.submitted) {
4134 continue;
4135 }
4136
4137 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4138 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4139 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4140
4141 if (halRequest->settings != NULL) {
4142 captureRequest->mSettings.unlock(halRequest->settings);
4143 }
4144
4145 if (captureRequest->mInputStream != NULL) {
4146 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4147 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4148 }
4149
4150 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4151 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4152 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4153 }
4154
4155 if (sendRequestError) {
4156 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004157 sp<NotificationListener> listener = mListener.promote();
4158 if (listener != NULL) {
4159 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004160 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004161 captureRequest->mResultExtras);
4162 }
4163 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004164
4165 // Remove yet-to-be submitted inflight request from inflightMap
4166 {
4167 sp<Camera3Device> parent = mParent.promote();
4168 if (parent != NULL) {
4169 Mutex::Autolock l(parent->mInFlightLock);
4170 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4171 if (idx >= 0) {
4172 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4173 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4174 parent->removeInFlightMapEntryLocked(idx);
4175 }
4176 }
4177 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004178 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004179
4180 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004181 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004182}
4183
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004184void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004185 // Optimized a bit for the simple steady-state case (single repeating
4186 // request), to avoid putting that request in the queue temporarily.
4187 Mutex::Autolock l(mRequestLock);
4188
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004189 assert(mNextRequests.empty());
4190
4191 NextRequest nextRequest;
4192 nextRequest.captureRequest = waitForNextRequestLocked();
4193 if (nextRequest.captureRequest == nullptr) {
4194 return;
4195 }
4196
4197 nextRequest.halRequest = camera3_capture_request_t();
4198 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004199 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004200
4201 // Wait for additional requests
4202 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4203
4204 for (size_t i = 1; i < batchSize; i++) {
4205 NextRequest additionalRequest;
4206 additionalRequest.captureRequest = waitForNextRequestLocked();
4207 if (additionalRequest.captureRequest == nullptr) {
4208 break;
4209 }
4210
4211 additionalRequest.halRequest = camera3_capture_request_t();
4212 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004213 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004214 }
4215
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004216 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004217 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004218 mNextRequests.size(), batchSize);
4219 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004220 }
4221
4222 return;
4223}
4224
4225sp<Camera3Device::CaptureRequest>
4226 Camera3Device::RequestThread::waitForNextRequestLocked() {
4227 status_t res;
4228 sp<CaptureRequest> nextRequest;
4229
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004230 while (mRequestQueue.empty()) {
4231 if (!mRepeatingRequests.empty()) {
4232 // Always atomically enqueue all requests in a repeating request
4233 // list. Guarantees a complete in-sequence set of captures to
4234 // application.
4235 const RequestList &requests = mRepeatingRequests;
4236 RequestList::const_iterator firstRequest =
4237 requests.begin();
4238 nextRequest = *firstRequest;
4239 mRequestQueue.insert(mRequestQueue.end(),
4240 ++firstRequest,
4241 requests.end());
4242 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004243
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004244 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004245
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004246 break;
4247 }
4248
4249 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4250
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004251 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4252 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004253 Mutex::Autolock pl(mPauseLock);
4254 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004255 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004257 // Let the tracker know
4258 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4259 if (statusTracker != 0) {
4260 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4261 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004262 }
4263 // Stop waiting for now and let thread management happen
4264 return NULL;
4265 }
4266 }
4267
4268 if (nextRequest == NULL) {
4269 // Don't have a repeating request already in hand, so queue
4270 // must have an entry now.
4271 RequestList::iterator firstRequest =
4272 mRequestQueue.begin();
4273 nextRequest = *firstRequest;
4274 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004275 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4276 sp<NotificationListener> listener = mListener.promote();
4277 if (listener != NULL) {
4278 listener->notifyRequestQueueEmpty();
4279 }
4280 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004281 }
4282
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004283 // In case we've been unpaused by setPaused clearing mDoPause, need to
4284 // update internal pause state (capture/setRepeatingRequest unpause
4285 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004286 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004287 if (mPaused) {
4288 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4289 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4290 if (statusTracker != 0) {
4291 statusTracker->markComponentActive(mStatusId);
4292 }
4293 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294 mPaused = false;
4295
4296 // Check if we've reconfigured since last time, and reset the preview
4297 // request if so. Can't use 'NULL request == repeat' across configure calls.
4298 if (mReconfigured) {
4299 mPrevRequest.clear();
4300 mReconfigured = false;
4301 }
4302
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004303 if (nextRequest != NULL) {
4304 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004305 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4306 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004307
4308 // Since RequestThread::clear() removes buffers from the input stream,
4309 // get the right buffer here before unlocking mRequestLock
4310 if (nextRequest->mInputStream != NULL) {
4311 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4312 if (res != OK) {
4313 // Can't get input buffer from gralloc queue - this could be due to
4314 // disconnected queue or other producer misbehavior, so not a fatal
4315 // error
4316 ALOGE("%s: Can't get input buffer, skipping request:"
4317 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004318
4319 sp<NotificationListener> listener = mListener.promote();
4320 if (listener != NULL) {
4321 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004322 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004323 nextRequest->mResultExtras);
4324 }
4325 return NULL;
4326 }
4327 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004328 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004329
4330 handleAePrecaptureCancelRequest(nextRequest);
4331
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004332 return nextRequest;
4333}
4334
4335bool Camera3Device::RequestThread::waitIfPaused() {
4336 status_t res;
4337 Mutex::Autolock l(mPauseLock);
4338 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004339 if (mPaused == false) {
4340 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004341 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4342 // Let the tracker know
4343 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4344 if (statusTracker != 0) {
4345 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4346 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004348
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004349 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004350 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 return true;
4352 }
4353 }
4354 // We don't set mPaused to false here, because waitForNextRequest needs
4355 // to further manage the paused state in case of starvation.
4356 return false;
4357}
4358
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004359void Camera3Device::RequestThread::unpauseForNewRequests() {
4360 // With work to do, mark thread as unpaused.
4361 // If paused by request (setPaused), don't resume, to avoid
4362 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004363 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004364 Mutex::Autolock p(mPauseLock);
4365 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004366 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4367 if (mPaused) {
4368 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4369 if (statusTracker != 0) {
4370 statusTracker->markComponentActive(mStatusId);
4371 }
4372 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004373 mPaused = false;
4374 }
4375}
4376
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004377void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4378 sp<Camera3Device> parent = mParent.promote();
4379 if (parent != NULL) {
4380 va_list args;
4381 va_start(args, fmt);
4382
4383 parent->setErrorStateV(fmt, args);
4384
4385 va_end(args);
4386 }
4387}
4388
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004389status_t Camera3Device::RequestThread::insertTriggers(
4390 const sp<CaptureRequest> &request) {
4391
4392 Mutex::Autolock al(mTriggerMutex);
4393
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004394 sp<Camera3Device> parent = mParent.promote();
4395 if (parent == NULL) {
4396 CLOGE("RequestThread: Parent is gone");
4397 return DEAD_OBJECT;
4398 }
4399
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004400 CameraMetadata &metadata = request->mSettings;
4401 size_t count = mTriggerMap.size();
4402
4403 for (size_t i = 0; i < count; ++i) {
4404 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004405 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004406
4407 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4408 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4409 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004410 if (isAeTrigger) {
4411 request->mResultExtras.precaptureTriggerId = triggerId;
4412 mCurrentPreCaptureTriggerId = triggerId;
4413 } else {
4414 request->mResultExtras.afTriggerId = triggerId;
4415 mCurrentAfTriggerId = triggerId;
4416 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004417 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4418 continue; // Trigger ID tag is deprecated since device HAL 3.2
4419 }
4420 }
4421
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004422 camera_metadata_entry entry = metadata.find(tag);
4423
4424 if (entry.count > 0) {
4425 /**
4426 * Already has an entry for this trigger in the request.
4427 * Rewrite it with our requested trigger value.
4428 */
4429 RequestTrigger oldTrigger = trigger;
4430
4431 oldTrigger.entryValue = entry.data.u8[0];
4432
4433 mTriggerReplacedMap.add(tag, oldTrigger);
4434 } else {
4435 /**
4436 * More typical, no trigger entry, so we just add it
4437 */
4438 mTriggerRemovedMap.add(tag, trigger);
4439 }
4440
4441 status_t res;
4442
4443 switch (trigger.getTagType()) {
4444 case TYPE_BYTE: {
4445 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4446 res = metadata.update(tag,
4447 &entryValue,
4448 /*count*/1);
4449 break;
4450 }
4451 case TYPE_INT32:
4452 res = metadata.update(tag,
4453 &trigger.entryValue,
4454 /*count*/1);
4455 break;
4456 default:
4457 ALOGE("%s: Type not supported: 0x%x",
4458 __FUNCTION__,
4459 trigger.getTagType());
4460 return INVALID_OPERATION;
4461 }
4462
4463 if (res != OK) {
4464 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4465 ", value %d", __FUNCTION__, trigger.getTagName(),
4466 trigger.entryValue);
4467 return res;
4468 }
4469
4470 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4471 trigger.getTagName(),
4472 trigger.entryValue);
4473 }
4474
4475 mTriggerMap.clear();
4476
4477 return count;
4478}
4479
4480status_t Camera3Device::RequestThread::removeTriggers(
4481 const sp<CaptureRequest> &request) {
4482 Mutex::Autolock al(mTriggerMutex);
4483
4484 CameraMetadata &metadata = request->mSettings;
4485
4486 /**
4487 * Replace all old entries with their old values.
4488 */
4489 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4490 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4491
4492 status_t res;
4493
4494 uint32_t tag = trigger.metadataTag;
4495 switch (trigger.getTagType()) {
4496 case TYPE_BYTE: {
4497 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4498 res = metadata.update(tag,
4499 &entryValue,
4500 /*count*/1);
4501 break;
4502 }
4503 case TYPE_INT32:
4504 res = metadata.update(tag,
4505 &trigger.entryValue,
4506 /*count*/1);
4507 break;
4508 default:
4509 ALOGE("%s: Type not supported: 0x%x",
4510 __FUNCTION__,
4511 trigger.getTagType());
4512 return INVALID_OPERATION;
4513 }
4514
4515 if (res != OK) {
4516 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4517 ", trigger value %d", __FUNCTION__,
4518 trigger.getTagName(), trigger.entryValue);
4519 return res;
4520 }
4521 }
4522 mTriggerReplacedMap.clear();
4523
4524 /**
4525 * Remove all new entries.
4526 */
4527 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4528 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4529 status_t res = metadata.erase(trigger.metadataTag);
4530
4531 if (res != OK) {
4532 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4533 ", trigger value %d", __FUNCTION__,
4534 trigger.getTagName(), trigger.entryValue);
4535 return res;
4536 }
4537 }
4538 mTriggerRemovedMap.clear();
4539
4540 return OK;
4541}
4542
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004543status_t Camera3Device::RequestThread::addDummyTriggerIds(
4544 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004545 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004546 static const int32_t dummyTriggerId = 1;
4547 status_t res;
4548
4549 CameraMetadata &metadata = request->mSettings;
4550
4551 // If AF trigger is active, insert a dummy AF trigger ID if none already
4552 // exists
4553 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4554 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4555 if (afTrigger.count > 0 &&
4556 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4557 afId.count == 0) {
4558 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4559 if (res != OK) return res;
4560 }
4561
4562 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4563 // if none already exists
4564 camera_metadata_entry pcTrigger =
4565 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4566 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4567 if (pcTrigger.count > 0 &&
4568 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4569 pcId.count == 0) {
4570 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4571 &dummyTriggerId, 1);
4572 if (res != OK) return res;
4573 }
4574
4575 return OK;
4576}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004577
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004578/**
4579 * PreparerThread inner class methods
4580 */
4581
4582Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004583 Thread(/*canCallJava*/false), mListener(nullptr),
4584 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004585}
4586
4587Camera3Device::PreparerThread::~PreparerThread() {
4588 Thread::requestExitAndWait();
4589 if (mCurrentStream != nullptr) {
4590 mCurrentStream->cancelPrepare();
4591 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4592 mCurrentStream.clear();
4593 }
4594 clear();
4595}
4596
Ruben Brunkc78ac262015-08-13 17:58:46 -07004597status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004598 status_t res;
4599
4600 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004601 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004602
Ruben Brunkc78ac262015-08-13 17:58:46 -07004603 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004604 if (res == OK) {
4605 // No preparation needed, fire listener right off
4606 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004607 if (listener != NULL) {
4608 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004609 }
4610 return OK;
4611 } else if (res != NOT_ENOUGH_DATA) {
4612 return res;
4613 }
4614
4615 // Need to prepare, start up thread if necessary
4616 if (!mActive) {
4617 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4618 // isn't running
4619 Thread::requestExitAndWait();
4620 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4621 if (res != OK) {
4622 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004623 if (listener != NULL) {
4624 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004625 }
4626 return res;
4627 }
4628 mCancelNow = false;
4629 mActive = true;
4630 ALOGV("%s: Preparer stream started", __FUNCTION__);
4631 }
4632
4633 // queue up the work
4634 mPendingStreams.push_back(stream);
4635 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4636
4637 return OK;
4638}
4639
4640status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004641 Mutex::Autolock l(mLock);
4642
4643 for (const auto& stream : mPendingStreams) {
4644 stream->cancelPrepare();
4645 }
4646 mPendingStreams.clear();
4647 mCancelNow = true;
4648
4649 return OK;
4650}
4651
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004652void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004653 Mutex::Autolock l(mLock);
4654 mListener = listener;
4655}
4656
4657bool Camera3Device::PreparerThread::threadLoop() {
4658 status_t res;
4659 {
4660 Mutex::Autolock l(mLock);
4661 if (mCurrentStream == nullptr) {
4662 // End thread if done with work
4663 if (mPendingStreams.empty()) {
4664 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4665 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4666 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4667 mActive = false;
4668 return false;
4669 }
4670
4671 // Get next stream to prepare
4672 auto it = mPendingStreams.begin();
4673 mCurrentStream = *it;
4674 mPendingStreams.erase(it);
4675 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4676 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4677 } else if (mCancelNow) {
4678 mCurrentStream->cancelPrepare();
4679 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4680 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4681 mCurrentStream.clear();
4682 mCancelNow = false;
4683 return true;
4684 }
4685 }
4686
4687 res = mCurrentStream->prepareNextBuffer();
4688 if (res == NOT_ENOUGH_DATA) return true;
4689 if (res != OK) {
4690 // Something bad happened; try to recover by cancelling prepare and
4691 // signalling listener anyway
4692 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4693 mCurrentStream->getId(), res, strerror(-res));
4694 mCurrentStream->cancelPrepare();
4695 }
4696
4697 // This stream has finished, notify listener
4698 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004699 sp<NotificationListener> listener = mListener.promote();
4700 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004701 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4702 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004703 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004704 }
4705
4706 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4707 mCurrentStream.clear();
4708
4709 return true;
4710}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004711
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004712/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004713 * Static callback forwarding methods from HAL to instance
4714 */
4715
4716void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4717 const camera3_capture_result *result) {
4718 Camera3Device *d =
4719 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004720
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004721 d->processCaptureResult(result);
4722}
4723
4724void Camera3Device::sNotify(const camera3_callback_ops *cb,
4725 const camera3_notify_msg *msg) {
4726 Camera3Device *d =
4727 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4728 d->notify(msg);
4729}
4730
4731}; // namespace android