blob: 980ba398b613a6d4eacd93e51a90104ca5a40c9e [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 Talvala1a2f15d2017-03-23 15:37:22 -070047#include <grallocusage/GrallocUsageConversion.h>
48
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070079 mListener(NULL)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080080{
81 ATRACE_CALL();
82 camera3_callback_ops::notify = &sNotify;
83 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080084 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080085}
86
87Camera3Device::~Camera3Device()
88{
89 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080090 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080091 disconnect();
92}
93
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080095 return mId;
96}
97
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080098/**
99 * CameraDeviceBase interface
100 */
101
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800102status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103{
104 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700105 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800106 Mutex::Autolock l(mLock);
107
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800109 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700110 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111 return INVALID_OPERATION;
112 }
113
114 /** Open HAL device */
115
116 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800117
118 camera3_device_t *device;
119
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 ATRACE_BEGIN("CameraHal::open");
121 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800122 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800123 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800124
125 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700126 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800127 return res;
128 }
129
130 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700132 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700133 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800134 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800135 device->common.version);
136 device->common.close(&device->common);
137 return BAD_VALUE;
138 }
139
140 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800141 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800142 if (res != OK) return res;
143
144 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700145 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
146 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700147 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800148 device->common.close(&device->common);
149 return BAD_VALUE;
150 }
151
152 /** Initialize device with callback functions */
153
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800154 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800155 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700156 ATRACE_END();
157
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800158 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700159 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
160 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800161 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800162 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800163 }
164
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800165 /** Everything is good to go */
166
167 mDeviceVersion = device->common.version;
168 mDeviceInfo = info.static_camera_characteristics;
169 mInterface = std::make_unique<HalInterface>(device);
170
171 return initializeCommonLocked();
172}
173
174status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
175 ATRACE_CALL();
176 Mutex::Autolock il(mInterfaceLock);
177 Mutex::Autolock l(mLock);
178
179 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
180 if (mStatus != STATUS_UNINITIALIZED) {
181 CLOGE("Already initialized!");
182 return INVALID_OPERATION;
183 }
184 if (manager == nullptr) return INVALID_OPERATION;
185
186 sp<ICameraDeviceSession> session;
187 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800188 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800189 /*out*/ &session);
190 ATRACE_END();
191 if (res != OK) {
192 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
193 return res;
194 }
195
Steven Moreland5ff9c912017-03-09 23:13:00 -0800196 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800197 if (res != OK) {
198 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
199 session->close();
200 return res;
201 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800202
203 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
204 // for now use 3_4 to keep legacy devices working
205 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800206 mInterface = std::make_unique<HalInterface>(session);
207
208 return initializeCommonLocked();
209}
210
211status_t Camera3Device::initializeCommonLocked() {
212
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700213 /** Start up status tracker thread */
214 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800215 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700216 if (res != OK) {
217 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
218 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800219 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700220 mStatusTracker.clear();
221 return res;
222 }
223
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700224 /** Register in-flight map to the status tracker */
225 mInFlightStatusId = mStatusTracker->addComponent();
226
Zhijun He125684a2015-12-26 15:07:30 -0800227 /** Create buffer manager */
228 mBufferManager = new Camera3BufferManager();
229
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700230 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800231 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
232 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
233 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700234 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
235 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
236 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800237
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700238 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800239 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
240 aeLockAvailable);
241 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800242 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700243 SET_ERR_L("Unable to start request queue thread: %s (%d)",
244 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800245 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800246 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800247 return res;
248 }
249
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700250 mPreparerThread = new PreparerThread();
251
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700252 // Determine whether we need to derive sensitivity boost values for older devices.
253 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
254 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800255 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700256 mDerivePostRawSensKey = true;
257 }
258
Ruben Brunk183f0562015-08-12 12:55:02 -0700259 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800260 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700261 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700262 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800264
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800265 // Measure the clock domain offset between camera and video/hw_composer
266 camera_metadata_entry timestampSource =
267 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
268 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
269 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
270 mTimestampOffset = getMonoToBoottimeOffset();
271 }
272
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700273 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700274 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
275 camera_metadata_entry partialResultsCount =
276 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
277 if (partialResultsCount.count > 0) {
278 mNumPartialResults = partialResultsCount.data.i32[0];
279 mUsePartialResult = (mNumPartialResults > 1);
280 }
281 } else {
282 camera_metadata_entry partialResultsQuirk =
283 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
284 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
285 mUsePartialResult = true;
286 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700287 }
288
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700289 camera_metadata_entry configs =
290 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
291 for (uint32_t i = 0; i < configs.count; i += 4) {
292 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
293 configs.data.i32[i + 3] ==
294 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
295 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
296 configs.data.i32[i + 2]));
297 }
298 }
299
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800300 return OK;
301}
302
303status_t Camera3Device::disconnect() {
304 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700307 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800308
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700309 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 {
312 Mutex::Autolock l(mLock);
313 if (mStatus == STATUS_UNINITIALIZED) return res;
314
315 if (mStatus == STATUS_ACTIVE ||
316 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
317 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700318 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700320 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700321 } else {
322 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
323 if (res != OK) {
324 SET_ERR_L("Timeout waiting for HAL to drain");
325 // Continue to close device even in case of error
326 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700327 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800328 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800329
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700330 if (mStatus == STATUS_ERROR) {
331 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700332 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700333
334 if (mStatusTracker != NULL) {
335 mStatusTracker->requestExit();
336 }
337
338 if (mRequestThread != NULL) {
339 mRequestThread->requestExit();
340 }
341
342 mOutputStreams.clear();
343 mInputStream.clear();
344 }
345
346 // Joining done without holding mLock, otherwise deadlocks may ensue
347 // as the threads try to access parent state
348 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
349 // HAL may be in a bad state, so waiting for request thread
350 // (which may be stuck in the HAL processCaptureRequest call)
351 // could be dangerous.
352 mRequestThread->join();
353 }
354
355 if (mStatusTracker != NULL) {
356 mStatusTracker->join();
357 }
358
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800359 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700360 {
361 Mutex::Autolock l(mLock);
362
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800363 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700364 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800365 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800366
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800367 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700368 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800369
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700370 // Call close without internal mutex held, as the HAL close may need to
371 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800372 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700373
374 {
375 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800376 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700377 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800379
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700380 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700381 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800382}
383
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384// For dumping/debugging only -
385// try to acquire a lock a few times, eventually give up to proceed with
386// debug/dump operations
387bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
388 bool gotLock = false;
389 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
390 if (lock.tryLock() == NO_ERROR) {
391 gotLock = true;
392 break;
393 } else {
394 usleep(kDumpSleepDuration);
395 }
396 }
397 return gotLock;
398}
399
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700400Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
401 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
402 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
403 const int STREAM_CONFIGURATION_SIZE = 4;
404 const int STREAM_FORMAT_OFFSET = 0;
405 const int STREAM_WIDTH_OFFSET = 1;
406 const int STREAM_HEIGHT_OFFSET = 2;
407 const int STREAM_IS_INPUT_OFFSET = 3;
408 camera_metadata_ro_entry_t availableStreamConfigs =
409 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
410 if (availableStreamConfigs.count == 0 ||
411 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
412 return Size(0, 0);
413 }
414
415 // Get max jpeg size (area-wise).
416 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
417 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
418 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
419 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
420 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
421 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
422 && format == HAL_PIXEL_FORMAT_BLOB &&
423 (width * height > maxJpegWidth * maxJpegHeight)) {
424 maxJpegWidth = width;
425 maxJpegHeight = height;
426 }
427 }
428 } else {
429 camera_metadata_ro_entry availableJpegSizes =
430 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
431 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
432 return Size(0, 0);
433 }
434
435 // Get max jpeg size (area-wise).
436 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
437 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
438 > (maxJpegWidth * maxJpegHeight)) {
439 maxJpegWidth = availableJpegSizes.data.i32[i];
440 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
441 }
442 }
443 }
444 return Size(maxJpegWidth, maxJpegHeight);
445}
446
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800447nsecs_t Camera3Device::getMonoToBoottimeOffset() {
448 // try three times to get the clock offset, choose the one
449 // with the minimum gap in measurements.
450 const int tries = 3;
451 nsecs_t bestGap, measured;
452 for (int i = 0; i < tries; ++i) {
453 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
454 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
455 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
456 const nsecs_t gap = tmono2 - tmono;
457 if (i == 0 || gap < bestGap) {
458 bestGap = gap;
459 measured = tbase - ((tmono + tmono2) >> 1);
460 }
461 }
462 return measured;
463}
464
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700465/**
466 * Map Android N dataspace definitions back to Android M definitions, for
467 * use with HALv3.3 or older.
468 *
469 * Only map where correspondences exist, and otherwise preserve the value.
470 */
471android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
472 switch (dataSpace) {
473 case HAL_DATASPACE_V0_SRGB_LINEAR:
474 return HAL_DATASPACE_SRGB_LINEAR;
475 case HAL_DATASPACE_V0_SRGB:
476 return HAL_DATASPACE_SRGB;
477 case HAL_DATASPACE_V0_JFIF:
478 return HAL_DATASPACE_JFIF;
479 case HAL_DATASPACE_V0_BT601_625:
480 return HAL_DATASPACE_BT601_625;
481 case HAL_DATASPACE_V0_BT601_525:
482 return HAL_DATASPACE_BT601_525;
483 case HAL_DATASPACE_V0_BT709:
484 return HAL_DATASPACE_BT709;
485 default:
486 return dataSpace;
487 }
488}
489
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
491 int frameworkFormat) {
492 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
493}
494
495DataspaceFlags Camera3Device::mapToHidlDataspace(
496 android_dataspace dataSpace) {
497 return dataSpace;
498}
499
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
501 switch (rotation) {
502 case CAMERA3_STREAM_ROTATION_0:
503 return StreamRotation::ROTATION_0;
504 case CAMERA3_STREAM_ROTATION_90:
505 return StreamRotation::ROTATION_90;
506 case CAMERA3_STREAM_ROTATION_180:
507 return StreamRotation::ROTATION_180;
508 case CAMERA3_STREAM_ROTATION_270:
509 return StreamRotation::ROTATION_270;
510 }
511 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
512 return StreamRotation::ROTATION_0;
513}
514
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800515status_t Camera3Device::mapToStreamConfigurationMode(
516 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
517 if (mode == nullptr) return BAD_VALUE;
518 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
519 switch(operationMode) {
520 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
521 *mode = StreamConfigurationMode::NORMAL_MODE;
522 break;
523 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
524 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
525 break;
526 default:
527 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
528 return BAD_VALUE;
529 }
530 } else {
531 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800532 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800533 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534}
535
536camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
537 switch (status) {
538 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
539 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
540 }
541 return CAMERA3_BUFFER_STATUS_ERROR;
542}
543
544int Camera3Device::mapToFrameworkFormat(
545 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
546 return static_cast<uint32_t>(pixelFormat);
547}
548
Zhijun Hef7da0962014-04-24 13:27:56 -0700549ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700550 // Get max jpeg size (area-wise).
551 Size maxJpegResolution = getMaxJpegResolution();
552 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
554 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700555 return BAD_VALUE;
556 }
557
Zhijun Hef7da0962014-04-24 13:27:56 -0700558 // Get max jpeg buffer size
559 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700560 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
561 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800562 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
563 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700564 return BAD_VALUE;
565 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700566 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800567 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700568
569 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700570 float scaleFactor = ((float) (width * height)) /
571 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800572 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
573 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700574 if (jpegBufferSize > maxJpegBufferSize) {
575 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700576 }
577
578 return jpegBufferSize;
579}
580
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700581ssize_t Camera3Device::getPointCloudBufferSize() const {
582 const int FLOATS_PER_POINT=4;
583 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
584 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
586 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700587 return BAD_VALUE;
588 }
589 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
590 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
591 return maxBytesForPointCloud;
592}
593
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800595 const int PER_CONFIGURATION_SIZE = 3;
596 const int WIDTH_OFFSET = 0;
597 const int HEIGHT_OFFSET = 1;
598 const int SIZE_OFFSET = 2;
599 camera_metadata_ro_entry rawOpaqueSizes =
600 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800601 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800602 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
604 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800605 return BAD_VALUE;
606 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700607
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800608 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
609 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
610 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
611 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
612 }
613 }
614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
616 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800617 return BAD_VALUE;
618}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700619
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800620status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
621 ATRACE_CALL();
622 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700623
624 // Try to lock, but continue in case of failure (to avoid blocking in
625 // deadlocks)
626 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
627 bool gotLock = tryLockSpinRightRound(mLock);
628
629 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800630 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
631 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700632 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
634 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700635
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800636 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700637
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700639 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800640 int n = args.size();
641 for (int i = 0; i < n; i++) {
642 if (args[i] == templatesOption) {
643 dumpTemplates = true;
644 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700645 if (args[i] == monitorOption) {
646 if (i + 1 < n) {
647 String8 monitorTags = String8(args[i + 1]);
648 if (monitorTags == "off") {
649 mTagMonitor.disableMonitoring();
650 } else {
651 mTagMonitor.parseTagsToMonitor(monitorTags);
652 }
653 } else {
654 mTagMonitor.disableMonitoring();
655 }
656 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800657 }
658
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800659 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800660
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800661 const char *status =
662 mStatus == STATUS_ERROR ? "ERROR" :
663 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700664 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
665 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800666 mStatus == STATUS_ACTIVE ? "ACTIVE" :
667 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700668
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800669 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700670 if (mStatus == STATUS_ERROR) {
671 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
672 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800673 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800674 const char *mode =
675 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
676 mOperatingMode == static_cast<int>(
677 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
678 "CUSTOM";
679 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680
681 if (mInputStream != NULL) {
682 write(fd, lines.string(), lines.size());
683 mInputStream->dump(fd, args);
684 } else {
685 lines.appendFormat(" No input stream.\n");
686 write(fd, lines.string(), lines.size());
687 }
688 for (size_t i = 0; i < mOutputStreams.size(); i++) {
689 mOutputStreams[i]->dump(fd,args);
690 }
691
Zhijun He431503c2016-03-07 17:30:16 -0800692 if (mBufferManager != NULL) {
693 lines = String8(" Camera3 Buffer Manager:\n");
694 write(fd, lines.string(), lines.size());
695 mBufferManager->dump(fd, args);
696 }
Zhijun He125684a2015-12-26 15:07:30 -0800697
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700698 lines = String8(" In-flight requests:\n");
699 if (mInFlightMap.size() == 0) {
700 lines.append(" None\n");
701 } else {
702 for (size_t i = 0; i < mInFlightMap.size(); i++) {
703 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700704 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700705 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800706 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700707 r.numBuffersLeft);
708 }
709 }
710 write(fd, lines.string(), lines.size());
711
Igor Murashkin1e479c02013-09-06 16:55:14 -0700712 {
713 lines = String8(" Last request sent:\n");
714 write(fd, lines.string(), lines.size());
715
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700716 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700717 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
718 }
719
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 if (dumpTemplates) {
721 const char *templateNames[] = {
722 "TEMPLATE_PREVIEW",
723 "TEMPLATE_STILL_CAPTURE",
724 "TEMPLATE_VIDEO_RECORD",
725 "TEMPLATE_VIDEO_SNAPSHOT",
726 "TEMPLATE_ZERO_SHUTTER_LAG",
727 "TEMPLATE_MANUAL"
728 };
729
730 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800731 camera_metadata_t *templateRequest = nullptr;
732 mInterface->constructDefaultRequestSettings(
733 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800734 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800735 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800736 lines.append(" Not supported\n");
737 write(fd, lines.string(), lines.size());
738 } else {
739 write(fd, lines.string(), lines.size());
740 dump_indented_camera_metadata(templateRequest,
741 fd, /*verbosity*/2, /*indentation*/8);
742 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800743 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800744 }
745 }
746
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700747 mTagMonitor.dumpMonitoredMetadata(fd);
748
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800749 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800750 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800754
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700755 if (gotLock) mLock.unlock();
756 if (gotInterfaceLock) mInterfaceLock.unlock();
757
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800758 return OK;
759}
760
761const CameraMetadata& Camera3Device::info() const {
762 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800763 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
764 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700765 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800766 mStatus == STATUS_ERROR ?
767 "when in error state" : "before init");
768 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800769 return mDeviceInfo;
770}
771
Jianing Wei90e59c92014-03-12 18:29:36 -0700772status_t Camera3Device::checkStatusOkToCaptureLocked() {
773 switch (mStatus) {
774 case STATUS_ERROR:
775 CLOGE("Device has encountered a serious error");
776 return INVALID_OPERATION;
777 case STATUS_UNINITIALIZED:
778 CLOGE("Device not initialized");
779 return INVALID_OPERATION;
780 case STATUS_UNCONFIGURED:
781 case STATUS_CONFIGURED:
782 case STATUS_ACTIVE:
783 // OK
784 break;
785 default:
786 SET_ERR_L("Unexpected status: %d", mStatus);
787 return INVALID_OPERATION;
788 }
789 return OK;
790}
791
792status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700793 const List<const CameraMetadata> &metadataList,
794 const std::list<const SurfaceMap> &surfaceMaps,
795 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700796 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700797 if (requestList == NULL) {
798 CLOGE("requestList cannot be NULL.");
799 return BAD_VALUE;
800 }
801
Jianing Weicb0652e2014-03-12 18:29:36 -0700802 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700803 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
804 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
805 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
806 ++metadataIt, ++surfaceMapIt) {
807 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700808 if (newRequest == 0) {
809 CLOGE("Can't create capture request");
810 return BAD_VALUE;
811 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700812
Shuzhen Wang9d066012016-09-30 11:30:20 -0700813 newRequest->mRepeating = repeating;
814
Jianing Weicb0652e2014-03-12 18:29:36 -0700815 // Setup burst Id and request Id
816 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700817 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
818 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700819 CLOGE("RequestID entry exists; but must not be empty in metadata");
820 return BAD_VALUE;
821 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700823 } else {
824 CLOGE("RequestID does not exist in metadata");
825 return BAD_VALUE;
826 }
827
Jianing Wei90e59c92014-03-12 18:29:36 -0700828 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700829
830 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
833 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
834 return BAD_VALUE;
835 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700836
837 // Setup batch size if this is a high speed video recording request.
838 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
839 auto firstRequest = requestList->begin();
840 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
841 if (outputStream->isVideoStream()) {
842 (*firstRequest)->mBatchSize = requestList->size();
843 break;
844 }
845 }
846 }
847
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 return OK;
849}
850
Jianing Weicb0652e2014-03-12 18:29:36 -0700851status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800853
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700854 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700855 std::list<const SurfaceMap> surfaceMaps;
856 convertToRequestList(requests, surfaceMaps, request);
857
858 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
859}
860
861void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
862 std::list<const SurfaceMap>& surfaceMaps,
863 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700864 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700865
866 SurfaceMap surfaceMap;
867 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
868 // With no surface list passed in, stream and surface will have 1-to-1
869 // mapping. So the surface index is 0 for each stream in the surfaceMap.
870 for (size_t i = 0; i < streams.count; i++) {
871 surfaceMap[streams.data.i32[i]].push_back(0);
872 }
873 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874}
875
Jianing Wei90e59c92014-03-12 18:29:36 -0700876status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700877 const List<const CameraMetadata> &requests,
878 const std::list<const SurfaceMap> &surfaceMaps,
879 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700880 /*out*/
881 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 ATRACE_CALL();
883 Mutex::Autolock il(mInterfaceLock);
884 Mutex::Autolock l(mLock);
885
886 status_t res = checkStatusOkToCaptureLocked();
887 if (res != OK) {
888 // error logged by previous call
889 return res;
890 }
891
892 RequestList requestList;
893
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
895 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700896 if (res != OK) {
897 // error logged by previous call
898 return res;
899 }
900
901 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700902 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700904 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700905 }
906
907 if (res == OK) {
908 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
909 if (res != OK) {
910 SET_ERR_L("Can't transition to active in %f seconds!",
911 kActiveTimeout/1e9);
912 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800913 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700914 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700915 } else {
916 CLOGE("Cannot queue request. Impossible.");
917 return BAD_VALUE;
918 }
919
920 return res;
921}
922
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800923
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800924hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800925 const hardware::hidl_vec<
926 hardware::camera::device::V3_2::CaptureResult>& results) {
927 for (const auto& result : results) {
928 processOneCaptureResult(result);
929 }
930 return hardware::Void();
931}
932
933void Camera3Device::processOneCaptureResult(
934 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800935 camera3_capture_result r;
936 status_t res;
937 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800938 if (result.result.size() != 0) {
939 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
940 size_t expected_metadata_size = result.result.size();
941 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
942 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
943 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800944 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800945 }
946 } else {
947 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800948 }
949
950 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
951 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
952 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
953 auto& bDst = outputBuffers[i];
954 const StreamBuffer &bSrc = result.outputBuffers[i];
955
956 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100957 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800958 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
959 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800960 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800961 }
962 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
963
964 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800965 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800966 if (res != OK) {
967 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
968 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800969 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800970 }
971 bDst.buffer = buffer;
972 bDst.status = mapHidlBufferStatus(bSrc.status);
973 bDst.acquire_fence = -1;
974 if (bSrc.releaseFence == nullptr) {
975 bDst.release_fence = -1;
976 } else if (bSrc.releaseFence->numFds == 1) {
977 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
978 } else {
979 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
980 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800981 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800982 }
983 }
984 r.num_output_buffers = outputBuffers.size();
985 r.output_buffers = outputBuffers.data();
986
987 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800988 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800989 r.input_buffer = nullptr;
990 } else {
991 if (mInputStream->getId() != result.inputBuffer.streamId) {
992 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
993 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800994 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 }
996 inputBuffer.stream = mInputStream->asHalStream();
997 buffer_handle_t *buffer;
998 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
999 &buffer);
1000 if (res != OK) {
1001 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1002 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001003 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001004 }
1005 inputBuffer.buffer = buffer;
1006 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1007 inputBuffer.acquire_fence = -1;
1008 if (result.inputBuffer.releaseFence == nullptr) {
1009 inputBuffer.release_fence = -1;
1010 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1011 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1012 } else {
1013 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1014 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001015 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001016 }
1017 r.input_buffer = &inputBuffer;
1018 }
1019
1020 r.partial_result = result.partialResult;
1021
1022 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023}
1024
1025hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001026 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1027 for (const auto& msg : msgs) {
1028 notify(msg);
1029 }
1030 return hardware::Void();
1031}
1032
1033void Camera3Device::notify(
1034 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1035
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001036 camera3_notify_msg m;
1037 switch (msg.type) {
1038 case MsgType::ERROR:
1039 m.type = CAMERA3_MSG_ERROR;
1040 m.message.error.frame_number = msg.msg.error.frameNumber;
1041 if (msg.msg.error.errorStreamId >= 0) {
1042 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001043 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001044 ALOGE("%s: Frame %d: Invalid error stream id %d",
1045 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001046 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001047 }
1048 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1049 } else {
1050 m.message.error.error_stream = nullptr;
1051 }
1052 switch (msg.msg.error.errorCode) {
1053 case ErrorCode::ERROR_DEVICE:
1054 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1055 break;
1056 case ErrorCode::ERROR_REQUEST:
1057 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1058 break;
1059 case ErrorCode::ERROR_RESULT:
1060 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1061 break;
1062 case ErrorCode::ERROR_BUFFER:
1063 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1064 break;
1065 }
1066 break;
1067 case MsgType::SHUTTER:
1068 m.type = CAMERA3_MSG_SHUTTER;
1069 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1070 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1071 break;
1072 }
1073 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001074}
1075
Jianing Weicb0652e2014-03-12 18:29:36 -07001076status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001078 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001079 ATRACE_CALL();
1080
Shuzhen Wang0129d522016-10-30 22:43:41 -07001081 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001082}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001083
Jianing Weicb0652e2014-03-12 18:29:36 -07001084status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1085 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001086 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001087
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001088 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001089 std::list<const SurfaceMap> surfaceMaps;
1090 convertToRequestList(requests, surfaceMaps, request);
1091
1092 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1093 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001094}
1095
Jianing Weicb0652e2014-03-12 18:29:36 -07001096status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001097 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001098 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001099 ATRACE_CALL();
1100
Shuzhen Wang0129d522016-10-30 22:43:41 -07001101 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001102}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001103
1104sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001105 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001106 status_t res;
1107
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001108 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001109 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1110 // so unilaterally select normal operating mode.
1111 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001112 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001113 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001114 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001115 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001116 } else if (mStatus == STATUS_UNCONFIGURED) {
1117 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001118 CLOGE("No streams configured");
1119 return NULL;
1120 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121 }
1122
Shuzhen Wang0129d522016-10-30 22:43:41 -07001123 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001124 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001125}
1126
Jianing Weicb0652e2014-03-12 18:29:36 -07001127status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001128 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001129 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001130 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001131
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 switch (mStatus) {
1133 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001134 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001135 return INVALID_OPERATION;
1136 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001137 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001138 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001139 case STATUS_UNCONFIGURED:
1140 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001141 case STATUS_ACTIVE:
1142 // OK
1143 break;
1144 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001145 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001146 return INVALID_OPERATION;
1147 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001148 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001149
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001150 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001151}
1152
1153status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1154 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001155 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001156
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001157 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001158}
1159
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001160status_t Camera3Device::createInputStream(
1161 uint32_t width, uint32_t height, int format, int *id) {
1162 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001164 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001165 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1166 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001167
1168 status_t res;
1169 bool wasActive = false;
1170
1171 switch (mStatus) {
1172 case STATUS_ERROR:
1173 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1174 return INVALID_OPERATION;
1175 case STATUS_UNINITIALIZED:
1176 ALOGE("%s: Device not initialized", __FUNCTION__);
1177 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001178 case STATUS_UNCONFIGURED:
1179 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180 // OK
1181 break;
1182 case STATUS_ACTIVE:
1183 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001185 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001186 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001187 return res;
1188 }
1189 wasActive = true;
1190 break;
1191 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001192 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001193 return INVALID_OPERATION;
1194 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001196
1197 if (mInputStream != 0) {
1198 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1199 return INVALID_OPERATION;
1200 }
1201
1202 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1203 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001205
1206 mInputStream = newStream;
1207
1208 *id = mNextStreamId++;
1209
1210 // Continue captures if active at start
1211 if (wasActive) {
1212 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001213 // Reuse current operating mode for new stream config
1214 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001215 if (res != OK) {
1216 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1217 __FUNCTION__, mNextStreamId, strerror(-res), res);
1218 return res;
1219 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001221 }
1222
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001223 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001224 return OK;
1225}
1226
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001227status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001228 uint32_t width, uint32_t height, int format,
1229 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001230 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001231 ATRACE_CALL();
1232
1233 if (consumer == nullptr) {
1234 ALOGE("%s: consumer must not be null", __FUNCTION__);
1235 return BAD_VALUE;
1236 }
1237
1238 std::vector<sp<Surface>> consumers;
1239 consumers.push_back(consumer);
1240
1241 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001242 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001243}
1244
1245status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1246 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1247 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001248 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001252 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001253 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1254 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 status_t res;
1257 bool wasActive = false;
1258
1259 switch (mStatus) {
1260 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
1263 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001264 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 case STATUS_UNCONFIGURED:
1267 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 // OK
1269 break;
1270 case STATUS_ACTIVE:
1271 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001272 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return res;
1276 }
1277 wasActive = true;
1278 break;
1279 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001280 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 return INVALID_OPERATION;
1282 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284
1285 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001286 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001287 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001288 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001289 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1290 }
Zhijun He5d677d12016-05-29 16:52:39 -07001291
Shuzhen Wang0129d522016-10-30 22:43:41 -07001292 if (consumers.size() == 0 && !hasDeferredConsumer) {
1293 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1294 return BAD_VALUE;
1295 }
Zhijun He5d677d12016-05-29 16:52:39 -07001296 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1297 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001298 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001299 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1300 return BAD_VALUE;
1301 }
1302
Shuzhen Wang0129d522016-10-30 22:43:41 -07001303 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001304 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1305 return BAD_VALUE;
1306 }
1307
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001308 // Use legacy dataspace values for older HALs
1309 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1310 dataSpace = mapToLegacyDataspace(dataSpace);
1311 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001313 ssize_t blobBufferSize;
1314 if (dataSpace != HAL_DATASPACE_DEPTH) {
1315 blobBufferSize = getJpegBufferSize(width, height);
1316 if (blobBufferSize <= 0) {
1317 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1318 return BAD_VALUE;
1319 }
1320 } else {
1321 blobBufferSize = getPointCloudBufferSize();
1322 if (blobBufferSize <= 0) {
1323 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1324 return BAD_VALUE;
1325 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001326 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001327 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001328 width, height, blobBufferSize, format, dataSpace, rotation,
1329 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001330 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1331 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1332 if (rawOpaqueBufferSize <= 0) {
1333 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1334 return BAD_VALUE;
1335 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001336 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001337 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1338 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001339 } else if (isShared) {
1340 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1341 width, height, format, consumerUsage, dataSpace, rotation,
1342 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001343 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001344 newStream = new Camera3OutputStream(mNextStreamId,
1345 width, height, format, consumerUsage, dataSpace, rotation,
1346 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001348 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001349 width, height, format, dataSpace, rotation,
1350 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001352 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353
Zhijun He125684a2015-12-26 15:07:30 -08001354 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001355 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1356 * requires buffers to be statically allocated for internal static buffer registration, while
1357 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1358 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001359 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001360 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001361 newStream->setBufferManager(mBufferManager);
1362 }
1363
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 res = mOutputStreams.add(mNextStreamId, newStream);
1365 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return res;
1368 }
1369
1370 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001371 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372
1373 // Continue captures if active at start
1374 if (wasActive) {
1375 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001376 // Reuse current operating mode for new stream config
1377 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001379 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1380 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 return res;
1382 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001383 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001385 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001387}
1388
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001389status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001390 uint32_t *width, uint32_t *height,
1391 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001392 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001395
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 switch (mStatus) {
1397 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001398 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 return INVALID_OPERATION;
1400 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001401 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001403 case STATUS_UNCONFIGURED:
1404 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 case STATUS_ACTIVE:
1406 // OK
1407 break;
1408 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001409 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 return INVALID_OPERATION;
1411 }
1412
1413 ssize_t idx = mOutputStreams.indexOfKey(id);
1414 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001415 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 return idx;
1417 }
1418
1419 if (width) *width = mOutputStreams[idx]->getWidth();
1420 if (height) *height = mOutputStreams[idx]->getHeight();
1421 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001422 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001424}
1425
1426status_t Camera3Device::setStreamTransform(int id,
1427 int transform) {
1428 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001429 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001431
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 switch (mStatus) {
1433 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001434 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 return INVALID_OPERATION;
1436 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001437 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001439 case STATUS_UNCONFIGURED:
1440 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 case STATUS_ACTIVE:
1442 // OK
1443 break;
1444 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001445 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 return INVALID_OPERATION;
1447 }
1448
1449 ssize_t idx = mOutputStreams.indexOfKey(id);
1450 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001451 CLOGE("Stream %d does not exist",
1452 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 return BAD_VALUE;
1454 }
1455
1456 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001457}
1458
1459status_t Camera3Device::deleteStream(int id) {
1460 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 Mutex::Autolock l(mLock);
1463 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001464
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001465 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 // CameraDevice semantics require device to already be idle before
1468 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001470 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001471 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 }
1473
Igor Murashkin2fba5842013-04-22 14:03:54 -07001474 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001475 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 if (mInputStream != NULL && id == mInputStream->getId()) {
1477 deletedStream = mInputStream;
1478 mInputStream.clear();
1479 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001480 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001481 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 return BAD_VALUE;
1483 }
Zhijun He5f446352014-01-22 09:49:33 -08001484 }
1485
1486 // Delete output stream or the output part of a bi-directional stream.
1487 if (outputStreamIdx != NAME_NOT_FOUND) {
1488 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 mOutputStreams.removeItem(id);
1490 }
1491
1492 // Free up the stream endpoint so that it can be used by some other stream
1493 res = deletedStream->disconnect();
1494 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 // fall through since we want to still list the stream as deleted.
1497 }
1498 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001499 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500
1501 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001502}
1503
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001504status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001505 ATRACE_CALL();
1506 ALOGV("%s: E", __FUNCTION__);
1507
1508 Mutex::Autolock il(mInterfaceLock);
1509 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001510
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001511 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001512}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001514status_t Camera3Device::getInputBufferProducer(
1515 sp<IGraphicBufferProducer> *producer) {
1516 Mutex::Autolock il(mInterfaceLock);
1517 Mutex::Autolock l(mLock);
1518
1519 if (producer == NULL) {
1520 return BAD_VALUE;
1521 } else if (mInputStream == NULL) {
1522 return INVALID_OPERATION;
1523 }
1524
1525 return mInputStream->getInputBufferProducer(producer);
1526}
1527
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001528status_t Camera3Device::createDefaultRequest(int templateId,
1529 CameraMetadata *request) {
1530 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001531 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001532
1533 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1534 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1535 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1536 return BAD_VALUE;
1537 }
1538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 Mutex::Autolock l(mLock);
1541
1542 switch (mStatus) {
1543 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001544 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return INVALID_OPERATION;
1546 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001547 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 case STATUS_UNCONFIGURED:
1550 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 case STATUS_ACTIVE:
1552 // OK
1553 break;
1554 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558
Zhijun Hea1530f12014-09-14 12:44:20 -07001559 if (!mRequestTemplateCache[templateId].isEmpty()) {
1560 *request = mRequestTemplateCache[templateId];
1561 return OK;
1562 }
1563
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001564 camera_metadata_t *rawRequest;
1565 status_t res = mInterface->constructDefaultRequestSettings(
1566 (camera3_request_template_t) templateId, &rawRequest);
1567 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001568 ALOGI("%s: template %d is not supported on this camera device",
1569 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001570 return res;
1571 } else if (res != OK) {
1572 CLOGE("Unable to construct request template %d: %s (%d)",
1573 templateId, strerror(-res), res);
1574 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001575 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001576
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001577 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001578
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001579 // Derive some new keys for backward compatibility
1580 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1581 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1582 int32_t defaultBoost[1] = {100};
1583 mRequestTemplateCache[templateId].update(
1584 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1585 defaultBoost, 1);
1586 }
1587
1588 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001589 return OK;
1590}
1591
1592status_t Camera3Device::waitUntilDrained() {
1593 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001596
Zhijun He69a37482014-03-23 18:44:49 -07001597 return waitUntilDrainedLocked();
1598}
1599
1600status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001601 switch (mStatus) {
1602 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 ALOGV("%s: Already idle", __FUNCTION__);
1605 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001606 case STATUS_CONFIGURED:
1607 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001608 case STATUS_ERROR:
1609 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001610 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001611 break;
1612 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001613 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return INVALID_OPERATION;
1615 }
1616
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001617 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001618 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001619 if (res != OK) {
1620 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1621 res);
1622 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001623 return res;
1624}
1625
Ruben Brunk183f0562015-08-12 12:55:02 -07001626
1627void Camera3Device::internalUpdateStatusLocked(Status status) {
1628 mStatus = status;
1629 mRecentStatusUpdates.add(mStatus);
1630 mStatusChanged.broadcast();
1631}
1632
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633// Pause to reconfigure
1634status_t Camera3Device::internalPauseAndWaitLocked() {
1635 mRequestThread->setPaused(true);
1636 mPauseStateNotify = true;
1637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001638 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1640 if (res != OK) {
1641 SET_ERR_L("Can't idle device in %f seconds!",
1642 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001643 }
1644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 return res;
1646}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001647
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001648// Resume after internalPauseAndWaitLocked
1649status_t Camera3Device::internalResumeLocked() {
1650 status_t res;
1651
1652 mRequestThread->setPaused(false);
1653
1654 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1655 if (res != OK) {
1656 SET_ERR_L("Can't transition to active in %f seconds!",
1657 kActiveTimeout/1e9);
1658 }
1659 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001660 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661}
1662
Ruben Brunk183f0562015-08-12 12:55:02 -07001663status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001664 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001665
1666 size_t startIndex = 0;
1667 if (mStatusWaiters == 0) {
1668 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1669 // this status list
1670 mRecentStatusUpdates.clear();
1671 } else {
1672 // If other threads are waiting on updates to this status list, set the position of the
1673 // first element that this list will check rather than clearing the list.
1674 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675 }
1676
Ruben Brunk183f0562015-08-12 12:55:02 -07001677 mStatusWaiters++;
1678
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679 bool stateSeen = false;
1680 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001681 if (active == (mStatus == STATUS_ACTIVE)) {
1682 // Desired state is current
1683 break;
1684 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001685
1686 res = mStatusChanged.waitRelative(mLock, timeout);
1687 if (res != OK) break;
1688
Ruben Brunk183f0562015-08-12 12:55:02 -07001689 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1690 // transitions.
1691 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1692 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1693 __FUNCTION__);
1694
1695 // Encountered desired state since we began waiting
1696 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001697 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1698 stateSeen = true;
1699 break;
1700 }
1701 }
1702 } while (!stateSeen);
1703
Ruben Brunk183f0562015-08-12 12:55:02 -07001704 mStatusWaiters--;
1705
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 return res;
1707}
1708
1709
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001710status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001711 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001712 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001714 if (listener != NULL && mListener != NULL) {
1715 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1716 }
1717 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001718 mRequestThread->setNotificationListener(listener);
1719 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001720
1721 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001722}
1723
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001724bool Camera3Device::willNotify3A() {
1725 return false;
1726}
1727
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001729 status_t res;
1730 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001732 while (mResultQueue.empty()) {
1733 res = mResultSignal.waitRelative(mOutputLock, timeout);
1734 if (res == TIMED_OUT) {
1735 return res;
1736 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001737 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1738 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001739 return res;
1740 }
1741 }
1742 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
Jianing Weicb0652e2014-03-12 18:29:36 -07001745status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001747 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001749 if (mResultQueue.empty()) {
1750 return NOT_ENOUGH_DATA;
1751 }
1752
Jianing Weicb0652e2014-03-12 18:29:36 -07001753 if (frame == NULL) {
1754 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1755 return BAD_VALUE;
1756 }
1757
1758 CaptureResult &result = *(mResultQueue.begin());
1759 frame->mResultExtras = result.mResultExtras;
1760 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001761 mResultQueue.erase(mResultQueue.begin());
1762
1763 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764}
1765
1766status_t Camera3Device::triggerAutofocus(uint32_t id) {
1767 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001770 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1771 // Mix-in this trigger into the next request and only the next request.
1772 RequestTrigger trigger[] = {
1773 {
1774 ANDROID_CONTROL_AF_TRIGGER,
1775 ANDROID_CONTROL_AF_TRIGGER_START
1776 },
1777 {
1778 ANDROID_CONTROL_AF_TRIGGER_ID,
1779 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001780 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001781 };
1782
1783 return mRequestThread->queueTrigger(trigger,
1784 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785}
1786
1787status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1788 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001791 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1792 // Mix-in this trigger into the next request and only the next request.
1793 RequestTrigger trigger[] = {
1794 {
1795 ANDROID_CONTROL_AF_TRIGGER,
1796 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1797 },
1798 {
1799 ANDROID_CONTROL_AF_TRIGGER_ID,
1800 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001801 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001802 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001803
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001804 return mRequestThread->queueTrigger(trigger,
1805 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806}
1807
1808status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1809 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001812 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1813 // Mix-in this trigger into the next request and only the next request.
1814 RequestTrigger trigger[] = {
1815 {
1816 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1817 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1818 },
1819 {
1820 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1821 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001822 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001824
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001825 return mRequestThread->queueTrigger(trigger,
1826 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001827}
1828
Jianing Weicb0652e2014-03-12 18:29:36 -07001829status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001830 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001831 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001833
Zhijun He7ef20392014-04-21 16:04:17 -07001834 {
1835 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001836 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001837 }
1838
Zhijun He491e3412013-12-27 10:57:44 -08001839 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001840 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001841 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001842 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001843 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001844 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001845 }
1846
1847 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001848}
1849
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001850status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001851 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1852}
1853
1854status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001855 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001856 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001857 Mutex::Autolock il(mInterfaceLock);
1858 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001859
1860 sp<Camera3StreamInterface> stream;
1861 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1862 if (outputStreamIdx == NAME_NOT_FOUND) {
1863 CLOGE("Stream %d does not exist", streamId);
1864 return BAD_VALUE;
1865 }
1866
1867 stream = mOutputStreams.editValueAt(outputStreamIdx);
1868
1869 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001870 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001871 return BAD_VALUE;
1872 }
1873
1874 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001875 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001876 return BAD_VALUE;
1877 }
1878
Ruben Brunkc78ac262015-08-13 17:58:46 -07001879 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001880}
1881
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001882status_t Camera3Device::tearDown(int streamId) {
1883 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001884 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001885 Mutex::Autolock il(mInterfaceLock);
1886 Mutex::Autolock l(mLock);
1887
1888 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1889 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001890 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001891 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001892 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001893 return NO_INIT;
1894 }
1895
1896 sp<Camera3StreamInterface> stream;
1897 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1898 if (outputStreamIdx == NAME_NOT_FOUND) {
1899 CLOGE("Stream %d does not exist", streamId);
1900 return BAD_VALUE;
1901 }
1902
1903 stream = mOutputStreams.editValueAt(outputStreamIdx);
1904
1905 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1906 CLOGE("Stream %d is a target of a in-progress request", streamId);
1907 return BAD_VALUE;
1908 }
1909
1910 return stream->tearDown();
1911}
1912
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001913status_t Camera3Device::addBufferListenerForStream(int streamId,
1914 wp<Camera3StreamBufferListener> listener) {
1915 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001916 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001917 Mutex::Autolock il(mInterfaceLock);
1918 Mutex::Autolock l(mLock);
1919
1920 sp<Camera3StreamInterface> stream;
1921 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1922 if (outputStreamIdx == NAME_NOT_FOUND) {
1923 CLOGE("Stream %d does not exist", streamId);
1924 return BAD_VALUE;
1925 }
1926
1927 stream = mOutputStreams.editValueAt(outputStreamIdx);
1928 stream->addBufferListener(listener);
1929
1930 return OK;
1931}
1932
Zhijun He204e3292014-07-14 17:09:23 -07001933uint32_t Camera3Device::getDeviceVersion() {
1934 ATRACE_CALL();
1935 Mutex::Autolock il(mInterfaceLock);
1936 return mDeviceVersion;
1937}
1938
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001939/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001940 * Methods called by subclasses
1941 */
1942
1943void Camera3Device::notifyStatus(bool idle) {
1944 {
1945 // Need mLock to safely update state and synchronize to current
1946 // state of methods in flight.
1947 Mutex::Autolock l(mLock);
1948 // We can get various system-idle notices from the status tracker
1949 // while starting up. Only care about them if we've actually sent
1950 // in some requests recently.
1951 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1952 return;
1953 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001954 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001955 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001956 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001957
1958 // Skip notifying listener if we're doing some user-transparent
1959 // state changes
1960 if (mPauseStateNotify) return;
1961 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001962
1963 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001964 {
1965 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001966 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001967 }
1968 if (idle && listener != NULL) {
1969 listener->notifyIdle();
1970 }
1971}
1972
Shuzhen Wang758c2152017-01-10 18:26:18 -08001973status_t Camera3Device::setConsumerSurfaces(int streamId,
1974 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001975 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001976 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1977 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001978 Mutex::Autolock il(mInterfaceLock);
1979 Mutex::Autolock l(mLock);
1980
Shuzhen Wang758c2152017-01-10 18:26:18 -08001981 if (consumers.size() == 0) {
1982 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001983 return BAD_VALUE;
1984 }
1985
1986 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1987 if (idx == NAME_NOT_FOUND) {
1988 CLOGE("Stream %d is unknown", streamId);
1989 return idx;
1990 }
1991 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001992 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001993 if (res != OK) {
1994 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1995 return res;
1996 }
1997
Shuzhen Wang0129d522016-10-30 22:43:41 -07001998 if (stream->isConsumerConfigurationDeferred()) {
1999 if (!stream->isConfiguring()) {
2000 CLOGE("Stream %d was already fully configured.", streamId);
2001 return INVALID_OPERATION;
2002 }
Zhijun He5d677d12016-05-29 16:52:39 -07002003
Shuzhen Wang0129d522016-10-30 22:43:41 -07002004 res = stream->finishConfiguration();
2005 if (res != OK) {
2006 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2007 stream->getId(), strerror(-res), res);
2008 return res;
2009 }
Zhijun He5d677d12016-05-29 16:52:39 -07002010 }
2011
2012 return OK;
2013}
2014
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002015/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016 * Camera3Device private methods
2017 */
2018
2019sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002020 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002021 ATRACE_CALL();
2022 status_t res;
2023
2024 sp<CaptureRequest> newRequest = new CaptureRequest;
2025 newRequest->mSettings = request;
2026
2027 camera_metadata_entry_t inputStreams =
2028 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2029 if (inputStreams.count > 0) {
2030 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002031 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002032 CLOGE("Request references unknown input stream %d",
2033 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002034 return NULL;
2035 }
2036 // Lazy completion of stream configuration (allocation/registration)
2037 // on first use
2038 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002039 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002041 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002042 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002043 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002044 return NULL;
2045 }
2046 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002047 // Check if stream is being prepared
2048 if (mInputStream->isPreparing()) {
2049 CLOGE("Request references an input stream that's being prepared!");
2050 return NULL;
2051 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052
2053 newRequest->mInputStream = mInputStream;
2054 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2055 }
2056
2057 camera_metadata_entry_t streams =
2058 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2059 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002060 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 return NULL;
2062 }
2063
2064 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002065 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002067 CLOGE("Request references unknown stream %d",
2068 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 return NULL;
2070 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002071 sp<Camera3OutputStreamInterface> stream =
2072 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
Zhijun He5d677d12016-05-29 16:52:39 -07002074 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002075 auto iter = surfaceMap.find(streams.data.i32[i]);
2076 if (iter != surfaceMap.end()) {
2077 const std::vector<size_t>& surfaces = iter->second;
2078 for (const auto& surface : surfaces) {
2079 if (stream->isConsumerConfigurationDeferred(surface)) {
2080 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2081 "due to deferred consumer", stream->getId(), surface);
2082 return NULL;
2083 }
2084 }
2085 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002086 }
2087
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 // Lazy completion of stream configuration (allocation/registration)
2089 // on first use
2090 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002091 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002093 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2094 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002095 return NULL;
2096 }
2097 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002098 // Check if stream is being prepared
2099 if (stream->isPreparing()) {
2100 CLOGE("Request references an output stream that's being prepared!");
2101 return NULL;
2102 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103
2104 newRequest->mOutputStreams.push(stream);
2105 }
2106 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002107 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002108
2109 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002110}
2111
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002112bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2113 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2114 Size size = mSupportedOpaqueInputSizes[i];
2115 if (size.width == width && size.height == height) {
2116 return true;
2117 }
2118 }
2119
2120 return false;
2121}
2122
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002123void Camera3Device::cancelStreamsConfigurationLocked() {
2124 int res = OK;
2125 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2126 res = mInputStream->cancelConfiguration();
2127 if (res != OK) {
2128 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2129 mInputStream->getId(), strerror(-res), res);
2130 }
2131 }
2132
2133 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2134 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2135 if (outputStream->isConfiguring()) {
2136 res = outputStream->cancelConfiguration();
2137 if (res != OK) {
2138 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2139 outputStream->getId(), strerror(-res), res);
2140 }
2141 }
2142 }
2143
2144 // Return state to that at start of call, so that future configures
2145 // properly clean things up
2146 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2147 mNeedConfig = true;
2148}
2149
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002150status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 ATRACE_CALL();
2152 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002153
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002155 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156 return INVALID_OPERATION;
2157 }
2158
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002159 if (operatingMode < 0) {
2160 CLOGE("Invalid operating mode: %d", operatingMode);
2161 return BAD_VALUE;
2162 }
2163
2164 bool isConstrainedHighSpeed =
2165 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2166 operatingMode;
2167
2168 if (mOperatingMode != operatingMode) {
2169 mNeedConfig = true;
2170 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2171 mOperatingMode = operatingMode;
2172 }
2173
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002174 if (!mNeedConfig) {
2175 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2176 return OK;
2177 }
2178
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002179 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2180 // adding a dummy stream instead.
2181 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2182 if (mOutputStreams.size() == 0) {
2183 addDummyStreamLocked();
2184 } else {
2185 tryRemoveDummyStreamLocked();
2186 }
2187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002188 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002189 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002190
2191 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002192 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2194
2195 Vector<camera3_stream_t*> streams;
2196 streams.setCapacity(config.num_streams);
2197
2198 if (mInputStream != NULL) {
2199 camera3_stream_t *inputStream;
2200 inputStream = mInputStream->startConfiguration();
2201 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002202 CLOGE("Can't start input stream configuration");
2203 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002204 return INVALID_OPERATION;
2205 }
2206 streams.add(inputStream);
2207 }
2208
2209 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002210
2211 // Don't configure bidi streams twice, nor add them twice to the list
2212 if (mOutputStreams[i].get() ==
2213 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2214
2215 config.num_streams--;
2216 continue;
2217 }
2218
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002219 camera3_stream_t *outputStream;
2220 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2221 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002222 CLOGE("Can't start output stream configuration");
2223 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224 return INVALID_OPERATION;
2225 }
2226 streams.add(outputStream);
2227 }
2228
2229 config.streams = streams.editArray();
2230
2231 // Do the HAL configuration; will potentially touch stream
2232 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002233
2234 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002236 if (res == BAD_VALUE) {
2237 // HAL rejected this set of streams as unsupported, clean up config
2238 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002239 CLOGE("Set of requested inputs/outputs not supported by HAL");
2240 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002241 return BAD_VALUE;
2242 } else if (res != OK) {
2243 // Some other kind of error from configure_streams - this is not
2244 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002245 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2246 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247 return res;
2248 }
2249
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002250 // Finish all stream configuration immediately.
2251 // TODO: Try to relax this later back to lazy completion, which should be
2252 // faster
2253
Igor Murashkin073f8572013-05-02 14:59:28 -07002254 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002255 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002256 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002257 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002258 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002259 cancelStreamsConfigurationLocked();
2260 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002261 }
2262 }
2263
2264 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002265 sp<Camera3OutputStreamInterface> outputStream =
2266 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002267 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002268 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002269 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002270 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002271 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002272 cancelStreamsConfigurationLocked();
2273 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002274 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002275 }
2276 }
2277
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002278 // Request thread needs to know to avoid using repeat-last-settings protocol
2279 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002280 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002281
Zhijun He90f7c372016-08-16 16:19:43 -07002282 char value[PROPERTY_VALUE_MAX];
2283 property_get("camera.fifo.disable", value, "0");
2284 int32_t disableFifo = atoi(value);
2285 if (disableFifo != 1) {
2286 // Boost priority of request thread to SCHED_FIFO.
2287 pid_t requestThreadTid = mRequestThread->getTid();
2288 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002289 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002290 if (res != OK) {
2291 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2292 strerror(-res), res);
2293 } else {
2294 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2295 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002296 }
2297
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002298 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002300 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301
Ruben Brunk183f0562015-08-12 12:55:02 -07002302 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2303 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002304
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002305 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002306
Zhijun He0a210512014-07-24 13:45:15 -07002307 // tear down the deleted streams after configure streams.
2308 mDeletedStreams.clear();
2309
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002311}
2312
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002313status_t Camera3Device::addDummyStreamLocked() {
2314 ATRACE_CALL();
2315 status_t res;
2316
2317 if (mDummyStreamId != NO_STREAM) {
2318 // Should never be adding a second dummy stream when one is already
2319 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002320 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2321 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002322 return INVALID_OPERATION;
2323 }
2324
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002325 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002326
2327 sp<Camera3OutputStreamInterface> dummyStream =
2328 new Camera3DummyStream(mNextStreamId);
2329
2330 res = mOutputStreams.add(mNextStreamId, dummyStream);
2331 if (res < 0) {
2332 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2333 return res;
2334 }
2335
2336 mDummyStreamId = mNextStreamId;
2337 mNextStreamId++;
2338
2339 return OK;
2340}
2341
2342status_t Camera3Device::tryRemoveDummyStreamLocked() {
2343 ATRACE_CALL();
2344 status_t res;
2345
2346 if (mDummyStreamId == NO_STREAM) return OK;
2347 if (mOutputStreams.size() == 1) return OK;
2348
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002349 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002350
2351 // Ok, have a dummy stream and there's at least one other output stream,
2352 // so remove the dummy
2353
2354 sp<Camera3StreamInterface> deletedStream;
2355 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2356 if (outputStreamIdx == NAME_NOT_FOUND) {
2357 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2358 return INVALID_OPERATION;
2359 }
2360
2361 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2362 mOutputStreams.removeItemsAt(outputStreamIdx);
2363
2364 // Free up the stream endpoint so that it can be used by some other stream
2365 res = deletedStream->disconnect();
2366 if (res != OK) {
2367 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2368 // fall through since we want to still list the stream as deleted.
2369 }
2370 mDeletedStreams.add(deletedStream);
2371 mDummyStreamId = NO_STREAM;
2372
2373 return res;
2374}
2375
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002376void Camera3Device::setErrorState(const char *fmt, ...) {
2377 Mutex::Autolock l(mLock);
2378 va_list args;
2379 va_start(args, fmt);
2380
2381 setErrorStateLockedV(fmt, args);
2382
2383 va_end(args);
2384}
2385
2386void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2387 Mutex::Autolock l(mLock);
2388 setErrorStateLockedV(fmt, args);
2389}
2390
2391void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2392 va_list args;
2393 va_start(args, fmt);
2394
2395 setErrorStateLockedV(fmt, args);
2396
2397 va_end(args);
2398}
2399
2400void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002401 // Print out all error messages to log
2402 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002403 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002404
2405 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002406 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002407
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002408 mErrorCause = errorCause;
2409
2410 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002411 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002412
2413 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002414 sp<NotificationListener> listener = mListener.promote();
2415 if (listener != NULL) {
2416 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002417 CaptureResultExtras());
2418 }
2419
2420 // Save stack trace. View by dumping it later.
2421 CameraTraces::saveTrace();
2422 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002423}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424
2425/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002426 * In-flight request management
2427 */
2428
Jianing Weicb0652e2014-03-12 18:29:36 -07002429status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002430 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002431 const AeTriggerCancelOverride_t &aeTriggerCancelOverride,
2432 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002433 ATRACE_CALL();
2434 Mutex::Autolock l(mInFlightLock);
2435
2436 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002437 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002438 aeTriggerCancelOverride, hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002439 if (res < 0) return res;
2440
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002441 if (mInFlightMap.size() == 1) {
2442 mStatusTracker->markComponentActive(mInFlightStatusId);
2443 }
2444
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002445 return OK;
2446}
2447
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002448void Camera3Device::returnOutputBuffers(
2449 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2450 nsecs_t timestamp) {
2451 for (size_t i = 0; i < numBuffers; i++)
2452 {
2453 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2454 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2455 // Note: stream may be deallocated at this point, if this buffer was
2456 // the last reference to it.
2457 if (res != OK) {
2458 ALOGE("Can't return buffer to its stream: %s (%d)",
2459 strerror(-res), res);
2460 }
2461 }
2462}
2463
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002464void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2465 mInFlightMap.removeItemsAt(idx, 1);
2466
2467 // Indicate idle inFlightMap to the status tracker
2468 if (mInFlightMap.size() == 0) {
2469 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2470 }
2471}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002472
2473void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2474
2475 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2476 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2477
2478 nsecs_t sensorTimestamp = request.sensorTimestamp;
2479 nsecs_t shutterTimestamp = request.shutterTimestamp;
2480
2481 // Check if it's okay to remove the request from InFlightMap:
2482 // In the case of a successful request:
2483 // all input and output buffers, all result metadata, shutter callback
2484 // arrived.
2485 // In the case of a unsuccessful request:
2486 // all input and output buffers arrived.
2487 if (request.numBuffersLeft == 0 &&
2488 (request.requestStatus != OK ||
2489 (request.haveResultMetadata && shutterTimestamp != 0))) {
2490 ATRACE_ASYNC_END("frame capture", frameNumber);
2491
Shuzhen Wang403044a2017-02-26 23:29:04 -08002492 // Sanity check - if sensor timestamp matches shutter timestamp in the
2493 // case of request having callback.
2494 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002495 sensorTimestamp != shutterTimestamp) {
2496 SET_ERR("sensor timestamp (%" PRId64
2497 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2498 sensorTimestamp, frameNumber, shutterTimestamp);
2499 }
2500
2501 // for an unsuccessful request, it may have pending output buffers to
2502 // return.
2503 assert(request.requestStatus != OK ||
2504 request.pendingOutputBuffers.size() == 0);
2505 returnOutputBuffers(request.pendingOutputBuffers.array(),
2506 request.pendingOutputBuffers.size(), 0);
2507
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002508 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002509 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2510 }
2511
2512 // Sanity check - if we have too many in-flight frames, something has
2513 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002514 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002515 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002516 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2517 kInFlightWarnLimitHighSpeed) {
2518 CLOGE("In-flight list too large for high speed configuration: %zu",
2519 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002520 }
2521}
2522
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002523void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2524 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2525 if (result == nullptr) return;
2526
2527 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2528 (int32_t*)&frameNumber, 1) != OK) {
2529 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2530 return;
2531 }
2532
2533 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2534 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2535 return;
2536 }
2537
2538 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2539
2540 // Valid result, insert into queue
2541 List<CaptureResult>::iterator queuedResult =
2542 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2543 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2544 ", burstId = %" PRId32, __FUNCTION__,
2545 queuedResult->mResultExtras.requestId,
2546 queuedResult->mResultExtras.frameNumber,
2547 queuedResult->mResultExtras.burstId);
2548
2549 mResultSignal.signal();
2550}
2551
2552
2553void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2554 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2555 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2556 Mutex::Autolock l(mOutputLock);
2557
2558 CaptureResult captureResult;
2559 captureResult.mResultExtras = resultExtras;
2560 captureResult.mMetadata = partialResult;
2561
2562 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2563}
2564
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002565
2566void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2567 CaptureResultExtras &resultExtras,
2568 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002569 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002570 bool reprocess,
2571 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002572 if (pendingMetadata.isEmpty())
2573 return;
2574
2575 Mutex::Autolock l(mOutputLock);
2576
2577 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002578 if (reprocess) {
2579 if (frameNumber < mNextReprocessResultFrameNumber) {
2580 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002581 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002582 frameNumber, mNextReprocessResultFrameNumber);
2583 return;
2584 }
2585 mNextReprocessResultFrameNumber = frameNumber + 1;
2586 } else {
2587 if (frameNumber < mNextResultFrameNumber) {
2588 SET_ERR("Out-of-order capture result metadata submitted! "
2589 "(got frame number %d, expecting %d)",
2590 frameNumber, mNextResultFrameNumber);
2591 return;
2592 }
2593 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002594 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002595
2596 CaptureResult captureResult;
2597 captureResult.mResultExtras = resultExtras;
2598 captureResult.mMetadata = pendingMetadata;
2599
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002600 // Append any previous partials to form a complete result
2601 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2602 captureResult.mMetadata.append(collectedPartialResult);
2603 }
2604
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002605 // Derive some new keys for backward compaibility
2606 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2607 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2608 int32_t defaultBoost[1] = {100};
2609 captureResult.mMetadata.update(
2610 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2611 defaultBoost, 1);
2612 }
2613
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002614 captureResult.mMetadata.sort();
2615
2616 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002617 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2618 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002619 SET_ERR("No timestamp provided by HAL for frame %d!",
2620 frameNumber);
2621 return;
2622 }
2623
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002624 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2625 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2626
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002627 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002628}
2629
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002630/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 * Camera HAL device callback methods
2632 */
2633
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002634void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002635 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002636
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002637 status_t res;
2638
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002639 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002640 if (result->result == NULL && result->num_output_buffers == 0 &&
2641 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002642 SET_ERR("No result data provided by HAL for frame %d",
2643 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002644 return;
2645 }
Zhijun He204e3292014-07-14 17:09:23 -07002646
2647 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2648 // partial_result to 1 when metadata is included in this result.
2649 if (!mUsePartialResult &&
2650 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2651 result->result != NULL &&
2652 result->partial_result != 1) {
2653 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2654 " if partial result is not supported",
2655 frameNumber, result->partial_result);
2656 return;
2657 }
2658
2659 bool isPartialResult = false;
2660 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002661 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002662 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002663
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002664 // Get shutter timestamp and resultExtras from list of in-flight requests,
2665 // where it was added by the shutter notification for this frame. If the
2666 // shutter timestamp isn't received yet, append the output buffers to the
2667 // in-flight request and they will be returned when the shutter timestamp
2668 // arrives. Update the in-flight status and remove the in-flight entry if
2669 // all result data and shutter timestamp have been received.
2670 nsecs_t shutterTimestamp = 0;
2671
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002672 {
2673 Mutex::Autolock l(mInFlightLock);
2674 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2675 if (idx == NAME_NOT_FOUND) {
2676 SET_ERR("Unknown frame number for capture result: %d",
2677 frameNumber);
2678 return;
2679 }
2680 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002681 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2682 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002683 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002684 __FUNCTION__, request.resultExtras.requestId,
2685 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002686 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002687 // Always update the partial count to the latest one if it's not 0
2688 // (buffers only). When framework aggregates adjacent partial results
2689 // into one, the latest partial count will be used.
2690 if (result->partial_result != 0)
2691 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002692
2693 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002694 if (mUsePartialResult && result->result != NULL) {
2695 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2696 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2697 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2698 " the range of [1, %d] when metadata is included in the result",
2699 frameNumber, result->partial_result, mNumPartialResults);
2700 return;
2701 }
2702 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002703 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002704 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002705 }
Zhijun He204e3292014-07-14 17:09:23 -07002706 } else {
2707 camera_metadata_ro_entry_t partialResultEntry;
2708 res = find_camera_metadata_ro_entry(result->result,
2709 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2710 if (res != NAME_NOT_FOUND &&
2711 partialResultEntry.count > 0 &&
2712 partialResultEntry.data.u8[0] ==
2713 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2714 // A partial result. Flag this as such, and collect this
2715 // set of metadata into the in-flight entry.
2716 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002717 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002718 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002719 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002720 ANDROID_QUIRKS_PARTIAL_RESULT);
2721 }
2722 }
2723
Shuzhen Wang4a472662017-02-26 23:29:04 -08002724 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002725 // Send partial capture result
2726 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2727 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002728 }
2729 }
2730
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002731 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002732 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002733
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002734 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002735 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002736 if (request.haveResultMetadata) {
2737 SET_ERR("Called multiple times with metadata for frame %d",
2738 frameNumber);
2739 return;
2740 }
Zhijun He204e3292014-07-14 17:09:23 -07002741 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002742 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002743 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002744 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002745 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002746 request.haveResultMetadata = true;
2747 }
2748
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002749 uint32_t numBuffersReturned = result->num_output_buffers;
2750 if (result->input_buffer != NULL) {
2751 if (hasInputBufferInRequest) {
2752 numBuffersReturned += 1;
2753 } else {
2754 ALOGW("%s: Input buffer should be NULL if there is no input"
2755 " buffer sent in the request",
2756 __FUNCTION__);
2757 }
2758 }
2759 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 if (request.numBuffersLeft < 0) {
2761 SET_ERR("Too many buffers returned for frame %d",
2762 frameNumber);
2763 return;
2764 }
2765
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002766 camera_metadata_ro_entry_t entry;
2767 res = find_camera_metadata_ro_entry(result->result,
2768 ANDROID_SENSOR_TIMESTAMP, &entry);
2769 if (res == OK && entry.count == 1) {
2770 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002771 }
2772
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002773 // If shutter event isn't received yet, append the output buffers to
2774 // the in-flight request. Otherwise, return the output buffers to
2775 // streams.
2776 if (shutterTimestamp == 0) {
2777 request.pendingOutputBuffers.appendArray(result->output_buffers,
2778 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002779 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002780 returnOutputBuffers(result->output_buffers,
2781 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002782 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002783
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002784 if (result->result != NULL && !isPartialResult) {
2785 if (shutterTimestamp == 0) {
2786 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002787 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002788 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002789 CameraMetadata metadata;
2790 metadata = result->result;
2791 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002792 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2793 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002794 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002795 }
2796
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002797 removeInFlightRequestIfReadyLocked(idx);
2798 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002799
Zhijun Hef0d962a2014-06-30 10:24:11 -07002800 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002801 if (hasInputBufferInRequest) {
2802 Camera3Stream *stream =
2803 Camera3Stream::cast(result->input_buffer->stream);
2804 res = stream->returnInputBuffer(*(result->input_buffer));
2805 // Note: stream may be deallocated at this point, if this buffer was the
2806 // last reference to it.
2807 if (res != OK) {
2808 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2809 " its stream:%s (%d)", __FUNCTION__,
2810 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002811 }
2812 } else {
2813 ALOGW("%s: Input buffer should be NULL if there is no input"
2814 " buffer sent in the request, skipping input buffer return.",
2815 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002816 }
2817 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002818}
2819
2820void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002821 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002822 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002823 {
2824 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002825 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002826 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002827
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002828 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002829 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002830 return;
2831 }
2832
2833 switch (msg->type) {
2834 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002836 break;
2837 }
2838 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002839 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002840 break;
2841 }
2842 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002843 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002844 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002845 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002846}
2847
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002849 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002850
2851 // Map camera HAL error codes to ICameraDeviceCallback error codes
2852 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002853 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002854 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002855 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002856 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002857 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002859 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002860 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002861 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002862 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002863 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002864 };
2865
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002866 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002867 ((msg.error_code >= 0) &&
2868 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2869 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002870 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002871
2872 int streamId = 0;
2873 if (msg.error_stream != NULL) {
2874 Camera3Stream *stream =
2875 Camera3Stream::cast(msg.error_stream);
2876 streamId = stream->getId();
2877 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002878 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2879 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 streamId, msg.error_code);
2881
2882 CaptureResultExtras resultExtras;
2883 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002884 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 // SET_ERR calls notifyError
2886 SET_ERR("Camera HAL reported serious device error");
2887 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002888 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2889 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2890 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002891 {
2892 Mutex::Autolock l(mInFlightLock);
2893 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2894 if (idx >= 0) {
2895 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2896 r.requestStatus = msg.error_code;
2897 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002898 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2899 errorCode) {
2900 // In case of missing result check whether the buffers
2901 // returned. If they returned, then remove inflight
2902 // request.
2903 removeInFlightRequestIfReadyLocked(idx);
2904 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002905 } else {
2906 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002907 ALOGE("Camera %s: %s: cannot find in-flight request on "
2908 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002909 resultExtras.frameNumber);
2910 }
2911 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002912 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002913 if (listener != NULL) {
2914 listener->notifyError(errorCode, resultExtras);
2915 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002916 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002917 }
2918 break;
2919 default:
2920 // SET_ERR calls notifyError
2921 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2922 break;
2923 }
2924}
2925
2926void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002927 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002928 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002929
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002930 // Set timestamp for the request in the in-flight tracking
2931 // and get the request ID to send upstream
2932 {
2933 Mutex::Autolock l(mInFlightLock);
2934 idx = mInFlightMap.indexOfKey(msg.frame_number);
2935 if (idx >= 0) {
2936 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002937
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002938 // Verify ordering of shutter notifications
2939 {
2940 Mutex::Autolock l(mOutputLock);
2941 // TODO: need to track errors for tighter bounds on expected frame number.
2942 if (r.hasInputBuffer) {
2943 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2944 SET_ERR("Shutter notification out-of-order. Expected "
2945 "notification for frame %d, got frame %d",
2946 mNextReprocessShutterFrameNumber, msg.frame_number);
2947 return;
2948 }
2949 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2950 } else {
2951 if (msg.frame_number < mNextShutterFrameNumber) {
2952 SET_ERR("Shutter notification out-of-order. Expected "
2953 "notification for frame %d, got frame %d",
2954 mNextShutterFrameNumber, msg.frame_number);
2955 return;
2956 }
2957 mNextShutterFrameNumber = msg.frame_number + 1;
2958 }
2959 }
2960
Shuzhen Wang4a472662017-02-26 23:29:04 -08002961 r.shutterTimestamp = msg.timestamp;
2962 if (r.hasCallback) {
2963 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002964 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002965 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002966 // Call listener, if any
2967 if (listener != NULL) {
2968 listener->notifyShutter(r.resultExtras, msg.timestamp);
2969 }
2970 // send pending result and buffers
2971 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2972 r.collectedPartialResult, msg.frame_number,
2973 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002974 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002975 returnOutputBuffers(r.pendingOutputBuffers.array(),
2976 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2977 r.pendingOutputBuffers.clear();
2978
2979 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002980 }
2981 }
2982 if (idx < 0) {
2983 SET_ERR("Shutter notification for non-existent frame number %d",
2984 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002985 }
2986}
2987
2988
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002989CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002990 ALOGV("%s", __FUNCTION__);
2991
Igor Murashkin1e479c02013-09-06 16:55:14 -07002992 CameraMetadata retVal;
2993
2994 if (mRequestThread != NULL) {
2995 retVal = mRequestThread->getLatestRequest();
2996 }
2997
Igor Murashkin1e479c02013-09-06 16:55:14 -07002998 return retVal;
2999}
3000
Jianing Weicb0652e2014-03-12 18:29:36 -07003001
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003002void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3003 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3004 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3005}
3006
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003007/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003008 * HalInterface inner class methods
3009 */
3010
3011Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3012 mHal3Device(device) {}
3013
3014Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3015 mHal3Device(nullptr),
3016 mHidlSession(session) {}
3017
3018Camera3Device::HalInterface::HalInterface() :
3019 mHal3Device(nullptr) {}
3020
3021Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003022 mHal3Device(other.mHal3Device),
3023 mHidlSession(other.mHidlSession) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003024
3025bool Camera3Device::HalInterface::valid() {
3026 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3027}
3028
3029void Camera3Device::HalInterface::clear() {
3030 mHal3Device = nullptr;
3031 mHidlSession.clear();
3032}
3033
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003034bool Camera3Device::HalInterface::supportBatchRequest() {
3035 return mHidlSession != nullptr;
3036}
3037
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003038status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3039 camera3_request_template_t templateId,
3040 /*out*/ camera_metadata_t **requestTemplate) {
3041 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3042 if (!valid()) return INVALID_OPERATION;
3043 status_t res = OK;
3044
3045 if (mHal3Device != nullptr) {
3046 const camera_metadata *r;
3047 r = mHal3Device->ops->construct_default_request_settings(
3048 mHal3Device, templateId);
3049 if (r == nullptr) return BAD_VALUE;
3050 *requestTemplate = clone_camera_metadata(r);
3051 if (requestTemplate == nullptr) {
3052 ALOGE("%s: Unable to clone camera metadata received from HAL",
3053 __FUNCTION__);
3054 return INVALID_OPERATION;
3055 }
3056 } else {
3057 common::V1_0::Status status;
3058 RequestTemplate id;
3059 switch (templateId) {
3060 case CAMERA3_TEMPLATE_PREVIEW:
3061 id = RequestTemplate::PREVIEW;
3062 break;
3063 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3064 id = RequestTemplate::STILL_CAPTURE;
3065 break;
3066 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3067 id = RequestTemplate::VIDEO_RECORD;
3068 break;
3069 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3070 id = RequestTemplate::VIDEO_SNAPSHOT;
3071 break;
3072 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3073 id = RequestTemplate::ZERO_SHUTTER_LAG;
3074 break;
3075 case CAMERA3_TEMPLATE_MANUAL:
3076 id = RequestTemplate::MANUAL;
3077 break;
3078 default:
3079 // Unknown template ID
3080 return BAD_VALUE;
3081 }
3082 mHidlSession->constructDefaultRequestSettings(id,
3083 [&status, &requestTemplate]
3084 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3085 status = s;
3086 if (status == common::V1_0::Status::OK) {
3087 const camera_metadata *r =
3088 reinterpret_cast<const camera_metadata_t*>(request.data());
3089 size_t expectedSize = request.size();
3090 int ret = validate_camera_metadata_structure(r, &expectedSize);
3091 if (ret == OK) {
3092 *requestTemplate = clone_camera_metadata(r);
3093 if (*requestTemplate == nullptr) {
3094 ALOGE("%s: Unable to clone camera metadata received from HAL",
3095 __FUNCTION__);
3096 status = common::V1_0::Status::INTERNAL_ERROR;
3097 }
3098 } else {
3099 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3100 status = common::V1_0::Status::INTERNAL_ERROR;
3101 }
3102 }
3103 });
3104 res = CameraProviderManager::mapToStatusT(status);
3105 }
3106 return res;
3107}
3108
3109status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3110 ATRACE_NAME("CameraHal::configureStreams");
3111 if (!valid()) return INVALID_OPERATION;
3112 status_t res = OK;
3113
3114 if (mHal3Device != nullptr) {
3115 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3116 } else {
3117 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003118 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003119 StreamConfiguration requestedConfiguration;
3120 requestedConfiguration.streams.resize(config->num_streams);
3121 for (size_t i = 0; i < config->num_streams; i++) {
3122 Stream &dst = requestedConfiguration.streams[i];
3123 camera3_stream_t *src = config->streams[i];
3124
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003125 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3126 cam3stream->setBufferFreedListener(this);
3127 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128 StreamType streamType;
3129 switch (src->stream_type) {
3130 case CAMERA3_STREAM_OUTPUT:
3131 streamType = StreamType::OUTPUT;
3132 break;
3133 case CAMERA3_STREAM_INPUT:
3134 streamType = StreamType::INPUT;
3135 break;
3136 default:
3137 ALOGE("%s: Stream %d: Unsupported stream type %d",
3138 __FUNCTION__, streamId, config->streams[i]->stream_type);
3139 return BAD_VALUE;
3140 }
3141 dst.id = streamId;
3142 dst.streamType = streamType;
3143 dst.width = src->width;
3144 dst.height = src->height;
3145 dst.format = mapToPixelFormat(src->format);
Eino-Ville Talvala1a2f15d2017-03-23 15:37:22 -07003146 uint64_t consumerUsage, producerUsage;
3147 ::android_convertGralloc0To1Usage(src->usage, &producerUsage, &consumerUsage);
3148 dst.usage = consumerUsage;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003149 dst.dataSpace = mapToHidlDataspace(src->data_space);
3150 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003151
3152 activeStreams.insert(streamId);
3153 // Create Buffer ID map if necessary
3154 if (mBufferIdMaps.count(streamId) == 0) {
3155 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3156 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003157 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003158 // remove BufferIdMap for deleted streams
3159 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3160 int streamId = it->first;
3161 bool active = activeStreams.count(streamId) > 0;
3162 if (!active) {
3163 it = mBufferIdMaps.erase(it);
3164 } else {
3165 ++it;
3166 }
3167 }
3168
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003169 res = mapToStreamConfigurationMode(
3170 (camera3_stream_configuration_mode_t) config->operation_mode,
3171 /*out*/ &requestedConfiguration.operationMode);
3172 if (res != OK) {
3173 return res;
3174 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003175
3176 // Invoke configureStreams
3177
3178 HalStreamConfiguration finalConfiguration;
3179 common::V1_0::Status status;
3180 mHidlSession->configureStreams(requestedConfiguration,
3181 [&status, &finalConfiguration]
3182 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3183 finalConfiguration = halConfiguration;
3184 status = s;
3185 });
3186 if (status != common::V1_0::Status::OK ) {
3187 return CameraProviderManager::mapToStatusT(status);
3188 }
3189
3190 // And convert output stream configuration from HIDL
3191
3192 for (size_t i = 0; i < config->num_streams; i++) {
3193 camera3_stream_t *dst = config->streams[i];
3194 int streamId = Camera3Stream::cast(dst)->getId();
3195
3196 // Start scan at i, with the assumption that the stream order matches
3197 size_t realIdx = i;
3198 bool found = false;
3199 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3200 if (finalConfiguration.streams[realIdx].id == streamId) {
3201 found = true;
3202 break;
3203 }
3204 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3205 }
3206 if (!found) {
3207 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3208 __FUNCTION__, streamId);
3209 return INVALID_OPERATION;
3210 }
3211 HalStream &src = finalConfiguration.streams[realIdx];
3212
3213 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3214 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3215 if (dst->format != overrideFormat) {
3216 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3217 streamId, dst->format);
3218 }
3219 } else {
3220 // Override allowed with IMPLEMENTATION_DEFINED
3221 dst->format = overrideFormat;
3222 }
3223
3224 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3225 if (src.producerUsage != 0) {
3226 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3227 __FUNCTION__, streamId);
3228 return INVALID_OPERATION;
3229 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003230 } else {
3231 // OUTPUT
3232 if (src.consumerUsage != 0) {
3233 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3234 __FUNCTION__, streamId);
3235 return INVALID_OPERATION;
3236 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003237 }
Eino-Ville Talvala1a2f15d2017-03-23 15:37:22 -07003238 dst->usage = ::android_convertGralloc1To0Usage(src.producerUsage, src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003239 dst->max_buffers = src.maxBuffers;
3240 }
3241 }
3242 return res;
3243}
3244
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003245void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3246 /*out*/device::V3_2::CaptureRequest* captureRequest,
3247 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3248
3249 if (captureRequest == nullptr || handlesCreated == nullptr) {
3250 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3251 __FUNCTION__, captureRequest, handlesCreated);
3252 return;
3253 }
3254
3255 captureRequest->frameNumber = request->frame_number;
3256 // A null request settings maps to a size-0 CameraMetadata
3257 if (request->settings != nullptr) {
3258 captureRequest->settings.setToExternal(
3259 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3260 get_camera_metadata_size(request->settings));
3261 }
3262
3263 {
3264 std::lock_guard<std::mutex> lock(mInflightLock);
3265 if (request->input_buffer != nullptr) {
3266 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3267 buffer_handle_t buf = *(request->input_buffer->buffer);
3268 auto pair = getBufferId(buf, streamId);
3269 bool isNewBuffer = pair.first;
3270 uint64_t bufferId = pair.second;
3271 captureRequest->inputBuffer.streamId = streamId;
3272 captureRequest->inputBuffer.bufferId = bufferId;
3273 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3274 captureRequest->inputBuffer.status = BufferStatus::OK;
3275 native_handle_t *acquireFence = nullptr;
3276 if (request->input_buffer->acquire_fence != -1) {
3277 acquireFence = native_handle_create(1,0);
3278 acquireFence->data[0] = request->input_buffer->acquire_fence;
3279 handlesCreated->push_back(acquireFence);
3280 }
3281 captureRequest->inputBuffer.acquireFence = acquireFence;
3282 captureRequest->inputBuffer.releaseFence = nullptr;
3283
3284 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3285 request->input_buffer->buffer,
3286 request->input_buffer->acquire_fence);
3287 } else {
3288 captureRequest->inputBuffer.streamId = -1;
3289 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3290 }
3291
3292 captureRequest->outputBuffers.resize(request->num_output_buffers);
3293 for (size_t i = 0; i < request->num_output_buffers; i++) {
3294 const camera3_stream_buffer_t *src = request->output_buffers + i;
3295 StreamBuffer &dst = captureRequest->outputBuffers[i];
3296 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3297 buffer_handle_t buf = *(src->buffer);
3298 auto pair = getBufferId(buf, streamId);
3299 bool isNewBuffer = pair.first;
3300 dst.streamId = streamId;
3301 dst.bufferId = pair.second;
3302 dst.buffer = isNewBuffer ? buf : nullptr;
3303 dst.status = BufferStatus::OK;
3304 native_handle_t *acquireFence = nullptr;
3305 if (src->acquire_fence != -1) {
3306 acquireFence = native_handle_create(1,0);
3307 acquireFence->data[0] = src->acquire_fence;
3308 handlesCreated->push_back(acquireFence);
3309 }
3310 dst.acquireFence = acquireFence;
3311 dst.releaseFence = nullptr;
3312
3313 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3314 src->buffer, src->acquire_fence);
3315 }
3316 }
3317}
3318
3319status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3320 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3321 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3322 if (!valid()) return INVALID_OPERATION;
3323
3324 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3325 size_t batchSize = requests.size();
3326 captureRequests.resize(batchSize);
3327 std::vector<native_handle_t*> handlesCreated;
3328
3329 for (size_t i = 0; i < batchSize; i++) {
3330 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3331 }
3332
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003333 std::vector<device::V3_2::BufferCache> cachesToRemove;
3334 {
3335 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3336 for (auto& pair : mFreedBuffers) {
3337 // The stream might have been removed since onBufferFreed
3338 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3339 cachesToRemove.push_back({pair.first, pair.second});
3340 }
3341 }
3342 mFreedBuffers.clear();
3343 }
3344
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003345 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3346 *numRequestProcessed = 0;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003347 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003348 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3349 status = s;
3350 *numRequestProcessed = n;
3351 });
3352
3353 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3354 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3355 __FUNCTION__, *numRequestProcessed, batchSize);
3356 status = common::V1_0::Status::INTERNAL_ERROR;
3357 }
3358
3359 for (auto& handle : handlesCreated) {
3360 native_handle_delete(handle);
3361 }
3362 return CameraProviderManager::mapToStatusT(status);
3363}
3364
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003365status_t Camera3Device::HalInterface::processCaptureRequest(
3366 camera3_capture_request_t *request) {
3367 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003368 if (!valid()) return INVALID_OPERATION;
3369 status_t res = OK;
3370
3371 if (mHal3Device != nullptr) {
3372 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3373 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003374 uint32_t numRequestProcessed = 0;
3375 std::vector<camera3_capture_request_t*> requests(1);
3376 requests[0] = request;
3377 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003378 }
3379 return res;
3380}
3381
3382status_t Camera3Device::HalInterface::flush() {
3383 ATRACE_NAME("CameraHal::flush");
3384 if (!valid()) return INVALID_OPERATION;
3385 status_t res = OK;
3386
3387 if (mHal3Device != nullptr) {
3388 res = mHal3Device->ops->flush(mHal3Device);
3389 } else {
3390 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3391 }
3392 return res;
3393}
3394
3395status_t Camera3Device::HalInterface::dump(int fd) {
3396 ATRACE_NAME("CameraHal::dump");
3397 if (!valid()) return INVALID_OPERATION;
3398 status_t res = OK;
3399
3400 if (mHal3Device != nullptr) {
3401 mHal3Device->ops->dump(mHal3Device, fd);
3402 } else {
3403 // Handled by CameraProviderManager::dump
3404 }
3405 return res;
3406}
3407
3408status_t Camera3Device::HalInterface::close() {
3409 ATRACE_NAME("CameraHal::close()");
3410 if (!valid()) return INVALID_OPERATION;
3411 status_t res = OK;
3412
3413 if (mHal3Device != nullptr) {
3414 mHal3Device->common.close(&mHal3Device->common);
3415 } else {
3416 mHidlSession->close();
3417 }
3418 return res;
3419}
3420
3421status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003422 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003423 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003424 auto pair = std::make_pair(buffer, acquireFence);
3425 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003426 return OK;
3427}
3428
3429status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003430 int32_t frameNumber, int32_t streamId,
3431 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003432 std::lock_guard<std::mutex> lock(mInflightLock);
3433
3434 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3435 auto it = mInflightBufferMap.find(key);
3436 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003437 auto pair = it->second;
3438 *buffer = pair.first;
3439 int acquireFence = pair.second;
3440 if (acquireFence > 0) {
3441 ::close(acquireFence);
3442 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003443 mInflightBufferMap.erase(it);
3444 return OK;
3445}
3446
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003447std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3448 const buffer_handle_t& buf, int streamId) {
3449 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3450
3451 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3452 auto it = bIdMap.find(buf);
3453 if (it == bIdMap.end()) {
3454 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003455 ALOGV("stream %d now have %zu buffer caches, buf %p",
3456 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003457 return std::make_pair(true, mNextBufferId - 1);
3458 } else {
3459 return std::make_pair(false, it->second);
3460 }
3461}
3462
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003463void Camera3Device::HalInterface::onBufferFreed(
3464 int streamId, const native_handle_t* handle) {
3465 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3466 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3467 auto mapIt = mBufferIdMaps.find(streamId);
3468 if (mapIt == mBufferIdMaps.end()) {
3469 // streamId might be from a deleted stream here
3470 ALOGI("%s: stream %d has been removed",
3471 __FUNCTION__, streamId);
3472 return;
3473 }
3474 BufferIdMap& bIdMap = mapIt->second;
3475 auto it = bIdMap.find(handle);
3476 if (it == bIdMap.end()) {
3477 ALOGW("%s: cannot find buffer %p in stream %d",
3478 __FUNCTION__, handle, streamId);
3479 return;
3480 } else {
3481 bufferId = it->second;
3482 bIdMap.erase(it);
3483 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3484 __FUNCTION__, streamId, bIdMap.size(), handle);
3485 }
3486 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3487}
3488
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003489/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003490 * RequestThread inner class methods
3491 */
3492
3493Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003494 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003495 HalInterface* interface,
3496 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003497 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003498 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003499 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003500 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003501 mInterface(interface),
3502 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003503 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003504 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003505 mReconfigured(false),
3506 mDoPause(false),
3507 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003508 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003509 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003510 mCurrentAfTriggerId(0),
3511 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003512 mRepeatingLastFrameNumber(
3513 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003514 mAeLockAvailable(aeLockAvailable),
3515 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003516 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003517}
3518
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003519Camera3Device::RequestThread::~RequestThread() {}
3520
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003521void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003522 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003523 Mutex::Autolock l(mRequestLock);
3524 mListener = listener;
3525}
3526
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003527void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003528 Mutex::Autolock l(mRequestLock);
3529 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003530 // Prepare video stream for high speed recording.
3531 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003532}
3533
Jianing Wei90e59c92014-03-12 18:29:36 -07003534status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003535 List<sp<CaptureRequest> > &requests,
3536 /*out*/
3537 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003538 Mutex::Autolock l(mRequestLock);
3539 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3540 ++it) {
3541 mRequestQueue.push_back(*it);
3542 }
3543
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003544 if (lastFrameNumber != NULL) {
3545 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3546 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3547 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3548 *lastFrameNumber);
3549 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003550
Jianing Wei90e59c92014-03-12 18:29:36 -07003551 unpauseForNewRequests();
3552
3553 return OK;
3554}
3555
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003556
3557status_t Camera3Device::RequestThread::queueTrigger(
3558 RequestTrigger trigger[],
3559 size_t count) {
3560
3561 Mutex::Autolock l(mTriggerMutex);
3562 status_t ret;
3563
3564 for (size_t i = 0; i < count; ++i) {
3565 ret = queueTriggerLocked(trigger[i]);
3566
3567 if (ret != OK) {
3568 return ret;
3569 }
3570 }
3571
3572 return OK;
3573}
3574
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003575const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3576 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003577 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003578 if (d != nullptr) return d->mId;
3579 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003580}
3581
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003582status_t Camera3Device::RequestThread::queueTriggerLocked(
3583 RequestTrigger trigger) {
3584
3585 uint32_t tag = trigger.metadataTag;
3586 ssize_t index = mTriggerMap.indexOfKey(tag);
3587
3588 switch (trigger.getTagType()) {
3589 case TYPE_BYTE:
3590 // fall-through
3591 case TYPE_INT32:
3592 break;
3593 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003594 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3595 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003596 return INVALID_OPERATION;
3597 }
3598
3599 /**
3600 * Collect only the latest trigger, since we only have 1 field
3601 * in the request settings per trigger tag, and can't send more than 1
3602 * trigger per request.
3603 */
3604 if (index != NAME_NOT_FOUND) {
3605 mTriggerMap.editValueAt(index) = trigger;
3606 } else {
3607 mTriggerMap.add(tag, trigger);
3608 }
3609
3610 return OK;
3611}
3612
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003613status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003614 const RequestList &requests,
3615 /*out*/
3616 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003617 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003618 if (lastFrameNumber != NULL) {
3619 *lastFrameNumber = mRepeatingLastFrameNumber;
3620 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003621 mRepeatingRequests.clear();
3622 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3623 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003624
3625 unpauseForNewRequests();
3626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003627 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003628 return OK;
3629}
3630
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003631bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003632 if (mRepeatingRequests.empty()) {
3633 return false;
3634 }
3635 int32_t requestId = requestIn->mResultExtras.requestId;
3636 const RequestList &repeatRequests = mRepeatingRequests;
3637 // All repeating requests are guaranteed to have same id so only check first quest
3638 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3639 return (firstRequest->mResultExtras.requestId == requestId);
3640}
3641
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003642status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003643 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003644 return clearRepeatingRequestsLocked(lastFrameNumber);
3645
3646}
3647
3648status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003649 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003650 if (lastFrameNumber != NULL) {
3651 *lastFrameNumber = mRepeatingLastFrameNumber;
3652 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003653 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003654 return OK;
3655}
3656
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003657status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003658 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003659 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003660 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003661
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003662 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003663
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003664 // Send errors for all requests pending in the request queue, including
3665 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003666 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003667 if (listener != NULL) {
3668 for (RequestList::iterator it = mRequestQueue.begin();
3669 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003670 // Abort the input buffers for reprocess requests.
3671 if ((*it)->mInputStream != NULL) {
3672 camera3_stream_buffer_t inputBuffer;
3673 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3674 if (res != OK) {
3675 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3676 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3677 } else {
3678 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3679 if (res != OK) {
3680 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3681 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3682 }
3683 }
3684 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003685 // Set the frame number this request would have had, if it
3686 // had been submitted; this frame number will not be reused.
3687 // The requestId and burstId fields were set when the request was
3688 // submitted originally (in convertMetadataListToRequestListLocked)
3689 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003690 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003691 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003692 }
3693 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003694 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003695
3696 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003697 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003698 if (lastFrameNumber != NULL) {
3699 *lastFrameNumber = mRepeatingLastFrameNumber;
3700 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003701 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003702 return OK;
3703}
3704
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003705status_t Camera3Device::RequestThread::flush() {
3706 ATRACE_CALL();
3707 Mutex::Autolock l(mFlushLock);
3708
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003709 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3710 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711 }
3712
3713 return -ENOTSUP;
3714}
3715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003716void Camera3Device::RequestThread::setPaused(bool paused) {
3717 Mutex::Autolock l(mPauseLock);
3718 mDoPause = paused;
3719 mDoPauseSignal.signal();
3720}
3721
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003722status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3723 int32_t requestId, nsecs_t timeout) {
3724 Mutex::Autolock l(mLatestRequestMutex);
3725 status_t res;
3726 while (mLatestRequestId != requestId) {
3727 nsecs_t startTime = systemTime();
3728
3729 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3730 if (res != OK) return res;
3731
3732 timeout -= (systemTime() - startTime);
3733 }
3734
3735 return OK;
3736}
3737
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003738void Camera3Device::RequestThread::requestExit() {
3739 // Call parent to set up shutdown
3740 Thread::requestExit();
3741 // The exit from any possible waits
3742 mDoPauseSignal.signal();
3743 mRequestSignal.signal();
3744}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003745
Chien-Yu Chend196d612015-06-22 19:49:01 -07003746
3747/**
3748 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3749 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3750 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3751 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3752 * request.
3753 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003754void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003755 request->mAeTriggerCancelOverride.applyAeLock = false;
3756 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3757
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003758 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003759 return;
3760 }
3761
3762 camera_metadata_entry_t aePrecaptureTrigger =
3763 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3764 if (aePrecaptureTrigger.count > 0 &&
3765 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3766 // Always override CANCEL to IDLE
3767 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3768 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3769 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3770 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3771 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3772
3773 if (mAeLockAvailable == true) {
3774 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3775 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3776 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3777 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3778 request->mAeTriggerCancelOverride.applyAeLock = true;
3779 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3780 }
3781 }
3782 }
3783}
3784
3785/**
3786 * Override result metadata for cancelling AE precapture trigger applied in
3787 * handleAePrecaptureCancelRequest().
3788 */
3789void Camera3Device::overrideResultForPrecaptureCancel(
3790 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3791 if (aeTriggerCancelOverride.applyAeLock) {
3792 // Only devices <= v3.2 should have this override
3793 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3794 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3795 }
3796
3797 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3798 // Only devices <= v3.2 should have this override
3799 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3800 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3801 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3802 }
3803}
3804
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003805void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003806 bool surfaceAbandoned = false;
3807 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003808 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003809 {
3810 Mutex::Autolock l(mRequestLock);
3811 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3812 // repeating requests.
3813 for (const auto& request : mRepeatingRequests) {
3814 for (const auto& s : request->mOutputStreams) {
3815 if (s->isAbandoned()) {
3816 surfaceAbandoned = true;
3817 clearRepeatingRequestsLocked(&lastFrameNumber);
3818 break;
3819 }
3820 }
3821 if (surfaceAbandoned) {
3822 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003823 }
3824 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003825 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003826 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003827
3828 if (listener != NULL && surfaceAbandoned) {
3829 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003830 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003831}
3832
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003833bool Camera3Device::RequestThread::sendRequestsBatch() {
3834 status_t res;
3835 size_t batchSize = mNextRequests.size();
3836 std::vector<camera3_capture_request_t*> requests(batchSize);
3837 uint32_t numRequestProcessed = 0;
3838 for (size_t i = 0; i < batchSize; i++) {
3839 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3840 }
3841
3842 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3843 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3844
3845 bool triggerRemoveFailed = false;
3846 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3847 for (size_t i = 0; i < numRequestProcessed; i++) {
3848 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3849 nextRequest.submitted = true;
3850
3851
3852 // Update the latest request sent to HAL
3853 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3854 Mutex::Autolock al(mLatestRequestMutex);
3855
3856 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3857 mLatestRequest.acquire(cloned);
3858
3859 sp<Camera3Device> parent = mParent.promote();
3860 if (parent != NULL) {
3861 parent->monitorMetadata(TagMonitor::REQUEST,
3862 nextRequest.halRequest.frame_number,
3863 0, mLatestRequest);
3864 }
3865 }
3866
3867 if (nextRequest.halRequest.settings != NULL) {
3868 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3869 }
3870
3871 if (!triggerRemoveFailed) {
3872 // Remove any previously queued triggers (after unlock)
3873 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3874 if (removeTriggerRes != OK) {
3875 triggerRemoveFailed = true;
3876 triggerFailedRequest = nextRequest;
3877 }
3878 }
3879 }
3880
3881 if (triggerRemoveFailed) {
3882 SET_ERR("RequestThread: Unable to remove triggers "
3883 "(capture request %d, HAL device: %s (%d)",
3884 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3885 cleanUpFailedRequests(/*sendRequestError*/ false);
3886 return false;
3887 }
3888
3889 if (res != OK) {
3890 // Should only get a failure here for malformed requests or device-level
3891 // errors, so consider all errors fatal. Bad metadata failures should
3892 // come through notify.
3893 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3894 mNextRequests[numRequestProcessed].halRequest.frame_number,
3895 strerror(-res), res);
3896 cleanUpFailedRequests(/*sendRequestError*/ false);
3897 return false;
3898 }
3899 return true;
3900}
3901
3902bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3903 status_t res;
3904
3905 for (auto& nextRequest : mNextRequests) {
3906 // Submit request and block until ready for next one
3907 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3908 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3909
3910 if (res != OK) {
3911 // Should only get a failure here for malformed requests or device-level
3912 // errors, so consider all errors fatal. Bad metadata failures should
3913 // come through notify.
3914 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3915 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3916 res);
3917 cleanUpFailedRequests(/*sendRequestError*/ false);
3918 return false;
3919 }
3920
3921 // Mark that the request has be submitted successfully.
3922 nextRequest.submitted = true;
3923
3924 // Update the latest request sent to HAL
3925 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3926 Mutex::Autolock al(mLatestRequestMutex);
3927
3928 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3929 mLatestRequest.acquire(cloned);
3930
3931 sp<Camera3Device> parent = mParent.promote();
3932 if (parent != NULL) {
3933 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3934 0, mLatestRequest);
3935 }
3936 }
3937
3938 if (nextRequest.halRequest.settings != NULL) {
3939 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3940 }
3941
3942 // Remove any previously queued triggers (after unlock)
3943 res = removeTriggers(mPrevRequest);
3944 if (res != OK) {
3945 SET_ERR("RequestThread: Unable to remove triggers "
3946 "(capture request %d, HAL device: %s (%d)",
3947 nextRequest.halRequest.frame_number, strerror(-res), res);
3948 cleanUpFailedRequests(/*sendRequestError*/ false);
3949 return false;
3950 }
3951 }
3952 return true;
3953}
3954
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003955bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003956 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003957 status_t res;
3958
3959 // Handle paused state.
3960 if (waitIfPaused()) {
3961 return true;
3962 }
3963
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003964 // Wait for the next batch of requests.
3965 waitForNextRequestBatch();
3966 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003967 return true;
3968 }
3969
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003970 // Get the latest request ID, if any
3971 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003972 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003973 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003974 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003975 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003976 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003977 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3978 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003979 }
3980
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003981 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003982 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003983 if (res == TIMED_OUT) {
3984 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003985 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003986 // Check if any stream is abandoned.
3987 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003988 return true;
3989 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003990 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003991 return false;
3992 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003993
Zhijun Hecc27e112013-10-03 16:12:43 -07003994 // Inform waitUntilRequestProcessed thread of a new request ID
3995 {
3996 Mutex::Autolock al(mLatestRequestMutex);
3997
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003998 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003999 mLatestRequestSignal.signal();
4000 }
4001
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004002 // Submit a batch of requests to HAL.
4003 // Use flush lock only when submitting multilple requests in a batch.
4004 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4005 // which may take a long time to finish so synchronizing flush() and
4006 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4007 // For now, only synchronize for high speed recording and we should figure something out for
4008 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004009 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004010
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004011 if (useFlushLock) {
4012 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004013 }
4014
Zhijun Hef0645c12016-08-02 00:58:11 -07004015 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004016 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004017
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004018 bool submitRequestSuccess = false;
4019 if (mInterface->supportBatchRequest()) {
4020 submitRequestSuccess = sendRequestsBatch();
4021 } else {
4022 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004023 }
4024
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004025 if (useFlushLock) {
4026 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004027 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004028
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004029 // Unset as current request
4030 {
4031 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004032 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004033 }
4034
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004035 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004036}
4037
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004038status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004039 ATRACE_CALL();
4040
Shuzhen Wang4a472662017-02-26 23:29:04 -08004041 for (size_t i = 0; i < mNextRequests.size(); i++) {
4042 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004043 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4044 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4045 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4046
4047 // Prepare a request to HAL
4048 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4049
4050 // Insert any queued triggers (before metadata is locked)
4051 status_t res = insertTriggers(captureRequest);
4052
4053 if (res < 0) {
4054 SET_ERR("RequestThread: Unable to insert triggers "
4055 "(capture request %d, HAL device: %s (%d)",
4056 halRequest->frame_number, strerror(-res), res);
4057 return INVALID_OPERATION;
4058 }
4059 int triggerCount = res;
4060 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4061 mPrevTriggers = triggerCount;
4062
4063 // If the request is the same as last, or we had triggers last time
4064 if (mPrevRequest != captureRequest || triggersMixedIn) {
4065 /**
4066 * HAL workaround:
4067 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4068 */
4069 res = addDummyTriggerIds(captureRequest);
4070 if (res != OK) {
4071 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4072 "(capture request %d, HAL device: %s (%d)",
4073 halRequest->frame_number, strerror(-res), res);
4074 return INVALID_OPERATION;
4075 }
4076
4077 /**
4078 * The request should be presorted so accesses in HAL
4079 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4080 */
4081 captureRequest->mSettings.sort();
4082 halRequest->settings = captureRequest->mSettings.getAndLock();
4083 mPrevRequest = captureRequest;
4084 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4085
4086 IF_ALOGV() {
4087 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4088 find_camera_metadata_ro_entry(
4089 halRequest->settings,
4090 ANDROID_CONTROL_AF_TRIGGER,
4091 &e
4092 );
4093 if (e.count > 0) {
4094 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4095 __FUNCTION__,
4096 halRequest->frame_number,
4097 e.data.u8[0]);
4098 }
4099 }
4100 } else {
4101 // leave request.settings NULL to indicate 'reuse latest given'
4102 ALOGVV("%s: Request settings are REUSED",
4103 __FUNCTION__);
4104 }
4105
4106 uint32_t totalNumBuffers = 0;
4107
4108 // Fill in buffers
4109 if (captureRequest->mInputStream != NULL) {
4110 halRequest->input_buffer = &captureRequest->mInputBuffer;
4111 totalNumBuffers += 1;
4112 } else {
4113 halRequest->input_buffer = NULL;
4114 }
4115
4116 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4117 captureRequest->mOutputStreams.size());
4118 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004119 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4120 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004121
4122 // Prepare video buffers for high speed recording on the first video request.
4123 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4124 // Only try to prepare video stream on the first video request.
4125 mPrepareVideoStream = false;
4126
4127 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4128 while (res == NOT_ENOUGH_DATA) {
4129 res = outputStream->prepareNextBuffer();
4130 }
4131 if (res != OK) {
4132 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4133 __FUNCTION__, strerror(-res), res);
4134 outputStream->cancelPrepare();
4135 }
4136 }
4137
Shuzhen Wang4a472662017-02-26 23:29:04 -08004138 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4139 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004140 if (res != OK) {
4141 // Can't get output buffer from gralloc queue - this could be due to
4142 // abandoned queue or other consumer misbehavior, so not a fatal
4143 // error
4144 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4145 " %s (%d)", strerror(-res), res);
4146
4147 return TIMED_OUT;
4148 }
4149 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004150
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004151 }
4152 totalNumBuffers += halRequest->num_output_buffers;
4153
4154 // Log request in the in-flight queue
4155 sp<Camera3Device> parent = mParent.promote();
4156 if (parent == NULL) {
4157 // Should not happen, and nowhere to send errors to, so just log it
4158 CLOGE("RequestThread: Parent is gone");
4159 return INVALID_OPERATION;
4160 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004161
4162 // If this request list is for constrained high speed recording (not
4163 // preview), and the current request is not the last one in the batch,
4164 // do not send callback to the app.
4165 bool hasCallback = true;
4166 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4167 hasCallback = false;
4168 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004169 res = parent->registerInFlight(halRequest->frame_number,
4170 totalNumBuffers, captureRequest->mResultExtras,
4171 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004172 captureRequest->mAeTriggerCancelOverride,
4173 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004174 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4175 ", burstId = %" PRId32 ".",
4176 __FUNCTION__,
4177 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4178 captureRequest->mResultExtras.burstId);
4179 if (res != OK) {
4180 SET_ERR("RequestThread: Unable to register new in-flight request:"
4181 " %s (%d)", strerror(-res), res);
4182 return INVALID_OPERATION;
4183 }
4184 }
4185
4186 return OK;
4187}
4188
Igor Murashkin1e479c02013-09-06 16:55:14 -07004189CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4190 Mutex::Autolock al(mLatestRequestMutex);
4191
4192 ALOGV("RequestThread::%s", __FUNCTION__);
4193
4194 return mLatestRequest;
4195}
4196
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004197bool Camera3Device::RequestThread::isStreamPending(
4198 sp<Camera3StreamInterface>& stream) {
4199 Mutex::Autolock l(mRequestLock);
4200
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004201 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004202 if (!nextRequest.submitted) {
4203 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4204 if (stream == s) return true;
4205 }
4206 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004207 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004208 }
4209
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004210 for (const auto& request : mRequestQueue) {
4211 for (const auto& s : request->mOutputStreams) {
4212 if (stream == s) return true;
4213 }
4214 if (stream == request->mInputStream) return true;
4215 }
4216
4217 for (const auto& request : mRepeatingRequests) {
4218 for (const auto& s : request->mOutputStreams) {
4219 if (stream == s) return true;
4220 }
4221 if (stream == request->mInputStream) return true;
4222 }
4223
4224 return false;
4225}
Jianing Weicb0652e2014-03-12 18:29:36 -07004226
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004227void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4228 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004229 return;
4230 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004231
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004232 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004233 // Skip the ones that have been submitted successfully.
4234 if (nextRequest.submitted) {
4235 continue;
4236 }
4237
4238 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4239 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4240 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4241
4242 if (halRequest->settings != NULL) {
4243 captureRequest->mSettings.unlock(halRequest->settings);
4244 }
4245
4246 if (captureRequest->mInputStream != NULL) {
4247 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4248 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4249 }
4250
4251 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4252 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4253 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4254 }
4255
4256 if (sendRequestError) {
4257 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004258 sp<NotificationListener> listener = mListener.promote();
4259 if (listener != NULL) {
4260 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004261 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004262 captureRequest->mResultExtras);
4263 }
4264 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004265
4266 // Remove yet-to-be submitted inflight request from inflightMap
4267 {
4268 sp<Camera3Device> parent = mParent.promote();
4269 if (parent != NULL) {
4270 Mutex::Autolock l(parent->mInFlightLock);
4271 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4272 if (idx >= 0) {
4273 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4274 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4275 parent->removeInFlightMapEntryLocked(idx);
4276 }
4277 }
4278 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004279 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004280
4281 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004282 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004283}
4284
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004285void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004286 // Optimized a bit for the simple steady-state case (single repeating
4287 // request), to avoid putting that request in the queue temporarily.
4288 Mutex::Autolock l(mRequestLock);
4289
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004290 assert(mNextRequests.empty());
4291
4292 NextRequest nextRequest;
4293 nextRequest.captureRequest = waitForNextRequestLocked();
4294 if (nextRequest.captureRequest == nullptr) {
4295 return;
4296 }
4297
4298 nextRequest.halRequest = camera3_capture_request_t();
4299 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004300 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004301
4302 // Wait for additional requests
4303 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4304
4305 for (size_t i = 1; i < batchSize; i++) {
4306 NextRequest additionalRequest;
4307 additionalRequest.captureRequest = waitForNextRequestLocked();
4308 if (additionalRequest.captureRequest == nullptr) {
4309 break;
4310 }
4311
4312 additionalRequest.halRequest = camera3_capture_request_t();
4313 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004314 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004315 }
4316
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004317 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004318 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004319 mNextRequests.size(), batchSize);
4320 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004321 }
4322
4323 return;
4324}
4325
4326sp<Camera3Device::CaptureRequest>
4327 Camera3Device::RequestThread::waitForNextRequestLocked() {
4328 status_t res;
4329 sp<CaptureRequest> nextRequest;
4330
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331 while (mRequestQueue.empty()) {
4332 if (!mRepeatingRequests.empty()) {
4333 // Always atomically enqueue all requests in a repeating request
4334 // list. Guarantees a complete in-sequence set of captures to
4335 // application.
4336 const RequestList &requests = mRepeatingRequests;
4337 RequestList::const_iterator firstRequest =
4338 requests.begin();
4339 nextRequest = *firstRequest;
4340 mRequestQueue.insert(mRequestQueue.end(),
4341 ++firstRequest,
4342 requests.end());
4343 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004344
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004345 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 break;
4348 }
4349
4350 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4351
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004352 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4353 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004354 Mutex::Autolock pl(mPauseLock);
4355 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004356 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004358 // Let the tracker know
4359 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4360 if (statusTracker != 0) {
4361 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363 }
4364 // Stop waiting for now and let thread management happen
4365 return NULL;
4366 }
4367 }
4368
4369 if (nextRequest == NULL) {
4370 // Don't have a repeating request already in hand, so queue
4371 // must have an entry now.
4372 RequestList::iterator firstRequest =
4373 mRequestQueue.begin();
4374 nextRequest = *firstRequest;
4375 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004376 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4377 sp<NotificationListener> listener = mListener.promote();
4378 if (listener != NULL) {
4379 listener->notifyRequestQueueEmpty();
4380 }
4381 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004382 }
4383
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004384 // In case we've been unpaused by setPaused clearing mDoPause, need to
4385 // update internal pause state (capture/setRepeatingRequest unpause
4386 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004387 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004388 if (mPaused) {
4389 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4390 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4391 if (statusTracker != 0) {
4392 statusTracker->markComponentActive(mStatusId);
4393 }
4394 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004395 mPaused = false;
4396
4397 // Check if we've reconfigured since last time, and reset the preview
4398 // request if so. Can't use 'NULL request == repeat' across configure calls.
4399 if (mReconfigured) {
4400 mPrevRequest.clear();
4401 mReconfigured = false;
4402 }
4403
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004404 if (nextRequest != NULL) {
4405 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004406 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4407 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004408
4409 // Since RequestThread::clear() removes buffers from the input stream,
4410 // get the right buffer here before unlocking mRequestLock
4411 if (nextRequest->mInputStream != NULL) {
4412 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4413 if (res != OK) {
4414 // Can't get input buffer from gralloc queue - this could be due to
4415 // disconnected queue or other producer misbehavior, so not a fatal
4416 // error
4417 ALOGE("%s: Can't get input buffer, skipping request:"
4418 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004419
4420 sp<NotificationListener> listener = mListener.promote();
4421 if (listener != NULL) {
4422 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004423 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004424 nextRequest->mResultExtras);
4425 }
4426 return NULL;
4427 }
4428 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004429 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004430
4431 handleAePrecaptureCancelRequest(nextRequest);
4432
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004433 return nextRequest;
4434}
4435
4436bool Camera3Device::RequestThread::waitIfPaused() {
4437 status_t res;
4438 Mutex::Autolock l(mPauseLock);
4439 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004440 if (mPaused == false) {
4441 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004442 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4443 // Let the tracker know
4444 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4445 if (statusTracker != 0) {
4446 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4447 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004451 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004452 return true;
4453 }
4454 }
4455 // We don't set mPaused to false here, because waitForNextRequest needs
4456 // to further manage the paused state in case of starvation.
4457 return false;
4458}
4459
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004460void Camera3Device::RequestThread::unpauseForNewRequests() {
4461 // With work to do, mark thread as unpaused.
4462 // If paused by request (setPaused), don't resume, to avoid
4463 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004464 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004465 Mutex::Autolock p(mPauseLock);
4466 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004467 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4468 if (mPaused) {
4469 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4470 if (statusTracker != 0) {
4471 statusTracker->markComponentActive(mStatusId);
4472 }
4473 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004474 mPaused = false;
4475 }
4476}
4477
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004478void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4479 sp<Camera3Device> parent = mParent.promote();
4480 if (parent != NULL) {
4481 va_list args;
4482 va_start(args, fmt);
4483
4484 parent->setErrorStateV(fmt, args);
4485
4486 va_end(args);
4487 }
4488}
4489
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004490status_t Camera3Device::RequestThread::insertTriggers(
4491 const sp<CaptureRequest> &request) {
4492
4493 Mutex::Autolock al(mTriggerMutex);
4494
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004495 sp<Camera3Device> parent = mParent.promote();
4496 if (parent == NULL) {
4497 CLOGE("RequestThread: Parent is gone");
4498 return DEAD_OBJECT;
4499 }
4500
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004501 CameraMetadata &metadata = request->mSettings;
4502 size_t count = mTriggerMap.size();
4503
4504 for (size_t i = 0; i < count; ++i) {
4505 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004506 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004507
4508 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4509 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4510 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004511 if (isAeTrigger) {
4512 request->mResultExtras.precaptureTriggerId = triggerId;
4513 mCurrentPreCaptureTriggerId = triggerId;
4514 } else {
4515 request->mResultExtras.afTriggerId = triggerId;
4516 mCurrentAfTriggerId = triggerId;
4517 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004518 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4519 continue; // Trigger ID tag is deprecated since device HAL 3.2
4520 }
4521 }
4522
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004523 camera_metadata_entry entry = metadata.find(tag);
4524
4525 if (entry.count > 0) {
4526 /**
4527 * Already has an entry for this trigger in the request.
4528 * Rewrite it with our requested trigger value.
4529 */
4530 RequestTrigger oldTrigger = trigger;
4531
4532 oldTrigger.entryValue = entry.data.u8[0];
4533
4534 mTriggerReplacedMap.add(tag, oldTrigger);
4535 } else {
4536 /**
4537 * More typical, no trigger entry, so we just add it
4538 */
4539 mTriggerRemovedMap.add(tag, trigger);
4540 }
4541
4542 status_t res;
4543
4544 switch (trigger.getTagType()) {
4545 case TYPE_BYTE: {
4546 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4547 res = metadata.update(tag,
4548 &entryValue,
4549 /*count*/1);
4550 break;
4551 }
4552 case TYPE_INT32:
4553 res = metadata.update(tag,
4554 &trigger.entryValue,
4555 /*count*/1);
4556 break;
4557 default:
4558 ALOGE("%s: Type not supported: 0x%x",
4559 __FUNCTION__,
4560 trigger.getTagType());
4561 return INVALID_OPERATION;
4562 }
4563
4564 if (res != OK) {
4565 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4566 ", value %d", __FUNCTION__, trigger.getTagName(),
4567 trigger.entryValue);
4568 return res;
4569 }
4570
4571 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4572 trigger.getTagName(),
4573 trigger.entryValue);
4574 }
4575
4576 mTriggerMap.clear();
4577
4578 return count;
4579}
4580
4581status_t Camera3Device::RequestThread::removeTriggers(
4582 const sp<CaptureRequest> &request) {
4583 Mutex::Autolock al(mTriggerMutex);
4584
4585 CameraMetadata &metadata = request->mSettings;
4586
4587 /**
4588 * Replace all old entries with their old values.
4589 */
4590 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4591 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4592
4593 status_t res;
4594
4595 uint32_t tag = trigger.metadataTag;
4596 switch (trigger.getTagType()) {
4597 case TYPE_BYTE: {
4598 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4599 res = metadata.update(tag,
4600 &entryValue,
4601 /*count*/1);
4602 break;
4603 }
4604 case TYPE_INT32:
4605 res = metadata.update(tag,
4606 &trigger.entryValue,
4607 /*count*/1);
4608 break;
4609 default:
4610 ALOGE("%s: Type not supported: 0x%x",
4611 __FUNCTION__,
4612 trigger.getTagType());
4613 return INVALID_OPERATION;
4614 }
4615
4616 if (res != OK) {
4617 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4618 ", trigger value %d", __FUNCTION__,
4619 trigger.getTagName(), trigger.entryValue);
4620 return res;
4621 }
4622 }
4623 mTriggerReplacedMap.clear();
4624
4625 /**
4626 * Remove all new entries.
4627 */
4628 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4629 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4630 status_t res = metadata.erase(trigger.metadataTag);
4631
4632 if (res != OK) {
4633 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4634 ", trigger value %d", __FUNCTION__,
4635 trigger.getTagName(), trigger.entryValue);
4636 return res;
4637 }
4638 }
4639 mTriggerRemovedMap.clear();
4640
4641 return OK;
4642}
4643
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004644status_t Camera3Device::RequestThread::addDummyTriggerIds(
4645 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004646 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004647 static const int32_t dummyTriggerId = 1;
4648 status_t res;
4649
4650 CameraMetadata &metadata = request->mSettings;
4651
4652 // If AF trigger is active, insert a dummy AF trigger ID if none already
4653 // exists
4654 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4655 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4656 if (afTrigger.count > 0 &&
4657 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4658 afId.count == 0) {
4659 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4660 if (res != OK) return res;
4661 }
4662
4663 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4664 // if none already exists
4665 camera_metadata_entry pcTrigger =
4666 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4667 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4668 if (pcTrigger.count > 0 &&
4669 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4670 pcId.count == 0) {
4671 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4672 &dummyTriggerId, 1);
4673 if (res != OK) return res;
4674 }
4675
4676 return OK;
4677}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004678
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004679/**
4680 * PreparerThread inner class methods
4681 */
4682
4683Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004684 Thread(/*canCallJava*/false), mListener(nullptr),
4685 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004686}
4687
4688Camera3Device::PreparerThread::~PreparerThread() {
4689 Thread::requestExitAndWait();
4690 if (mCurrentStream != nullptr) {
4691 mCurrentStream->cancelPrepare();
4692 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4693 mCurrentStream.clear();
4694 }
4695 clear();
4696}
4697
Ruben Brunkc78ac262015-08-13 17:58:46 -07004698status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004699 status_t res;
4700
4701 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004702 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004703
Ruben Brunkc78ac262015-08-13 17:58:46 -07004704 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004705 if (res == OK) {
4706 // No preparation needed, fire listener right off
4707 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004708 if (listener != NULL) {
4709 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004710 }
4711 return OK;
4712 } else if (res != NOT_ENOUGH_DATA) {
4713 return res;
4714 }
4715
4716 // Need to prepare, start up thread if necessary
4717 if (!mActive) {
4718 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4719 // isn't running
4720 Thread::requestExitAndWait();
4721 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4722 if (res != OK) {
4723 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004724 if (listener != NULL) {
4725 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004726 }
4727 return res;
4728 }
4729 mCancelNow = false;
4730 mActive = true;
4731 ALOGV("%s: Preparer stream started", __FUNCTION__);
4732 }
4733
4734 // queue up the work
4735 mPendingStreams.push_back(stream);
4736 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4737
4738 return OK;
4739}
4740
4741status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004742 Mutex::Autolock l(mLock);
4743
4744 for (const auto& stream : mPendingStreams) {
4745 stream->cancelPrepare();
4746 }
4747 mPendingStreams.clear();
4748 mCancelNow = true;
4749
4750 return OK;
4751}
4752
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004753void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004754 Mutex::Autolock l(mLock);
4755 mListener = listener;
4756}
4757
4758bool Camera3Device::PreparerThread::threadLoop() {
4759 status_t res;
4760 {
4761 Mutex::Autolock l(mLock);
4762 if (mCurrentStream == nullptr) {
4763 // End thread if done with work
4764 if (mPendingStreams.empty()) {
4765 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4766 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4767 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4768 mActive = false;
4769 return false;
4770 }
4771
4772 // Get next stream to prepare
4773 auto it = mPendingStreams.begin();
4774 mCurrentStream = *it;
4775 mPendingStreams.erase(it);
4776 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4777 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4778 } else if (mCancelNow) {
4779 mCurrentStream->cancelPrepare();
4780 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4781 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4782 mCurrentStream.clear();
4783 mCancelNow = false;
4784 return true;
4785 }
4786 }
4787
4788 res = mCurrentStream->prepareNextBuffer();
4789 if (res == NOT_ENOUGH_DATA) return true;
4790 if (res != OK) {
4791 // Something bad happened; try to recover by cancelling prepare and
4792 // signalling listener anyway
4793 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4794 mCurrentStream->getId(), res, strerror(-res));
4795 mCurrentStream->cancelPrepare();
4796 }
4797
4798 // This stream has finished, notify listener
4799 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004800 sp<NotificationListener> listener = mListener.promote();
4801 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004802 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4803 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004804 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004805 }
4806
4807 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4808 mCurrentStream.clear();
4809
4810 return true;
4811}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004812
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004813/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004814 * Static callback forwarding methods from HAL to instance
4815 */
4816
4817void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4818 const camera3_capture_result *result) {
4819 Camera3Device *d =
4820 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004821
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004822 d->processCaptureResult(result);
4823}
4824
4825void Camera3Device::sNotify(const camera3_callback_ops *cb,
4826 const camera3_notify_msg *msg) {
4827 Camera3Device *d =
4828 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4829 d->notify(msg);
4830}
4831
4832}; // namespace android