blob: a357be105b603edb8516f6c77ad62695305c6d92 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
54#include "device3/Camera3ZslStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070055#include "device3/Camera3DummyStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070066 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070067 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070068 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070069 mUsePartialResult(false),
70 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080071 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070072 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070073 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070074 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070075 mNextReprocessShutterFrameNumber(0),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070076 mListener(NULL)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080077{
78 ATRACE_CALL();
79 camera3_callback_ops::notify = &sNotify;
80 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082}
83
84Camera3Device::~Camera3Device()
85{
86 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080087 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080088 disconnect();
89}
90
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080092 return mId;
93}
94
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080095/**
96 * CameraDeviceBase interface
97 */
98
Yin-Chia Yehe074a932015-01-30 10:29:02 -080099status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700102 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800103 Mutex::Autolock l(mLock);
104
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800106 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700107 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108 return INVALID_OPERATION;
109 }
110
111 /** Open HAL device */
112
113 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800114
115 camera3_device_t *device;
116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117 ATRACE_BEGIN("CameraHal::open");
118 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800119 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800120 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800121
122 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700123 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800124 return res;
125 }
126
127 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700129 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700130 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800132 device->common.version);
133 device->common.close(&device->common);
134 return BAD_VALUE;
135 }
136
137 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800138 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800139 if (res != OK) return res;
140
141 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700142 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
143 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700144 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800145 device->common.close(&device->common);
146 return BAD_VALUE;
147 }
148
149 /** Initialize device with callback functions */
150
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800151 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800152 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700153 ATRACE_END();
154
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800155 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700156 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
157 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800158 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800159 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800160 }
161
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800162 /** Everything is good to go */
163
164 mDeviceVersion = device->common.version;
165 mDeviceInfo = info.static_camera_characteristics;
166 mInterface = std::make_unique<HalInterface>(device);
167
168 return initializeCommonLocked();
169}
170
171status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
172 ATRACE_CALL();
173 Mutex::Autolock il(mInterfaceLock);
174 Mutex::Autolock l(mLock);
175
176 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
177 if (mStatus != STATUS_UNINITIALIZED) {
178 CLOGE("Already initialized!");
179 return INVALID_OPERATION;
180 }
181 if (manager == nullptr) return INVALID_OPERATION;
182
183 sp<ICameraDeviceSession> session;
184 ATRACE_BEGIN("CameraHal::openSession");
185 status_t res = manager->openSession(String8::std_string(mId), this,
186 /*out*/ &session);
187 ATRACE_END();
188 if (res != OK) {
189 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
190 return res;
191 }
192
193 res = manager->getCameraCharacteristics(String8::std_string(mId), &mDeviceInfo);
194 if (res != OK) {
195 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
196 session->close();
197 return res;
198 }
199 hardware::hidl_version version = session->getInterfaceVersion();
200 mDeviceVersion = HARDWARE_DEVICE_API_VERSION(version.get_major(), version.get_minor());
201 mInterface = std::make_unique<HalInterface>(session);
202
203 return initializeCommonLocked();
204}
205
206status_t Camera3Device::initializeCommonLocked() {
207
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700208 /** Start up status tracker thread */
209 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800210 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700211 if (res != OK) {
212 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
213 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800214 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700215 mStatusTracker.clear();
216 return res;
217 }
218
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700219 /** Register in-flight map to the status tracker */
220 mInFlightStatusId = mStatusTracker->addComponent();
221
Zhijun He125684a2015-12-26 15:07:30 -0800222 /** Create buffer manager */
223 mBufferManager = new Camera3BufferManager();
224
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700225 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800226 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
227 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
228 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700229 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
230 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
231 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800232
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700233 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
235 aeLockAvailable);
236 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800237 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700238 SET_ERR_L("Unable to start request queue thread: %s (%d)",
239 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800240 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800241 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800242 return res;
243 }
244
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700245 mPreparerThread = new PreparerThread();
246
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700247 // Determine whether we need to derive sensitivity boost values for older devices.
248 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
249 // be listed (as the default value 100)
250 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_4 &&
251 mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
252 mDerivePostRawSensKey = true;
253 }
254
Ruben Brunk183f0562015-08-12 12:55:02 -0700255 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800256 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700257 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700258 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700259 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800260
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800261 // Measure the clock domain offset between camera and video/hw_composer
262 camera_metadata_entry timestampSource =
263 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
264 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
265 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
266 mTimestampOffset = getMonoToBoottimeOffset();
267 }
268
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700269 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700270 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
271 camera_metadata_entry partialResultsCount =
272 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
273 if (partialResultsCount.count > 0) {
274 mNumPartialResults = partialResultsCount.data.i32[0];
275 mUsePartialResult = (mNumPartialResults > 1);
276 }
277 } else {
278 camera_metadata_entry partialResultsQuirk =
279 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
280 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
281 mUsePartialResult = true;
282 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700283 }
284
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700285 camera_metadata_entry configs =
286 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
287 for (uint32_t i = 0; i < configs.count; i += 4) {
288 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
289 configs.data.i32[i + 3] ==
290 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
291 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
292 configs.data.i32[i + 2]));
293 }
294 }
295
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800296 return OK;
297}
298
299status_t Camera3Device::disconnect() {
300 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700301 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800302
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700303 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700305 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800306
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 {
308 Mutex::Autolock l(mLock);
309 if (mStatus == STATUS_UNINITIALIZED) return res;
310
311 if (mStatus == STATUS_ACTIVE ||
312 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
313 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700314 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700316 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 } else {
318 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
319 if (res != OK) {
320 SET_ERR_L("Timeout waiting for HAL to drain");
321 // Continue to close device even in case of error
322 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700323 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800325
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 if (mStatus == STATUS_ERROR) {
327 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700329
330 if (mStatusTracker != NULL) {
331 mStatusTracker->requestExit();
332 }
333
334 if (mRequestThread != NULL) {
335 mRequestThread->requestExit();
336 }
337
338 mOutputStreams.clear();
339 mInputStream.clear();
340 }
341
342 // Joining done without holding mLock, otherwise deadlocks may ensue
343 // as the threads try to access parent state
344 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
345 // HAL may be in a bad state, so waiting for request thread
346 // (which may be stuck in the HAL processCaptureRequest call)
347 // could be dangerous.
348 mRequestThread->join();
349 }
350
351 if (mStatusTracker != NULL) {
352 mStatusTracker->join();
353 }
354
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800355 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 {
357 Mutex::Autolock l(mLock);
358
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800359 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700360 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800361 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800362
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800363 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800365
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700366 // Call close without internal mutex held, as the HAL close may need to
367 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800368 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700369
370 {
371 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800372 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700373 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800375
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700376 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700377 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800378}
379
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380// For dumping/debugging only -
381// try to acquire a lock a few times, eventually give up to proceed with
382// debug/dump operations
383bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
384 bool gotLock = false;
385 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
386 if (lock.tryLock() == NO_ERROR) {
387 gotLock = true;
388 break;
389 } else {
390 usleep(kDumpSleepDuration);
391 }
392 }
393 return gotLock;
394}
395
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700396Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
397 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
398 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
399 const int STREAM_CONFIGURATION_SIZE = 4;
400 const int STREAM_FORMAT_OFFSET = 0;
401 const int STREAM_WIDTH_OFFSET = 1;
402 const int STREAM_HEIGHT_OFFSET = 2;
403 const int STREAM_IS_INPUT_OFFSET = 3;
404 camera_metadata_ro_entry_t availableStreamConfigs =
405 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
406 if (availableStreamConfigs.count == 0 ||
407 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
408 return Size(0, 0);
409 }
410
411 // Get max jpeg size (area-wise).
412 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
413 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
414 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
415 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
416 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
417 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
418 && format == HAL_PIXEL_FORMAT_BLOB &&
419 (width * height > maxJpegWidth * maxJpegHeight)) {
420 maxJpegWidth = width;
421 maxJpegHeight = height;
422 }
423 }
424 } else {
425 camera_metadata_ro_entry availableJpegSizes =
426 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
427 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
428 return Size(0, 0);
429 }
430
431 // Get max jpeg size (area-wise).
432 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
433 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
434 > (maxJpegWidth * maxJpegHeight)) {
435 maxJpegWidth = availableJpegSizes.data.i32[i];
436 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
437 }
438 }
439 }
440 return Size(maxJpegWidth, maxJpegHeight);
441}
442
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800443nsecs_t Camera3Device::getMonoToBoottimeOffset() {
444 // try three times to get the clock offset, choose the one
445 // with the minimum gap in measurements.
446 const int tries = 3;
447 nsecs_t bestGap, measured;
448 for (int i = 0; i < tries; ++i) {
449 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
450 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
451 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
452 const nsecs_t gap = tmono2 - tmono;
453 if (i == 0 || gap < bestGap) {
454 bestGap = gap;
455 measured = tbase - ((tmono + tmono2) >> 1);
456 }
457 }
458 return measured;
459}
460
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700461/**
462 * Map Android N dataspace definitions back to Android M definitions, for
463 * use with HALv3.3 or older.
464 *
465 * Only map where correspondences exist, and otherwise preserve the value.
466 */
467android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
468 switch (dataSpace) {
469 case HAL_DATASPACE_V0_SRGB_LINEAR:
470 return HAL_DATASPACE_SRGB_LINEAR;
471 case HAL_DATASPACE_V0_SRGB:
472 return HAL_DATASPACE_SRGB;
473 case HAL_DATASPACE_V0_JFIF:
474 return HAL_DATASPACE_JFIF;
475 case HAL_DATASPACE_V0_BT601_625:
476 return HAL_DATASPACE_BT601_625;
477 case HAL_DATASPACE_V0_BT601_525:
478 return HAL_DATASPACE_BT601_525;
479 case HAL_DATASPACE_V0_BT709:
480 return HAL_DATASPACE_BT709;
481 default:
482 return dataSpace;
483 }
484}
485
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800486hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
487 int frameworkFormat) {
488 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
489}
490
491DataspaceFlags Camera3Device::mapToHidlDataspace(
492 android_dataspace dataSpace) {
493 return dataSpace;
494}
495
496ConsumerUsageFlags Camera3Device::mapToConsumerUsage(
497 uint32_t usage) {
498 return usage;
499}
500
501StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
502 switch (rotation) {
503 case CAMERA3_STREAM_ROTATION_0:
504 return StreamRotation::ROTATION_0;
505 case CAMERA3_STREAM_ROTATION_90:
506 return StreamRotation::ROTATION_90;
507 case CAMERA3_STREAM_ROTATION_180:
508 return StreamRotation::ROTATION_180;
509 case CAMERA3_STREAM_ROTATION_270:
510 return StreamRotation::ROTATION_270;
511 }
512 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
513 return StreamRotation::ROTATION_0;
514}
515
516StreamConfigurationMode Camera3Device::mapToStreamConfigurationMode(
517 camera3_stream_configuration_mode_t operationMode) {
518 switch(operationMode) {
519 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
520 return StreamConfigurationMode::NORMAL_MODE;
521 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
522 return StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
523 case CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START:
524 // Needs to be mapped by vendor extensions
525 break;
526 }
527 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
528 return StreamConfigurationMode::NORMAL_MODE;
529}
530
531camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
532 switch (status) {
533 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
534 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
535 }
536 return CAMERA3_BUFFER_STATUS_ERROR;
537}
538
539int Camera3Device::mapToFrameworkFormat(
540 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
541 return static_cast<uint32_t>(pixelFormat);
542}
543
544uint32_t Camera3Device::mapConsumerToFrameworkUsage(
545 ConsumerUsageFlags usage) {
546 return usage;
547}
548
549uint32_t Camera3Device::mapProducerToFrameworkUsage(
550 ProducerUsageFlags usage) {
551 return usage;
552}
553
Zhijun Hef7da0962014-04-24 13:27:56 -0700554ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700555 // Get max jpeg size (area-wise).
556 Size maxJpegResolution = getMaxJpegResolution();
557 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800558 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
559 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700560 return BAD_VALUE;
561 }
562
Zhijun Hef7da0962014-04-24 13:27:56 -0700563 // Get max jpeg buffer size
564 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700565 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
566 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800567 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
568 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700569 return BAD_VALUE;
570 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700571 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800572 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700573
574 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700575 float scaleFactor = ((float) (width * height)) /
576 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800577 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
578 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700579 if (jpegBufferSize > maxJpegBufferSize) {
580 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 }
582
583 return jpegBufferSize;
584}
585
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700586ssize_t Camera3Device::getPointCloudBufferSize() const {
587 const int FLOATS_PER_POINT=4;
588 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
589 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800590 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
591 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700592 return BAD_VALUE;
593 }
594 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
595 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
596 return maxBytesForPointCloud;
597}
598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800599ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800600 const int PER_CONFIGURATION_SIZE = 3;
601 const int WIDTH_OFFSET = 0;
602 const int HEIGHT_OFFSET = 1;
603 const int SIZE_OFFSET = 2;
604 camera_metadata_ro_entry rawOpaqueSizes =
605 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800606 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800607 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800608 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
609 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800610 return BAD_VALUE;
611 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700612
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800613 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
614 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
615 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
616 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
617 }
618 }
619
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
621 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800622 return BAD_VALUE;
623}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700624
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800625status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
626 ATRACE_CALL();
627 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700628
629 // Try to lock, but continue in case of failure (to avoid blocking in
630 // deadlocks)
631 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
632 bool gotLock = tryLockSpinRightRound(mLock);
633
634 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
636 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700637 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
639 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700640
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800641 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700642
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800643 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700644 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800645 int n = args.size();
646 for (int i = 0; i < n; i++) {
647 if (args[i] == templatesOption) {
648 dumpTemplates = true;
649 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700650 if (args[i] == monitorOption) {
651 if (i + 1 < n) {
652 String8 monitorTags = String8(args[i + 1]);
653 if (monitorTags == "off") {
654 mTagMonitor.disableMonitoring();
655 } else {
656 mTagMonitor.parseTagsToMonitor(monitorTags);
657 }
658 } else {
659 mTagMonitor.disableMonitoring();
660 }
661 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800662 }
663
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800664 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800666 const char *status =
667 mStatus == STATUS_ERROR ? "ERROR" :
668 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700669 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
670 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800671 mStatus == STATUS_ACTIVE ? "ACTIVE" :
672 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700673
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800674 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700675 if (mStatus == STATUS_ERROR) {
676 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
677 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800678 lines.appendFormat(" Stream configuration:\n");
Zhijun He1fa89992015-06-01 15:44:31 -0700679 lines.appendFormat(" Operation mode: %s \n", mIsConstrainedHighSpeedConfiguration ?
Eino-Ville Talvala9a179412015-06-09 13:15:16 -0700680 "CONSTRAINED HIGH SPEED VIDEO" : "NORMAL");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800681
682 if (mInputStream != NULL) {
683 write(fd, lines.string(), lines.size());
684 mInputStream->dump(fd, args);
685 } else {
686 lines.appendFormat(" No input stream.\n");
687 write(fd, lines.string(), lines.size());
688 }
689 for (size_t i = 0; i < mOutputStreams.size(); i++) {
690 mOutputStreams[i]->dump(fd,args);
691 }
692
Zhijun He431503c2016-03-07 17:30:16 -0800693 if (mBufferManager != NULL) {
694 lines = String8(" Camera3 Buffer Manager:\n");
695 write(fd, lines.string(), lines.size());
696 mBufferManager->dump(fd, args);
697 }
Zhijun He125684a2015-12-26 15:07:30 -0800698
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700699 lines = String8(" In-flight requests:\n");
700 if (mInFlightMap.size() == 0) {
701 lines.append(" None\n");
702 } else {
703 for (size_t i = 0; i < mInFlightMap.size(); i++) {
704 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700705 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700706 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800707 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700708 r.numBuffersLeft);
709 }
710 }
711 write(fd, lines.string(), lines.size());
712
Igor Murashkin1e479c02013-09-06 16:55:14 -0700713 {
714 lines = String8(" Last request sent:\n");
715 write(fd, lines.string(), lines.size());
716
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700717 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700718 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
719 }
720
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800721 if (dumpTemplates) {
722 const char *templateNames[] = {
723 "TEMPLATE_PREVIEW",
724 "TEMPLATE_STILL_CAPTURE",
725 "TEMPLATE_VIDEO_RECORD",
726 "TEMPLATE_VIDEO_SNAPSHOT",
727 "TEMPLATE_ZERO_SHUTTER_LAG",
728 "TEMPLATE_MANUAL"
729 };
730
731 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800732 camera_metadata_t *templateRequest = nullptr;
733 mInterface->constructDefaultRequestSettings(
734 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800735 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800736 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800737 lines.append(" Not supported\n");
738 write(fd, lines.string(), lines.size());
739 } else {
740 write(fd, lines.string(), lines.size());
741 dump_indented_camera_metadata(templateRequest,
742 fd, /*verbosity*/2, /*indentation*/8);
743 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800744 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800745 }
746 }
747
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700748 mTagMonitor.dumpMonitoredMetadata(fd);
749
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800750 if (mInterface->valid()) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700751 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800752 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800753 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800755
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700756 if (gotLock) mLock.unlock();
757 if (gotInterfaceLock) mInterfaceLock.unlock();
758
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800759 return OK;
760}
761
762const CameraMetadata& Camera3Device::info() const {
763 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800764 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
765 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700766 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800767 mStatus == STATUS_ERROR ?
768 "when in error state" : "before init");
769 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770 return mDeviceInfo;
771}
772
Jianing Wei90e59c92014-03-12 18:29:36 -0700773status_t Camera3Device::checkStatusOkToCaptureLocked() {
774 switch (mStatus) {
775 case STATUS_ERROR:
776 CLOGE("Device has encountered a serious error");
777 return INVALID_OPERATION;
778 case STATUS_UNINITIALIZED:
779 CLOGE("Device not initialized");
780 return INVALID_OPERATION;
781 case STATUS_UNCONFIGURED:
782 case STATUS_CONFIGURED:
783 case STATUS_ACTIVE:
784 // OK
785 break;
786 default:
787 SET_ERR_L("Unexpected status: %d", mStatus);
788 return INVALID_OPERATION;
789 }
790 return OK;
791}
792
793status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang9d066012016-09-30 11:30:20 -0700794 const List<const CameraMetadata> &metadataList, bool repeating,
795 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700796 if (requestList == NULL) {
797 CLOGE("requestList cannot be NULL.");
798 return BAD_VALUE;
799 }
800
Jianing Weicb0652e2014-03-12 18:29:36 -0700801 int32_t burstId = 0;
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 for (List<const CameraMetadata>::const_iterator it = metadataList.begin();
803 it != metadataList.end(); ++it) {
804 sp<CaptureRequest> newRequest = setUpRequestLocked(*it);
805 if (newRequest == 0) {
806 CLOGE("Can't create capture request");
807 return BAD_VALUE;
808 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700809
Shuzhen Wang9d066012016-09-30 11:30:20 -0700810 newRequest->mRepeating = repeating;
811
Jianing Weicb0652e2014-03-12 18:29:36 -0700812 // Setup burst Id and request Id
813 newRequest->mResultExtras.burstId = burstId++;
814 if (it->exists(ANDROID_REQUEST_ID)) {
815 if (it->find(ANDROID_REQUEST_ID).count == 0) {
816 CLOGE("RequestID entry exists; but must not be empty in metadata");
817 return BAD_VALUE;
818 }
819 newRequest->mResultExtras.requestId = it->find(ANDROID_REQUEST_ID).data.i32[0];
820 } else {
821 CLOGE("RequestID does not exist in metadata");
822 return BAD_VALUE;
823 }
824
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700826
827 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700828 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700829
830 // Setup batch size if this is a high speed video recording request.
831 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
832 auto firstRequest = requestList->begin();
833 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
834 if (outputStream->isVideoStream()) {
835 (*firstRequest)->mBatchSize = requestList->size();
836 break;
837 }
838 }
839 }
840
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 return OK;
842}
843
Jianing Weicb0652e2014-03-12 18:29:36 -0700844status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700847 List<const CameraMetadata> requests;
848 requests.push_back(request);
849 return captureList(requests, /*lastFrameNumber*/NULL);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800850}
851
Jianing Wei90e59c92014-03-12 18:29:36 -0700852status_t Camera3Device::submitRequestsHelper(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700853 const List<const CameraMetadata> &requests, bool repeating,
854 /*out*/
855 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700856 ATRACE_CALL();
857 Mutex::Autolock il(mInterfaceLock);
858 Mutex::Autolock l(mLock);
859
860 status_t res = checkStatusOkToCaptureLocked();
861 if (res != OK) {
862 // error logged by previous call
863 return res;
864 }
865
866 RequestList requestList;
867
Shuzhen Wang9d066012016-09-30 11:30:20 -0700868 res = convertMetadataListToRequestListLocked(requests, repeating,
869 /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 if (res != OK) {
871 // error logged by previous call
872 return res;
873 }
874
875 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700876 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700877 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700878 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700879 }
880
881 if (res == OK) {
882 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
883 if (res != OK) {
884 SET_ERR_L("Can't transition to active in %f seconds!",
885 kActiveTimeout/1e9);
886 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800887 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700888 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700889 } else {
890 CLOGE("Cannot queue request. Impossible.");
891 return BAD_VALUE;
892 }
893
894 return res;
895}
896
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800897hardware::Return<void> Camera3Device::processCaptureResult(
898 const device::V3_2::CaptureResult& result) {
899 camera3_capture_result r;
900 status_t res;
901 r.frame_number = result.frameNumber;
902 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
903 size_t expected_metadata_size = result.result.size();
904 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
905 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
906 __FUNCTION__, result.frameNumber, strerror(-res), res);
907 return hardware::Void();
908 }
909
910 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
911 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
912 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
913 auto& bDst = outputBuffers[i];
914 const StreamBuffer &bSrc = result.outputBuffers[i];
915
916 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
917 if (idx == -1) {
918 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
919 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
920 return hardware::Void();
921 }
922 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
923
924 buffer_handle_t *buffer;
925 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId,
926 &buffer);
927 if (res != OK) {
928 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
929 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
930 return hardware::Void();
931 }
932 bDst.buffer = buffer;
933 bDst.status = mapHidlBufferStatus(bSrc.status);
934 bDst.acquire_fence = -1;
935 if (bSrc.releaseFence == nullptr) {
936 bDst.release_fence = -1;
937 } else if (bSrc.releaseFence->numFds == 1) {
938 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
939 } else {
940 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
941 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
942 return hardware::Void();
943 }
944 }
945 r.num_output_buffers = outputBuffers.size();
946 r.output_buffers = outputBuffers.data();
947
948 camera3_stream_buffer_t inputBuffer;
949 if (result.inputBuffer.buffer == nullptr) {
950 r.input_buffer = nullptr;
951 } else {
952 if (mInputStream->getId() != result.inputBuffer.streamId) {
953 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
954 result.frameNumber, result.inputBuffer.streamId);
955 return hardware::Void();
956 }
957 inputBuffer.stream = mInputStream->asHalStream();
958 buffer_handle_t *buffer;
959 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
960 &buffer);
961 if (res != OK) {
962 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
963 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
964 return hardware::Void();
965 }
966 inputBuffer.buffer = buffer;
967 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
968 inputBuffer.acquire_fence = -1;
969 if (result.inputBuffer.releaseFence == nullptr) {
970 inputBuffer.release_fence = -1;
971 } else if (result.inputBuffer.releaseFence->numFds == 1) {
972 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
973 } else {
974 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
975 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
976 return hardware::Void();
977 }
978 r.input_buffer = &inputBuffer;
979 }
980
981 r.partial_result = result.partialResult;
982
983 processCaptureResult(&r);
984
985 return hardware::Void();
986}
987
988hardware::Return<void> Camera3Device::notify(
989 const NotifyMsg& msg) {
990 camera3_notify_msg m;
991 switch (msg.type) {
992 case MsgType::ERROR:
993 m.type = CAMERA3_MSG_ERROR;
994 m.message.error.frame_number = msg.msg.error.frameNumber;
995 if (msg.msg.error.errorStreamId >= 0) {
996 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
997 if (idx == -1) {
998 ALOGE("%s: Frame %d: Invalid error stream id %d",
999 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1000 return hardware::Void();
1001 }
1002 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1003 } else {
1004 m.message.error.error_stream = nullptr;
1005 }
1006 switch (msg.msg.error.errorCode) {
1007 case ErrorCode::ERROR_DEVICE:
1008 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1009 break;
1010 case ErrorCode::ERROR_REQUEST:
1011 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1012 break;
1013 case ErrorCode::ERROR_RESULT:
1014 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1015 break;
1016 case ErrorCode::ERROR_BUFFER:
1017 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1018 break;
1019 }
1020 break;
1021 case MsgType::SHUTTER:
1022 m.type = CAMERA3_MSG_SHUTTER;
1023 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1024 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1025 break;
1026 }
1027 notify(&m);
1028
1029 return hardware::Void();
1030}
1031
Jianing Weicb0652e2014-03-12 18:29:36 -07001032status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
1033 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001034 ATRACE_CALL();
1035
Jianing Weicb0652e2014-03-12 18:29:36 -07001036 return submitRequestsHelper(requests, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001037}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001038
Jianing Weicb0652e2014-03-12 18:29:36 -07001039status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1040 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001041 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001042
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001043 List<const CameraMetadata> requests;
1044 requests.push_back(request);
1045 return setStreamingRequestList(requests, /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001046}
1047
Jianing Weicb0652e2014-03-12 18:29:36 -07001048status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
1049 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001050 ATRACE_CALL();
1051
Jianing Weicb0652e2014-03-12 18:29:36 -07001052 return submitRequestsHelper(requests, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001053}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001054
1055sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
1056 const CameraMetadata &request) {
1057 status_t res;
1058
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001061 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001063 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001065 } else if (mStatus == STATUS_UNCONFIGURED) {
1066 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001067 CLOGE("No streams configured");
1068 return NULL;
1069 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001070 }
1071
1072 sp<CaptureRequest> newRequest = createCaptureRequest(request);
1073 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001074}
1075
Jianing Weicb0652e2014-03-12 18:29:36 -07001076status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001077 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001078 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001080
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001081 switch (mStatus) {
1082 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001083 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001084 return INVALID_OPERATION;
1085 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001086 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001087 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001088 case STATUS_UNCONFIGURED:
1089 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090 case STATUS_ACTIVE:
1091 // OK
1092 break;
1093 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001094 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001095 return INVALID_OPERATION;
1096 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001097 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001098
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001099 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001100}
1101
1102status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1103 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001104 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001106 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001107}
1108
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001109status_t Camera3Device::createInputStream(
1110 uint32_t width, uint32_t height, int format, int *id) {
1111 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001112 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001113 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001114 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1115 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001116
1117 status_t res;
1118 bool wasActive = false;
1119
1120 switch (mStatus) {
1121 case STATUS_ERROR:
1122 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1123 return INVALID_OPERATION;
1124 case STATUS_UNINITIALIZED:
1125 ALOGE("%s: Device not initialized", __FUNCTION__);
1126 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001127 case STATUS_UNCONFIGURED:
1128 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001129 // OK
1130 break;
1131 case STATUS_ACTIVE:
1132 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001133 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001134 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001135 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001136 return res;
1137 }
1138 wasActive = true;
1139 break;
1140 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001141 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001142 return INVALID_OPERATION;
1143 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001144 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001145
1146 if (mInputStream != 0) {
1147 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1148 return INVALID_OPERATION;
1149 }
1150
1151 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1152 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001153 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001154
1155 mInputStream = newStream;
1156
1157 *id = mNextStreamId++;
1158
1159 // Continue captures if active at start
1160 if (wasActive) {
1161 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1162 res = configureStreamsLocked();
1163 if (res != OK) {
1164 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1165 __FUNCTION__, mNextStreamId, strerror(-res), res);
1166 return res;
1167 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001168 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001169 }
1170
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001171 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001172 return OK;
1173}
1174
Igor Murashkin2fba5842013-04-22 14:03:54 -07001175
1176status_t Camera3Device::createZslStream(
1177 uint32_t width, uint32_t height,
1178 int depth,
1179 /*out*/
1180 int *id,
1181 sp<Camera3ZslStream>* zslStream) {
1182 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001183 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001184 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001185 ALOGV("Camera %s: Creating ZSL stream %d: %d x %d, depth %d",
1186 mId.string(), mNextStreamId, width, height, depth);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001187
1188 status_t res;
1189 bool wasActive = false;
1190
1191 switch (mStatus) {
1192 case STATUS_ERROR:
1193 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1194 return INVALID_OPERATION;
1195 case STATUS_UNINITIALIZED:
1196 ALOGE("%s: Device not initialized", __FUNCTION__);
1197 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001198 case STATUS_UNCONFIGURED:
1199 case STATUS_CONFIGURED:
Igor Murashkin2fba5842013-04-22 14:03:54 -07001200 // OK
1201 break;
1202 case STATUS_ACTIVE:
1203 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 res = internalPauseAndWaitLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001205 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin2fba5842013-04-22 14:03:54 -07001207 return res;
1208 }
1209 wasActive = true;
1210 break;
1211 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 SET_ERR_L("Unexpected status: %d", mStatus);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001213 return INVALID_OPERATION;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001216
1217 if (mInputStream != 0) {
1218 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1219 return INVALID_OPERATION;
1220 }
1221
1222 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
1223 width, height, depth);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001225
1226 res = mOutputStreams.add(mNextStreamId, newStream);
1227 if (res < 0) {
1228 ALOGE("%s: Can't add new stream to set: %s (%d)",
1229 __FUNCTION__, strerror(-res), res);
1230 return res;
1231 }
1232 mInputStream = newStream;
1233
Yuvraj Pasie5e3d082014-04-15 18:37:45 +05301234 mNeedConfig = true;
1235
Igor Murashkin2fba5842013-04-22 14:03:54 -07001236 *id = mNextStreamId++;
1237 *zslStream = newStream;
1238
1239 // Continue captures if active at start
1240 if (wasActive) {
1241 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1242 res = configureStreamsLocked();
1243 if (res != OK) {
1244 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1245 __FUNCTION__, mNextStreamId, strerror(-res), res);
1246 return res;
1247 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001248 internalResumeLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001249 }
1250
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001251 ALOGV("Camera %s: Created ZSL stream", mId.string());
Igor Murashkin2fba5842013-04-22 14:03:54 -07001252 return OK;
1253}
1254
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001255status_t Camera3Device::createStream(sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -08001256 uint32_t width, uint32_t height, int format, android_dataspace dataSpace,
Zhijun He5d677d12016-05-29 16:52:39 -07001257 camera3_stream_rotation_t rotation, int *id, int streamSetId, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001258 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
1262 " consumer usage 0x%x", mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Zhijun He5d677d12016-05-29 16:52:39 -07001263 consumerUsage);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001264
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 status_t res;
1266 bool wasActive = false;
1267
1268 switch (mStatus) {
1269 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return INVALID_OPERATION;
1272 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001273 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 case STATUS_UNCONFIGURED:
1276 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 // OK
1278 break;
1279 case STATUS_ACTIVE:
1280 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 return res;
1285 }
1286 wasActive = true;
1287 break;
1288 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001289 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 return INVALID_OPERATION;
1291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293
1294 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001295 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001296 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001297 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001298 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1299 }
Zhijun He5d677d12016-05-29 16:52:39 -07001300
1301 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1302 // which requires a consumer surface to be available.
1303 if (consumer == nullptr && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
1304 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1305 return BAD_VALUE;
1306 }
1307
1308 if (consumer == nullptr && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
1309 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1310 return BAD_VALUE;
1311 }
1312
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001313 // Use legacy dataspace values for older HALs
1314 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1315 dataSpace = mapToLegacyDataspace(dataSpace);
1316 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001318 ssize_t blobBufferSize;
1319 if (dataSpace != HAL_DATASPACE_DEPTH) {
1320 blobBufferSize = getJpegBufferSize(width, height);
1321 if (blobBufferSize <= 0) {
1322 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1323 return BAD_VALUE;
1324 }
1325 } else {
1326 blobBufferSize = getPointCloudBufferSize();
1327 if (blobBufferSize <= 0) {
1328 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1329 return BAD_VALUE;
1330 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001331 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001332 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001333 width, height, blobBufferSize, format, dataSpace, rotation,
1334 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001335 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1336 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1337 if (rawOpaqueBufferSize <= 0) {
1338 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1339 return BAD_VALUE;
1340 }
1341 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001342 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1343 mTimestampOffset, streamSetId);
Zhijun He5d677d12016-05-29 16:52:39 -07001344 } else if (consumer == nullptr) {
1345 newStream = new Camera3OutputStream(mNextStreamId,
1346 width, height, format, consumerUsage, dataSpace, rotation,
1347 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001348 } else {
1349 newStream = new Camera3OutputStream(mNextStreamId, consumer,
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001350 width, height, format, dataSpace, rotation,
1351 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001353 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001354
Zhijun He125684a2015-12-26 15:07:30 -08001355 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001356 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1357 * requires buffers to be statically allocated for internal static buffer registration, while
1358 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1359 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001360 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001361 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001362 newStream->setBufferManager(mBufferManager);
1363 }
1364
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 res = mOutputStreams.add(mNextStreamId, newStream);
1366 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001367 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return res;
1369 }
1370
1371 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001372 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001373
1374 // Continue captures if active at start
1375 if (wasActive) {
1376 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1377 res = configureStreamsLocked();
1378 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
1389status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1390 ATRACE_CALL();
1391 (void)outputId; (void)id;
1392
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001393 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001394 return INVALID_OPERATION;
1395}
1396
1397
1398status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001399 uint32_t *width, uint32_t *height,
1400 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001401 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001402 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001404
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 switch (mStatus) {
1406 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001407 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 return INVALID_OPERATION;
1409 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001412 case STATUS_UNCONFIGURED:
1413 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 case STATUS_ACTIVE:
1415 // OK
1416 break;
1417 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001418 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 return INVALID_OPERATION;
1420 }
1421
1422 ssize_t idx = mOutputStreams.indexOfKey(id);
1423 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001424 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001425 return idx;
1426 }
1427
1428 if (width) *width = mOutputStreams[idx]->getWidth();
1429 if (height) *height = mOutputStreams[idx]->getHeight();
1430 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001431 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001433}
1434
1435status_t Camera3Device::setStreamTransform(int id,
1436 int transform) {
1437 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001438 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001439 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 switch (mStatus) {
1442 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001444 return INVALID_OPERATION;
1445 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001446 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 case STATUS_UNCONFIGURED:
1449 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 case STATUS_ACTIVE:
1451 // OK
1452 break;
1453 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 return INVALID_OPERATION;
1456 }
1457
1458 ssize_t idx = mOutputStreams.indexOfKey(id);
1459 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001460 CLOGE("Stream %d does not exist",
1461 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 return BAD_VALUE;
1463 }
1464
1465 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001466}
1467
1468status_t Camera3Device::deleteStream(int id) {
1469 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001470 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 Mutex::Autolock l(mLock);
1472 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001473
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001474 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 // CameraDevice semantics require device to already be idle before
1477 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001479 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001480 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 }
1482
Igor Murashkin2fba5842013-04-22 14:03:54 -07001483 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001484 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 if (mInputStream != NULL && id == mInputStream->getId()) {
1486 deletedStream = mInputStream;
1487 mInputStream.clear();
1488 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001489 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return BAD_VALUE;
1492 }
Zhijun He5f446352014-01-22 09:49:33 -08001493 }
1494
1495 // Delete output stream or the output part of a bi-directional stream.
1496 if (outputStreamIdx != NAME_NOT_FOUND) {
1497 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 mOutputStreams.removeItem(id);
1499 }
1500
1501 // Free up the stream endpoint so that it can be used by some other stream
1502 res = deletedStream->disconnect();
1503 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 // fall through since we want to still list the stream as deleted.
1506 }
1507 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001508 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509
1510 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511}
1512
1513status_t Camera3Device::deleteReprocessStream(int id) {
1514 ATRACE_CALL();
1515 (void)id;
1516
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001517 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001518 return INVALID_OPERATION;
1519}
1520
Zhijun He1fa89992015-06-01 15:44:31 -07001521status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001522 ATRACE_CALL();
1523 ALOGV("%s: E", __FUNCTION__);
1524
1525 Mutex::Autolock il(mInterfaceLock);
1526 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001527
1528 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) {
1529 mNeedConfig = true;
1530 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
1531 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001532
1533 return configureStreamsLocked();
1534}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001536status_t Camera3Device::getInputBufferProducer(
1537 sp<IGraphicBufferProducer> *producer) {
1538 Mutex::Autolock il(mInterfaceLock);
1539 Mutex::Autolock l(mLock);
1540
1541 if (producer == NULL) {
1542 return BAD_VALUE;
1543 } else if (mInputStream == NULL) {
1544 return INVALID_OPERATION;
1545 }
1546
1547 return mInputStream->getInputBufferProducer(producer);
1548}
1549
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001550status_t Camera3Device::createDefaultRequest(int templateId,
1551 CameraMetadata *request) {
1552 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001553 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001554
1555 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1556 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1557 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1558 return BAD_VALUE;
1559 }
1560
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 Mutex::Autolock l(mLock);
1563
1564 switch (mStatus) {
1565 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001566 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return INVALID_OPERATION;
1568 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001569 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 case STATUS_UNCONFIGURED:
1572 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 case STATUS_ACTIVE:
1574 // OK
1575 break;
1576 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 return INVALID_OPERATION;
1579 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001580
Zhijun Hea1530f12014-09-14 12:44:20 -07001581 if (!mRequestTemplateCache[templateId].isEmpty()) {
1582 *request = mRequestTemplateCache[templateId];
1583 return OK;
1584 }
1585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001586 camera_metadata_t *rawRequest;
1587 status_t res = mInterface->constructDefaultRequestSettings(
1588 (camera3_request_template_t) templateId, &rawRequest);
1589 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001590 ALOGI("%s: template %d is not supported on this camera device",
1591 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001592 return res;
1593 } else if (res != OK) {
1594 CLOGE("Unable to construct request template %d: %s (%d)",
1595 templateId, strerror(-res), res);
1596 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001597 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001598
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001599 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001600
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001601 // Derive some new keys for backward compatibility
1602 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1603 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1604 int32_t defaultBoost[1] = {100};
1605 mRequestTemplateCache[templateId].update(
1606 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1607 defaultBoost, 1);
1608 }
1609
1610 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001611 return OK;
1612}
1613
1614status_t Camera3Device::waitUntilDrained() {
1615 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001617 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618
Zhijun He69a37482014-03-23 18:44:49 -07001619 return waitUntilDrainedLocked();
1620}
1621
1622status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 switch (mStatus) {
1624 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 ALOGV("%s: Already idle", __FUNCTION__);
1627 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 case STATUS_CONFIGURED:
1629 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 case STATUS_ERROR:
1631 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001632 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 break;
1634 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001635 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 return INVALID_OPERATION;
1637 }
1638
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001639 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001640 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001641 if (res != OK) {
1642 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1643 res);
1644 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 return res;
1646}
1647
Ruben Brunk183f0562015-08-12 12:55:02 -07001648
1649void Camera3Device::internalUpdateStatusLocked(Status status) {
1650 mStatus = status;
1651 mRecentStatusUpdates.add(mStatus);
1652 mStatusChanged.broadcast();
1653}
1654
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001655// Pause to reconfigure
1656status_t Camera3Device::internalPauseAndWaitLocked() {
1657 mRequestThread->setPaused(true);
1658 mPauseStateNotify = true;
1659
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001660 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1662 if (res != OK) {
1663 SET_ERR_L("Can't idle device in %f seconds!",
1664 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001665 }
1666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667 return res;
1668}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001669
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001670// Resume after internalPauseAndWaitLocked
1671status_t Camera3Device::internalResumeLocked() {
1672 status_t res;
1673
1674 mRequestThread->setPaused(false);
1675
1676 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1677 if (res != OK) {
1678 SET_ERR_L("Can't transition to active in %f seconds!",
1679 kActiveTimeout/1e9);
1680 }
1681 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001682 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001683}
1684
Ruben Brunk183f0562015-08-12 12:55:02 -07001685status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001687
1688 size_t startIndex = 0;
1689 if (mStatusWaiters == 0) {
1690 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1691 // this status list
1692 mRecentStatusUpdates.clear();
1693 } else {
1694 // If other threads are waiting on updates to this status list, set the position of the
1695 // first element that this list will check rather than clearing the list.
1696 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001697 }
1698
Ruben Brunk183f0562015-08-12 12:55:02 -07001699 mStatusWaiters++;
1700
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001701 bool stateSeen = false;
1702 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001703 if (active == (mStatus == STATUS_ACTIVE)) {
1704 // Desired state is current
1705 break;
1706 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001707
1708 res = mStatusChanged.waitRelative(mLock, timeout);
1709 if (res != OK) break;
1710
Ruben Brunk183f0562015-08-12 12:55:02 -07001711 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1712 // transitions.
1713 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1714 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1715 __FUNCTION__);
1716
1717 // Encountered desired state since we began waiting
1718 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001719 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1720 stateSeen = true;
1721 break;
1722 }
1723 }
1724 } while (!stateSeen);
1725
Ruben Brunk183f0562015-08-12 12:55:02 -07001726 mStatusWaiters--;
1727
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001728 return res;
1729}
1730
1731
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001732status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001734 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001735
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001736 if (listener != NULL && mListener != NULL) {
1737 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1738 }
1739 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740 mRequestThread->setNotificationListener(listener);
1741 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001742
1743 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744}
1745
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001746bool Camera3Device::willNotify3A() {
1747 return false;
1748}
1749
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001751 status_t res;
1752 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001754 while (mResultQueue.empty()) {
1755 res = mResultSignal.waitRelative(mOutputLock, timeout);
1756 if (res == TIMED_OUT) {
1757 return res;
1758 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001759 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1760 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001761 return res;
1762 }
1763 }
1764 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765}
1766
Jianing Weicb0652e2014-03-12 18:29:36 -07001767status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001768 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001769 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001770
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001771 if (mResultQueue.empty()) {
1772 return NOT_ENOUGH_DATA;
1773 }
1774
Jianing Weicb0652e2014-03-12 18:29:36 -07001775 if (frame == NULL) {
1776 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1777 return BAD_VALUE;
1778 }
1779
1780 CaptureResult &result = *(mResultQueue.begin());
1781 frame->mResultExtras = result.mResultExtras;
1782 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001783 mResultQueue.erase(mResultQueue.begin());
1784
1785 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001786}
1787
1788status_t Camera3Device::triggerAutofocus(uint32_t id) {
1789 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001790 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001791
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001792 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1793 // Mix-in this trigger into the next request and only the next request.
1794 RequestTrigger trigger[] = {
1795 {
1796 ANDROID_CONTROL_AF_TRIGGER,
1797 ANDROID_CONTROL_AF_TRIGGER_START
1798 },
1799 {
1800 ANDROID_CONTROL_AF_TRIGGER_ID,
1801 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001802 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001803 };
1804
1805 return mRequestThread->queueTrigger(trigger,
1806 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001807}
1808
1809status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1810 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001811 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001812
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001813 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1814 // Mix-in this trigger into the next request and only the next request.
1815 RequestTrigger trigger[] = {
1816 {
1817 ANDROID_CONTROL_AF_TRIGGER,
1818 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1819 },
1820 {
1821 ANDROID_CONTROL_AF_TRIGGER_ID,
1822 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001823 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001824 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001826 return mRequestThread->queueTrigger(trigger,
1827 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001828}
1829
1830status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1831 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001833
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001834 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1835 // Mix-in this trigger into the next request and only the next request.
1836 RequestTrigger trigger[] = {
1837 {
1838 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1839 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1840 },
1841 {
1842 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1843 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001844 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001845 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001847 return mRequestThread->queueTrigger(trigger,
1848 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001849}
1850
1851status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1852 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1853 ATRACE_CALL();
1854 (void)reprocessStreamId; (void)buffer; (void)listener;
1855
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001856 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001857 return INVALID_OPERATION;
1858}
1859
Jianing Weicb0652e2014-03-12 18:29:36 -07001860status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001861 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001862 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001864
Zhijun He7ef20392014-04-21 16:04:17 -07001865 {
1866 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001867 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001868 }
1869
Zhijun He491e3412013-12-27 10:57:44 -08001870 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001871 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001872 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001873 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001874 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001875 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001876 }
1877
1878 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001879}
1880
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001881status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001882 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1883}
1884
1885status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001886 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001887 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001888 Mutex::Autolock il(mInterfaceLock);
1889 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890
1891 sp<Camera3StreamInterface> stream;
1892 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1893 if (outputStreamIdx == NAME_NOT_FOUND) {
1894 CLOGE("Stream %d does not exist", streamId);
1895 return BAD_VALUE;
1896 }
1897
1898 stream = mOutputStreams.editValueAt(outputStreamIdx);
1899
1900 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001901 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001902 return BAD_VALUE;
1903 }
1904
1905 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001906 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001907 return BAD_VALUE;
1908 }
1909
Ruben Brunkc78ac262015-08-13 17:58:46 -07001910 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001911}
1912
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001913status_t Camera3Device::tearDown(int streamId) {
1914 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001915 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001916 Mutex::Autolock il(mInterfaceLock);
1917 Mutex::Autolock l(mLock);
1918
1919 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1920 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001921 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001922 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001923 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001924 return NO_INIT;
1925 }
1926
1927 sp<Camera3StreamInterface> stream;
1928 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1929 if (outputStreamIdx == NAME_NOT_FOUND) {
1930 CLOGE("Stream %d does not exist", streamId);
1931 return BAD_VALUE;
1932 }
1933
1934 stream = mOutputStreams.editValueAt(outputStreamIdx);
1935
1936 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1937 CLOGE("Stream %d is a target of a in-progress request", streamId);
1938 return BAD_VALUE;
1939 }
1940
1941 return stream->tearDown();
1942}
1943
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001944status_t Camera3Device::addBufferListenerForStream(int streamId,
1945 wp<Camera3StreamBufferListener> listener) {
1946 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001947 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001948 Mutex::Autolock il(mInterfaceLock);
1949 Mutex::Autolock l(mLock);
1950
1951 sp<Camera3StreamInterface> stream;
1952 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1953 if (outputStreamIdx == NAME_NOT_FOUND) {
1954 CLOGE("Stream %d does not exist", streamId);
1955 return BAD_VALUE;
1956 }
1957
1958 stream = mOutputStreams.editValueAt(outputStreamIdx);
1959 stream->addBufferListener(listener);
1960
1961 return OK;
1962}
1963
Zhijun He204e3292014-07-14 17:09:23 -07001964uint32_t Camera3Device::getDeviceVersion() {
1965 ATRACE_CALL();
1966 Mutex::Autolock il(mInterfaceLock);
1967 return mDeviceVersion;
1968}
1969
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001970/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001971 * Methods called by subclasses
1972 */
1973
1974void Camera3Device::notifyStatus(bool idle) {
1975 {
1976 // Need mLock to safely update state and synchronize to current
1977 // state of methods in flight.
1978 Mutex::Autolock l(mLock);
1979 // We can get various system-idle notices from the status tracker
1980 // while starting up. Only care about them if we've actually sent
1981 // in some requests recently.
1982 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1983 return;
1984 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001985 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001986 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001987 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001988
1989 // Skip notifying listener if we're doing some user-transparent
1990 // state changes
1991 if (mPauseStateNotify) return;
1992 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001993
1994 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001995 {
1996 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001997 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001998 }
1999 if (idle && listener != NULL) {
2000 listener->notifyIdle();
2001 }
2002}
2003
Zhijun He5d677d12016-05-29 16:52:39 -07002004status_t Camera3Device::setConsumerSurface(int streamId, sp<Surface> consumer) {
2005 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002006 ALOGV("%s: Camera %s: set consumer surface for stream %d", __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002007 Mutex::Autolock il(mInterfaceLock);
2008 Mutex::Autolock l(mLock);
2009
2010 if (consumer == nullptr) {
2011 CLOGE("Null consumer is passed!");
2012 return BAD_VALUE;
2013 }
2014
2015 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2016 if (idx == NAME_NOT_FOUND) {
2017 CLOGE("Stream %d is unknown", streamId);
2018 return idx;
2019 }
2020 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2021 status_t res = stream->setConsumer(consumer);
2022 if (res != OK) {
2023 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2024 return res;
2025 }
2026
2027 if (!stream->isConfiguring()) {
2028 CLOGE("Stream %d was already fully configured.", streamId);
2029 return INVALID_OPERATION;
2030 }
2031
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002032 res = stream->finishConfiguration();
Zhijun He5d677d12016-05-29 16:52:39 -07002033 if (res != OK) {
2034 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2035 stream->getId(), strerror(-res), res);
2036 return res;
2037 }
2038
2039 return OK;
2040}
2041
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002042/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002043 * Camera3Device private methods
2044 */
2045
2046sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
2047 const CameraMetadata &request) {
2048 ATRACE_CALL();
2049 status_t res;
2050
2051 sp<CaptureRequest> newRequest = new CaptureRequest;
2052 newRequest->mSettings = request;
2053
2054 camera_metadata_entry_t inputStreams =
2055 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2056 if (inputStreams.count > 0) {
2057 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002058 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002059 CLOGE("Request references unknown input stream %d",
2060 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 return NULL;
2062 }
2063 // Lazy completion of stream configuration (allocation/registration)
2064 // on first use
2065 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002066 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002068 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002070 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return NULL;
2072 }
2073 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002074 // Check if stream is being prepared
2075 if (mInputStream->isPreparing()) {
2076 CLOGE("Request references an input stream that's being prepared!");
2077 return NULL;
2078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079
2080 newRequest->mInputStream = mInputStream;
2081 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2082 }
2083
2084 camera_metadata_entry_t streams =
2085 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2086 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002087 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 return NULL;
2089 }
2090
2091 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002092 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002094 CLOGE("Request references unknown stream %d",
2095 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096 return NULL;
2097 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002098 sp<Camera3OutputStreamInterface> stream =
2099 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100
Zhijun He5d677d12016-05-29 16:52:39 -07002101 // It is illegal to include a deferred consumer output stream into a request
2102 if (stream->isConsumerConfigurationDeferred()) {
2103 CLOGE("Stream %d hasn't finished configuration yet due to deferred consumer",
2104 stream->getId());
2105 return NULL;
2106 }
2107
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002108 // Lazy completion of stream configuration (allocation/registration)
2109 // on first use
2110 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002111 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002113 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2114 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 return NULL;
2116 }
2117 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002118 // Check if stream is being prepared
2119 if (stream->isPreparing()) {
2120 CLOGE("Request references an output stream that's being prepared!");
2121 return NULL;
2122 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123
2124 newRequest->mOutputStreams.push(stream);
2125 }
2126 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002127 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128
2129 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002130}
2131
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002132bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2133 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2134 Size size = mSupportedOpaqueInputSizes[i];
2135 if (size.width == width && size.height == height) {
2136 return true;
2137 }
2138 }
2139
2140 return false;
2141}
2142
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002143void Camera3Device::cancelStreamsConfigurationLocked() {
2144 int res = OK;
2145 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2146 res = mInputStream->cancelConfiguration();
2147 if (res != OK) {
2148 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2149 mInputStream->getId(), strerror(-res), res);
2150 }
2151 }
2152
2153 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2154 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2155 if (outputStream->isConfiguring()) {
2156 res = outputStream->cancelConfiguration();
2157 if (res != OK) {
2158 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2159 outputStream->getId(), strerror(-res), res);
2160 }
2161 }
2162 }
2163
2164 // Return state to that at start of call, so that future configures
2165 // properly clean things up
2166 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2167 mNeedConfig = true;
2168}
2169
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170status_t Camera3Device::configureStreamsLocked() {
2171 ATRACE_CALL();
2172 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002173
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002175 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002176 return INVALID_OPERATION;
2177 }
2178
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002179 if (!mNeedConfig) {
2180 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2181 return OK;
2182 }
2183
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002184 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2185 // adding a dummy stream instead.
2186 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2187 if (mOutputStreams.size() == 0) {
2188 addDummyStreamLocked();
2189 } else {
2190 tryRemoveDummyStreamLocked();
2191 }
2192
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002194 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195
2196 camera3_stream_configuration config;
Zhijun He1fa89992015-06-01 15:44:31 -07002197 config.operation_mode = mIsConstrainedHighSpeedConfiguration ?
2198 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE :
2199 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2201
2202 Vector<camera3_stream_t*> streams;
2203 streams.setCapacity(config.num_streams);
2204
2205 if (mInputStream != NULL) {
2206 camera3_stream_t *inputStream;
2207 inputStream = mInputStream->startConfiguration();
2208 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002209 CLOGE("Can't start input stream configuration");
2210 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002211 return INVALID_OPERATION;
2212 }
2213 streams.add(inputStream);
2214 }
2215
2216 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002217
2218 // Don't configure bidi streams twice, nor add them twice to the list
2219 if (mOutputStreams[i].get() ==
2220 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2221
2222 config.num_streams--;
2223 continue;
2224 }
2225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002226 camera3_stream_t *outputStream;
2227 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2228 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002229 CLOGE("Can't start output stream configuration");
2230 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 return INVALID_OPERATION;
2232 }
2233 streams.add(outputStream);
2234 }
2235
2236 config.streams = streams.editArray();
2237
2238 // Do the HAL configuration; will potentially touch stream
2239 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002240
2241 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002242
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002243 if (res == BAD_VALUE) {
2244 // HAL rejected this set of streams as unsupported, clean up config
2245 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002246 CLOGE("Set of requested inputs/outputs not supported by HAL");
2247 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002248 return BAD_VALUE;
2249 } else if (res != OK) {
2250 // Some other kind of error from configure_streams - this is not
2251 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002252 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2253 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 return res;
2255 }
2256
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002257 // Finish all stream configuration immediately.
2258 // TODO: Try to relax this later back to lazy completion, which should be
2259 // faster
2260
Igor Murashkin073f8572013-05-02 14:59:28 -07002261 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002262 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002263 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002264 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002265 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002266 cancelStreamsConfigurationLocked();
2267 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002268 }
2269 }
2270
2271 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002272 sp<Camera3OutputStreamInterface> outputStream =
2273 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002274 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002275 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002276 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002277 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002278 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002279 cancelStreamsConfigurationLocked();
2280 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002281 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002282 }
2283 }
2284
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002285 // Request thread needs to know to avoid using repeat-last-settings protocol
2286 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002287 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288
Zhijun He90f7c372016-08-16 16:19:43 -07002289 char value[PROPERTY_VALUE_MAX];
2290 property_get("camera.fifo.disable", value, "0");
2291 int32_t disableFifo = atoi(value);
2292 if (disableFifo != 1) {
2293 // Boost priority of request thread to SCHED_FIFO.
2294 pid_t requestThreadTid = mRequestThread->getTid();
2295 res = requestPriority(getpid(), requestThreadTid,
2296 kRequestThreadPriority, /*asynchronous*/ false);
2297 if (res != OK) {
2298 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2299 strerror(-res), res);
2300 } else {
2301 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2302 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002303 }
2304
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002305 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002307 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308
Ruben Brunk183f0562015-08-12 12:55:02 -07002309 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2310 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002311
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002312 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002313
Zhijun He0a210512014-07-24 13:45:15 -07002314 // tear down the deleted streams after configure streams.
2315 mDeletedStreams.clear();
2316
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002318}
2319
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002320status_t Camera3Device::addDummyStreamLocked() {
2321 ATRACE_CALL();
2322 status_t res;
2323
2324 if (mDummyStreamId != NO_STREAM) {
2325 // Should never be adding a second dummy stream when one is already
2326 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002327 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2328 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002329 return INVALID_OPERATION;
2330 }
2331
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002332 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002333
2334 sp<Camera3OutputStreamInterface> dummyStream =
2335 new Camera3DummyStream(mNextStreamId);
2336
2337 res = mOutputStreams.add(mNextStreamId, dummyStream);
2338 if (res < 0) {
2339 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2340 return res;
2341 }
2342
2343 mDummyStreamId = mNextStreamId;
2344 mNextStreamId++;
2345
2346 return OK;
2347}
2348
2349status_t Camera3Device::tryRemoveDummyStreamLocked() {
2350 ATRACE_CALL();
2351 status_t res;
2352
2353 if (mDummyStreamId == NO_STREAM) return OK;
2354 if (mOutputStreams.size() == 1) return OK;
2355
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002356 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002357
2358 // Ok, have a dummy stream and there's at least one other output stream,
2359 // so remove the dummy
2360
2361 sp<Camera3StreamInterface> deletedStream;
2362 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2363 if (outputStreamIdx == NAME_NOT_FOUND) {
2364 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2365 return INVALID_OPERATION;
2366 }
2367
2368 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2369 mOutputStreams.removeItemsAt(outputStreamIdx);
2370
2371 // Free up the stream endpoint so that it can be used by some other stream
2372 res = deletedStream->disconnect();
2373 if (res != OK) {
2374 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2375 // fall through since we want to still list the stream as deleted.
2376 }
2377 mDeletedStreams.add(deletedStream);
2378 mDummyStreamId = NO_STREAM;
2379
2380 return res;
2381}
2382
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002383void Camera3Device::setErrorState(const char *fmt, ...) {
2384 Mutex::Autolock l(mLock);
2385 va_list args;
2386 va_start(args, fmt);
2387
2388 setErrorStateLockedV(fmt, args);
2389
2390 va_end(args);
2391}
2392
2393void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2394 Mutex::Autolock l(mLock);
2395 setErrorStateLockedV(fmt, args);
2396}
2397
2398void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2399 va_list args;
2400 va_start(args, fmt);
2401
2402 setErrorStateLockedV(fmt, args);
2403
2404 va_end(args);
2405}
2406
2407void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002408 // Print out all error messages to log
2409 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002410 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002411
2412 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002413 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002414
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002415 mErrorCause = errorCause;
2416
2417 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002418 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002419
2420 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002421 sp<NotificationListener> listener = mListener.promote();
2422 if (listener != NULL) {
2423 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002424 CaptureResultExtras());
2425 }
2426
2427 // Save stack trace. View by dumping it later.
2428 CameraTraces::saveTrace();
2429 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002430}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002431
2432/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002433 * In-flight request management
2434 */
2435
Jianing Weicb0652e2014-03-12 18:29:36 -07002436status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002437 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2438 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002439 ATRACE_CALL();
2440 Mutex::Autolock l(mInFlightLock);
2441
2442 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002443 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2444 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002445 if (res < 0) return res;
2446
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002447 if (mInFlightMap.size() == 1) {
2448 mStatusTracker->markComponentActive(mInFlightStatusId);
2449 }
2450
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002451 return OK;
2452}
2453
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002454void Camera3Device::returnOutputBuffers(
2455 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2456 nsecs_t timestamp) {
2457 for (size_t i = 0; i < numBuffers; i++)
2458 {
2459 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2460 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2461 // Note: stream may be deallocated at this point, if this buffer was
2462 // the last reference to it.
2463 if (res != OK) {
2464 ALOGE("Can't return buffer to its stream: %s (%d)",
2465 strerror(-res), res);
2466 }
2467 }
2468}
2469
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002470void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2471 mInFlightMap.removeItemsAt(idx, 1);
2472
2473 // Indicate idle inFlightMap to the status tracker
2474 if (mInFlightMap.size() == 0) {
2475 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2476 }
2477}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002478
2479void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2480
2481 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2482 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2483
2484 nsecs_t sensorTimestamp = request.sensorTimestamp;
2485 nsecs_t shutterTimestamp = request.shutterTimestamp;
2486
2487 // Check if it's okay to remove the request from InFlightMap:
2488 // In the case of a successful request:
2489 // all input and output buffers, all result metadata, shutter callback
2490 // arrived.
2491 // In the case of a unsuccessful request:
2492 // all input and output buffers arrived.
2493 if (request.numBuffersLeft == 0 &&
2494 (request.requestStatus != OK ||
2495 (request.haveResultMetadata && shutterTimestamp != 0))) {
2496 ATRACE_ASYNC_END("frame capture", frameNumber);
2497
2498 // Sanity check - if sensor timestamp matches shutter timestamp
2499 if (request.requestStatus == OK &&
2500 sensorTimestamp != shutterTimestamp) {
2501 SET_ERR("sensor timestamp (%" PRId64
2502 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2503 sensorTimestamp, frameNumber, shutterTimestamp);
2504 }
2505
2506 // for an unsuccessful request, it may have pending output buffers to
2507 // return.
2508 assert(request.requestStatus != OK ||
2509 request.pendingOutputBuffers.size() == 0);
2510 returnOutputBuffers(request.pendingOutputBuffers.array(),
2511 request.pendingOutputBuffers.size(), 0);
2512
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002513 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002514 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2515 }
2516
2517 // Sanity check - if we have too many in-flight frames, something has
2518 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002519 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002520 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002521 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2522 kInFlightWarnLimitHighSpeed) {
2523 CLOGE("In-flight list too large for high speed configuration: %zu",
2524 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002525 }
2526}
2527
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002528void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2529 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2530 if (result == nullptr) return;
2531
2532 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2533 (int32_t*)&frameNumber, 1) != OK) {
2534 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2535 return;
2536 }
2537
2538 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2539 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2540 return;
2541 }
2542
2543 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2544
2545 // Valid result, insert into queue
2546 List<CaptureResult>::iterator queuedResult =
2547 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2548 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2549 ", burstId = %" PRId32, __FUNCTION__,
2550 queuedResult->mResultExtras.requestId,
2551 queuedResult->mResultExtras.frameNumber,
2552 queuedResult->mResultExtras.burstId);
2553
2554 mResultSignal.signal();
2555}
2556
2557
2558void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2559 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2560 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2561 Mutex::Autolock l(mOutputLock);
2562
2563 CaptureResult captureResult;
2564 captureResult.mResultExtras = resultExtras;
2565 captureResult.mMetadata = partialResult;
2566
2567 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2568}
2569
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002570
2571void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2572 CaptureResultExtras &resultExtras,
2573 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002574 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002575 bool reprocess,
2576 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002577 if (pendingMetadata.isEmpty())
2578 return;
2579
2580 Mutex::Autolock l(mOutputLock);
2581
2582 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002583 if (reprocess) {
2584 if (frameNumber < mNextReprocessResultFrameNumber) {
2585 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002586 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002587 frameNumber, mNextReprocessResultFrameNumber);
2588 return;
2589 }
2590 mNextReprocessResultFrameNumber = frameNumber + 1;
2591 } else {
2592 if (frameNumber < mNextResultFrameNumber) {
2593 SET_ERR("Out-of-order capture result metadata submitted! "
2594 "(got frame number %d, expecting %d)",
2595 frameNumber, mNextResultFrameNumber);
2596 return;
2597 }
2598 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002599 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002600
2601 CaptureResult captureResult;
2602 captureResult.mResultExtras = resultExtras;
2603 captureResult.mMetadata = pendingMetadata;
2604
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002605 // Append any previous partials to form a complete result
2606 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2607 captureResult.mMetadata.append(collectedPartialResult);
2608 }
2609
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002610 // Derive some new keys for backward compaibility
2611 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2612 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2613 int32_t defaultBoost[1] = {100};
2614 captureResult.mMetadata.update(
2615 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2616 defaultBoost, 1);
2617 }
2618
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002619 captureResult.mMetadata.sort();
2620
2621 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002622 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2623 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002624 SET_ERR("No timestamp provided by HAL for frame %d!",
2625 frameNumber);
2626 return;
2627 }
2628
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002629 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2630 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2631
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002632 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002633}
2634
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002635/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002636 * Camera HAL device callback methods
2637 */
2638
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002639void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002640 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002641
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002642 status_t res;
2643
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002644 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002645 if (result->result == NULL && result->num_output_buffers == 0 &&
2646 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002647 SET_ERR("No result data provided by HAL for frame %d",
2648 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002649 return;
2650 }
Zhijun He204e3292014-07-14 17:09:23 -07002651
2652 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2653 // partial_result to 1 when metadata is included in this result.
2654 if (!mUsePartialResult &&
2655 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2656 result->result != NULL &&
2657 result->partial_result != 1) {
2658 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2659 " if partial result is not supported",
2660 frameNumber, result->partial_result);
2661 return;
2662 }
2663
2664 bool isPartialResult = false;
2665 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002666 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002667 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002668
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002669 // Get shutter timestamp and resultExtras from list of in-flight requests,
2670 // where it was added by the shutter notification for this frame. If the
2671 // shutter timestamp isn't received yet, append the output buffers to the
2672 // in-flight request and they will be returned when the shutter timestamp
2673 // arrives. Update the in-flight status and remove the in-flight entry if
2674 // all result data and shutter timestamp have been received.
2675 nsecs_t shutterTimestamp = 0;
2676
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002677 {
2678 Mutex::Autolock l(mInFlightLock);
2679 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2680 if (idx == NAME_NOT_FOUND) {
2681 SET_ERR("Unknown frame number for capture result: %d",
2682 frameNumber);
2683 return;
2684 }
2685 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002686 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2687 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2688 ", partialResultCount = %d",
2689 __FUNCTION__, request.resultExtras.requestId,
2690 request.resultExtras.frameNumber, request.resultExtras.burstId,
2691 result->partial_result);
2692 // Always update the partial count to the latest one if it's not 0
2693 // (buffers only). When framework aggregates adjacent partial results
2694 // into one, the latest partial count will be used.
2695 if (result->partial_result != 0)
2696 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002697
2698 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002699 if (mUsePartialResult && result->result != NULL) {
2700 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2701 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2702 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2703 " the range of [1, %d] when metadata is included in the result",
2704 frameNumber, result->partial_result, mNumPartialResults);
2705 return;
2706 }
2707 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002708 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002709 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002710 }
Zhijun He204e3292014-07-14 17:09:23 -07002711 } else {
2712 camera_metadata_ro_entry_t partialResultEntry;
2713 res = find_camera_metadata_ro_entry(result->result,
2714 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2715 if (res != NAME_NOT_FOUND &&
2716 partialResultEntry.count > 0 &&
2717 partialResultEntry.data.u8[0] ==
2718 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2719 // A partial result. Flag this as such, and collect this
2720 // set of metadata into the in-flight entry.
2721 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002722 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002723 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002724 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002725 ANDROID_QUIRKS_PARTIAL_RESULT);
2726 }
2727 }
2728
2729 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002730 // Send partial capture result
2731 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2732 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002733 }
2734 }
2735
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002736 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002737 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002738
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002739 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002740 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002741 if (request.haveResultMetadata) {
2742 SET_ERR("Called multiple times with metadata for frame %d",
2743 frameNumber);
2744 return;
2745 }
Zhijun He204e3292014-07-14 17:09:23 -07002746 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002747 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002748 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002749 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002750 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002751 request.haveResultMetadata = true;
2752 }
2753
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002754 uint32_t numBuffersReturned = result->num_output_buffers;
2755 if (result->input_buffer != NULL) {
2756 if (hasInputBufferInRequest) {
2757 numBuffersReturned += 1;
2758 } else {
2759 ALOGW("%s: Input buffer should be NULL if there is no input"
2760 " buffer sent in the request",
2761 __FUNCTION__);
2762 }
2763 }
2764 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002765 if (request.numBuffersLeft < 0) {
2766 SET_ERR("Too many buffers returned for frame %d",
2767 frameNumber);
2768 return;
2769 }
2770
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771 camera_metadata_ro_entry_t entry;
2772 res = find_camera_metadata_ro_entry(result->result,
2773 ANDROID_SENSOR_TIMESTAMP, &entry);
2774 if (res == OK && entry.count == 1) {
2775 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002776 }
2777
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002778 // If shutter event isn't received yet, append the output buffers to
2779 // the in-flight request. Otherwise, return the output buffers to
2780 // streams.
2781 if (shutterTimestamp == 0) {
2782 request.pendingOutputBuffers.appendArray(result->output_buffers,
2783 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002784 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002785 returnOutputBuffers(result->output_buffers,
2786 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002787 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002788
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002789 if (result->result != NULL && !isPartialResult) {
2790 if (shutterTimestamp == 0) {
2791 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002792 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002793 } else {
2794 CameraMetadata metadata;
2795 metadata = result->result;
2796 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002797 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2798 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002799 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002800 }
2801
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002802 removeInFlightRequestIfReadyLocked(idx);
2803 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002804
Zhijun Hef0d962a2014-06-30 10:24:11 -07002805 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002806 if (hasInputBufferInRequest) {
2807 Camera3Stream *stream =
2808 Camera3Stream::cast(result->input_buffer->stream);
2809 res = stream->returnInputBuffer(*(result->input_buffer));
2810 // Note: stream may be deallocated at this point, if this buffer was the
2811 // last reference to it.
2812 if (res != OK) {
2813 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2814 " its stream:%s (%d)", __FUNCTION__,
2815 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002816 }
2817 } else {
2818 ALOGW("%s: Input buffer should be NULL if there is no input"
2819 " buffer sent in the request, skipping input buffer return.",
2820 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002821 }
2822 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002823}
2824
2825void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002826 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002827 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002828 {
2829 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002830 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002831 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002832
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002833 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002834 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002835 return;
2836 }
2837
2838 switch (msg->type) {
2839 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002841 break;
2842 }
2843 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002844 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002845 break;
2846 }
2847 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002848 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002849 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002850 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002851}
2852
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002853void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002854 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002855
2856 // Map camera HAL error codes to ICameraDeviceCallback error codes
2857 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002858 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002860 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002861 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002862 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002863 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002864 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002865 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002866 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002867 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002868 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869 };
2870
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002871 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002872 ((msg.error_code >= 0) &&
2873 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2874 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002875 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002876
2877 int streamId = 0;
2878 if (msg.error_stream != NULL) {
2879 Camera3Stream *stream =
2880 Camera3Stream::cast(msg.error_stream);
2881 streamId = stream->getId();
2882 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002883 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2884 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 streamId, msg.error_code);
2886
2887 CaptureResultExtras resultExtras;
2888 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002889 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890 // SET_ERR calls notifyError
2891 SET_ERR("Camera HAL reported serious device error");
2892 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002893 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2894 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2895 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002896 {
2897 Mutex::Autolock l(mInFlightLock);
2898 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2899 if (idx >= 0) {
2900 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2901 r.requestStatus = msg.error_code;
2902 resultExtras = r.resultExtras;
2903 } else {
2904 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002905 ALOGE("Camera %s: %s: cannot find in-flight request on "
2906 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002907 resultExtras.frameNumber);
2908 }
2909 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002910 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002911 if (listener != NULL) {
2912 listener->notifyError(errorCode, resultExtras);
2913 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002914 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002915 }
2916 break;
2917 default:
2918 // SET_ERR calls notifyError
2919 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2920 break;
2921 }
2922}
2923
2924void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002925 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002926 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002927
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002928 // Set timestamp for the request in the in-flight tracking
2929 // and get the request ID to send upstream
2930 {
2931 Mutex::Autolock l(mInFlightLock);
2932 idx = mInFlightMap.indexOfKey(msg.frame_number);
2933 if (idx >= 0) {
2934 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002935
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002936 // Verify ordering of shutter notifications
2937 {
2938 Mutex::Autolock l(mOutputLock);
2939 // TODO: need to track errors for tighter bounds on expected frame number.
2940 if (r.hasInputBuffer) {
2941 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2942 SET_ERR("Shutter notification out-of-order. Expected "
2943 "notification for frame %d, got frame %d",
2944 mNextReprocessShutterFrameNumber, msg.frame_number);
2945 return;
2946 }
2947 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2948 } else {
2949 if (msg.frame_number < mNextShutterFrameNumber) {
2950 SET_ERR("Shutter notification out-of-order. Expected "
2951 "notification for frame %d, got frame %d",
2952 mNextShutterFrameNumber, msg.frame_number);
2953 return;
2954 }
2955 mNextShutterFrameNumber = msg.frame_number + 1;
2956 }
2957 }
2958
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002959 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
2960 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002961 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
2962 // Call listener, if any
2963 if (listener != NULL) {
2964 listener->notifyShutter(r.resultExtras, msg.timestamp);
2965 }
2966
2967 r.shutterTimestamp = msg.timestamp;
2968
2969 // send pending result and buffers
2970 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002971 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002972 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002973 returnOutputBuffers(r.pendingOutputBuffers.array(),
2974 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2975 r.pendingOutputBuffers.clear();
2976
2977 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002978 }
2979 }
2980 if (idx < 0) {
2981 SET_ERR("Shutter notification for non-existent frame number %d",
2982 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002983 }
2984}
2985
2986
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002987CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002988 ALOGV("%s", __FUNCTION__);
2989
Igor Murashkin1e479c02013-09-06 16:55:14 -07002990 CameraMetadata retVal;
2991
2992 if (mRequestThread != NULL) {
2993 retVal = mRequestThread->getLatestRequest();
2994 }
2995
Igor Murashkin1e479c02013-09-06 16:55:14 -07002996 return retVal;
2997}
2998
Jianing Weicb0652e2014-03-12 18:29:36 -07002999
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003000void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3001 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3002 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3003}
3004
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003005/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 * HalInterface inner class methods
3007 */
3008
3009Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3010 mHal3Device(device) {}
3011
3012Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3013 mHal3Device(nullptr),
3014 mHidlSession(session) {}
3015
3016Camera3Device::HalInterface::HalInterface() :
3017 mHal3Device(nullptr) {}
3018
3019Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3020 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3021
3022bool Camera3Device::HalInterface::valid() {
3023 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3024}
3025
3026void Camera3Device::HalInterface::clear() {
3027 mHal3Device = nullptr;
3028 mHidlSession.clear();
3029}
3030
3031status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3032 camera3_request_template_t templateId,
3033 /*out*/ camera_metadata_t **requestTemplate) {
3034 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3035 if (!valid()) return INVALID_OPERATION;
3036 status_t res = OK;
3037
3038 if (mHal3Device != nullptr) {
3039 const camera_metadata *r;
3040 r = mHal3Device->ops->construct_default_request_settings(
3041 mHal3Device, templateId);
3042 if (r == nullptr) return BAD_VALUE;
3043 *requestTemplate = clone_camera_metadata(r);
3044 if (requestTemplate == nullptr) {
3045 ALOGE("%s: Unable to clone camera metadata received from HAL",
3046 __FUNCTION__);
3047 return INVALID_OPERATION;
3048 }
3049 } else {
3050 common::V1_0::Status status;
3051 RequestTemplate id;
3052 switch (templateId) {
3053 case CAMERA3_TEMPLATE_PREVIEW:
3054 id = RequestTemplate::PREVIEW;
3055 break;
3056 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3057 id = RequestTemplate::STILL_CAPTURE;
3058 break;
3059 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3060 id = RequestTemplate::VIDEO_RECORD;
3061 break;
3062 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3063 id = RequestTemplate::VIDEO_SNAPSHOT;
3064 break;
3065 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3066 id = RequestTemplate::ZERO_SHUTTER_LAG;
3067 break;
3068 case CAMERA3_TEMPLATE_MANUAL:
3069 id = RequestTemplate::MANUAL;
3070 break;
3071 default:
3072 // Unknown template ID
3073 return BAD_VALUE;
3074 }
3075 mHidlSession->constructDefaultRequestSettings(id,
3076 [&status, &requestTemplate]
3077 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3078 status = s;
3079 if (status == common::V1_0::Status::OK) {
3080 const camera_metadata *r =
3081 reinterpret_cast<const camera_metadata_t*>(request.data());
3082 size_t expectedSize = request.size();
3083 int ret = validate_camera_metadata_structure(r, &expectedSize);
3084 if (ret == OK) {
3085 *requestTemplate = clone_camera_metadata(r);
3086 if (*requestTemplate == nullptr) {
3087 ALOGE("%s: Unable to clone camera metadata received from HAL",
3088 __FUNCTION__);
3089 status = common::V1_0::Status::INTERNAL_ERROR;
3090 }
3091 } else {
3092 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3093 status = common::V1_0::Status::INTERNAL_ERROR;
3094 }
3095 }
3096 });
3097 res = CameraProviderManager::mapToStatusT(status);
3098 }
3099 return res;
3100}
3101
3102status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3103 ATRACE_NAME("CameraHal::configureStreams");
3104 if (!valid()) return INVALID_OPERATION;
3105 status_t res = OK;
3106
3107 if (mHal3Device != nullptr) {
3108 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3109 } else {
3110 // Convert stream config to HIDL
3111
3112 StreamConfiguration requestedConfiguration;
3113 requestedConfiguration.streams.resize(config->num_streams);
3114 for (size_t i = 0; i < config->num_streams; i++) {
3115 Stream &dst = requestedConfiguration.streams[i];
3116 camera3_stream_t *src = config->streams[i];
3117
3118 int streamId = Camera3Stream::cast(src)->getId();
3119 StreamType streamType;
3120 switch (src->stream_type) {
3121 case CAMERA3_STREAM_OUTPUT:
3122 streamType = StreamType::OUTPUT;
3123 break;
3124 case CAMERA3_STREAM_INPUT:
3125 streamType = StreamType::INPUT;
3126 break;
3127 default:
3128 ALOGE("%s: Stream %d: Unsupported stream type %d",
3129 __FUNCTION__, streamId, config->streams[i]->stream_type);
3130 return BAD_VALUE;
3131 }
3132 dst.id = streamId;
3133 dst.streamType = streamType;
3134 dst.width = src->width;
3135 dst.height = src->height;
3136 dst.format = mapToPixelFormat(src->format);
3137 dst.usage = mapToConsumerUsage(src->usage);
3138 dst.dataSpace = mapToHidlDataspace(src->data_space);
3139 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3140 }
3141 requestedConfiguration.operationMode = mapToStreamConfigurationMode(
3142 (camera3_stream_configuration_mode_t) config->operation_mode);
3143
3144 // Invoke configureStreams
3145
3146 HalStreamConfiguration finalConfiguration;
3147 common::V1_0::Status status;
3148 mHidlSession->configureStreams(requestedConfiguration,
3149 [&status, &finalConfiguration]
3150 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3151 finalConfiguration = halConfiguration;
3152 status = s;
3153 });
3154 if (status != common::V1_0::Status::OK ) {
3155 return CameraProviderManager::mapToStatusT(status);
3156 }
3157
3158 // And convert output stream configuration from HIDL
3159
3160 for (size_t i = 0; i < config->num_streams; i++) {
3161 camera3_stream_t *dst = config->streams[i];
3162 int streamId = Camera3Stream::cast(dst)->getId();
3163
3164 // Start scan at i, with the assumption that the stream order matches
3165 size_t realIdx = i;
3166 bool found = false;
3167 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3168 if (finalConfiguration.streams[realIdx].id == streamId) {
3169 found = true;
3170 break;
3171 }
3172 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3173 }
3174 if (!found) {
3175 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3176 __FUNCTION__, streamId);
3177 return INVALID_OPERATION;
3178 }
3179 HalStream &src = finalConfiguration.streams[realIdx];
3180
3181 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3182 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3183 if (dst->format != overrideFormat) {
3184 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3185 streamId, dst->format);
3186 }
3187 } else {
3188 // Override allowed with IMPLEMENTATION_DEFINED
3189 dst->format = overrideFormat;
3190 }
3191
3192 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3193 if (src.producerUsage != 0) {
3194 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3195 __FUNCTION__, streamId);
3196 return INVALID_OPERATION;
3197 }
3198 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3199 } else {
3200 // OUTPUT
3201 if (src.consumerUsage != 0) {
3202 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3203 __FUNCTION__, streamId);
3204 return INVALID_OPERATION;
3205 }
3206 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3207 }
3208 dst->max_buffers = src.maxBuffers;
3209 }
3210 }
3211 return res;
3212}
3213
3214status_t Camera3Device::HalInterface::processCaptureRequest(
3215 camera3_capture_request_t *request) {
3216 ATRACE_NAME("CameraHal::processCaptureRequest");
3217 (void) request;
3218 if (!valid()) return INVALID_OPERATION;
3219 status_t res = OK;
3220
3221 if (mHal3Device != nullptr) {
3222 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3223 } else {
3224 device::V3_2::CaptureRequest captureRequest;
3225 captureRequest.frameNumber = request->frame_number;
3226 std::vector<native_handle_t*> handlesCreated;
3227 // A null request settings maps to a size-0 CameraMetadata
3228 if (request->settings != nullptr) {
3229 captureRequest.settings.setToExternal(
3230 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3231 get_camera_metadata_size(request->settings));
3232 }
3233 std::lock_guard<std::mutex> lock(mInflightLock);
3234 if (request->input_buffer != nullptr) {
3235 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3236 captureRequest.inputBuffer.streamId = streamId;
3237 captureRequest.inputBuffer.buffer = *(request->input_buffer->buffer);
3238 captureRequest.inputBuffer.status = BufferStatus::OK;
3239 native_handle_t *acquireFence = nullptr;
3240 if (request->input_buffer->acquire_fence != -1) {
3241 acquireFence = native_handle_create(1,0);
3242 acquireFence->data[0] = request->input_buffer->acquire_fence;
3243 handlesCreated.push_back(acquireFence);
3244 }
3245 captureRequest.inputBuffer.acquireFence = acquireFence;
3246 captureRequest.inputBuffer.releaseFence = nullptr;
3247
3248 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3249 request->input_buffer->buffer);
3250 }
3251 captureRequest.outputBuffers.resize(request->num_output_buffers);
3252 for (size_t i = 0; i < request->num_output_buffers; i++) {
3253 const camera3_stream_buffer_t *src = request->output_buffers + i;
3254 StreamBuffer &dst = captureRequest.outputBuffers[i];
3255 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3256 dst.streamId = streamId;
3257 dst.buffer = *(src->buffer);
3258 dst.status = BufferStatus::OK;
3259 native_handle_t *acquireFence = nullptr;
3260 if (src->acquire_fence != -1) {
3261 acquireFence = native_handle_create(1,0);
3262 acquireFence->data[0] = src->acquire_fence;
3263 handlesCreated.push_back(acquireFence);
3264 }
3265 dst.acquireFence = acquireFence;
3266 dst.releaseFence = nullptr;
3267
3268 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3269 src->buffer);
3270 }
3271
3272 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3273
3274 for (auto& handle : handlesCreated) {
3275 native_handle_delete(handle);
3276 }
3277
3278 res = CameraProviderManager::mapToStatusT(status);
3279 }
3280 return res;
3281}
3282
3283status_t Camera3Device::HalInterface::flush() {
3284 ATRACE_NAME("CameraHal::flush");
3285 if (!valid()) return INVALID_OPERATION;
3286 status_t res = OK;
3287
3288 if (mHal3Device != nullptr) {
3289 res = mHal3Device->ops->flush(mHal3Device);
3290 } else {
3291 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3292 }
3293 return res;
3294}
3295
3296status_t Camera3Device::HalInterface::dump(int fd) {
3297 ATRACE_NAME("CameraHal::dump");
3298 if (!valid()) return INVALID_OPERATION;
3299 status_t res = OK;
3300
3301 if (mHal3Device != nullptr) {
3302 mHal3Device->ops->dump(mHal3Device, fd);
3303 } else {
3304 // Handled by CameraProviderManager::dump
3305 }
3306 return res;
3307}
3308
3309status_t Camera3Device::HalInterface::close() {
3310 ATRACE_NAME("CameraHal::close()");
3311 if (!valid()) return INVALID_OPERATION;
3312 status_t res = OK;
3313
3314 if (mHal3Device != nullptr) {
3315 mHal3Device->common.close(&mHal3Device->common);
3316 } else {
3317 mHidlSession->close();
3318 }
3319 return res;
3320}
3321
3322status_t Camera3Device::HalInterface::pushInflightBufferLocked(
3323 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
3324 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3325 mInflightBufferMap[key] = buffer;
3326 return OK;
3327}
3328
3329status_t Camera3Device::HalInterface::popInflightBuffer(
3330 int32_t frameNumber, int32_t streamId, /*out*/ buffer_handle_t **buffer) {
3331 std::lock_guard<std::mutex> lock(mInflightLock);
3332
3333 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3334 auto it = mInflightBufferMap.find(key);
3335 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
3336 *buffer = it->second;
3337 mInflightBufferMap.erase(it);
3338 return OK;
3339}
3340
3341/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003342 * RequestThread inner class methods
3343 */
3344
3345Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003346 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003347 HalInterface* interface,
3348 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003349 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003350 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003351 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003352 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003353 mInterface(interface),
3354 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003355 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003356 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003357 mReconfigured(false),
3358 mDoPause(false),
3359 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003360 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003361 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003362 mCurrentAfTriggerId(0),
3363 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003364 mRepeatingLastFrameNumber(
3365 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003366 mAeLockAvailable(aeLockAvailable),
3367 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003368 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003369}
3370
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003371Camera3Device::RequestThread::~RequestThread() {}
3372
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003373void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003374 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003375 Mutex::Autolock l(mRequestLock);
3376 mListener = listener;
3377}
3378
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003379void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003380 Mutex::Autolock l(mRequestLock);
3381 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003382 // Prepare video stream for high speed recording.
3383 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003384}
3385
Jianing Wei90e59c92014-03-12 18:29:36 -07003386status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003387 List<sp<CaptureRequest> > &requests,
3388 /*out*/
3389 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003390 Mutex::Autolock l(mRequestLock);
3391 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3392 ++it) {
3393 mRequestQueue.push_back(*it);
3394 }
3395
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003396 if (lastFrameNumber != NULL) {
3397 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3398 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3399 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3400 *lastFrameNumber);
3401 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003402
Jianing Wei90e59c92014-03-12 18:29:36 -07003403 unpauseForNewRequests();
3404
3405 return OK;
3406}
3407
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003408
3409status_t Camera3Device::RequestThread::queueTrigger(
3410 RequestTrigger trigger[],
3411 size_t count) {
3412
3413 Mutex::Autolock l(mTriggerMutex);
3414 status_t ret;
3415
3416 for (size_t i = 0; i < count; ++i) {
3417 ret = queueTriggerLocked(trigger[i]);
3418
3419 if (ret != OK) {
3420 return ret;
3421 }
3422 }
3423
3424 return OK;
3425}
3426
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003427const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3428 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003429 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 if (d != nullptr) return d->mId;
3431 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003432}
3433
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003434status_t Camera3Device::RequestThread::queueTriggerLocked(
3435 RequestTrigger trigger) {
3436
3437 uint32_t tag = trigger.metadataTag;
3438 ssize_t index = mTriggerMap.indexOfKey(tag);
3439
3440 switch (trigger.getTagType()) {
3441 case TYPE_BYTE:
3442 // fall-through
3443 case TYPE_INT32:
3444 break;
3445 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003446 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3447 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003448 return INVALID_OPERATION;
3449 }
3450
3451 /**
3452 * Collect only the latest trigger, since we only have 1 field
3453 * in the request settings per trigger tag, and can't send more than 1
3454 * trigger per request.
3455 */
3456 if (index != NAME_NOT_FOUND) {
3457 mTriggerMap.editValueAt(index) = trigger;
3458 } else {
3459 mTriggerMap.add(tag, trigger);
3460 }
3461
3462 return OK;
3463}
3464
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003465status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003466 const RequestList &requests,
3467 /*out*/
3468 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003469 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003470 if (lastFrameNumber != NULL) {
3471 *lastFrameNumber = mRepeatingLastFrameNumber;
3472 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003473 mRepeatingRequests.clear();
3474 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3475 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003476
3477 unpauseForNewRequests();
3478
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003479 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003480 return OK;
3481}
3482
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003483bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003484 if (mRepeatingRequests.empty()) {
3485 return false;
3486 }
3487 int32_t requestId = requestIn->mResultExtras.requestId;
3488 const RequestList &repeatRequests = mRepeatingRequests;
3489 // All repeating requests are guaranteed to have same id so only check first quest
3490 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3491 return (firstRequest->mResultExtras.requestId == requestId);
3492}
3493
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003494status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003495 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003496 return clearRepeatingRequestsLocked(lastFrameNumber);
3497
3498}
3499
3500status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003501 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003502 if (lastFrameNumber != NULL) {
3503 *lastFrameNumber = mRepeatingLastFrameNumber;
3504 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003505 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003506 return OK;
3507}
3508
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003509status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003510 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003511 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003512 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003513
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003514 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003515
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003516 // Send errors for all requests pending in the request queue, including
3517 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003518 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003519 if (listener != NULL) {
3520 for (RequestList::iterator it = mRequestQueue.begin();
3521 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003522 // Abort the input buffers for reprocess requests.
3523 if ((*it)->mInputStream != NULL) {
3524 camera3_stream_buffer_t inputBuffer;
3525 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3526 if (res != OK) {
3527 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3528 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3529 } else {
3530 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3531 if (res != OK) {
3532 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3533 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3534 }
3535 }
3536 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003537 // Set the frame number this request would have had, if it
3538 // had been submitted; this frame number will not be reused.
3539 // The requestId and burstId fields were set when the request was
3540 // submitted originally (in convertMetadataListToRequestListLocked)
3541 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003542 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003543 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003544 }
3545 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003546 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003547
3548 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003549 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003550 if (lastFrameNumber != NULL) {
3551 *lastFrameNumber = mRepeatingLastFrameNumber;
3552 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003553 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003554 return OK;
3555}
3556
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003557status_t Camera3Device::RequestThread::flush() {
3558 ATRACE_CALL();
3559 Mutex::Autolock l(mFlushLock);
3560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3562 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003563 }
3564
3565 return -ENOTSUP;
3566}
3567
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003568void Camera3Device::RequestThread::setPaused(bool paused) {
3569 Mutex::Autolock l(mPauseLock);
3570 mDoPause = paused;
3571 mDoPauseSignal.signal();
3572}
3573
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003574status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3575 int32_t requestId, nsecs_t timeout) {
3576 Mutex::Autolock l(mLatestRequestMutex);
3577 status_t res;
3578 while (mLatestRequestId != requestId) {
3579 nsecs_t startTime = systemTime();
3580
3581 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3582 if (res != OK) return res;
3583
3584 timeout -= (systemTime() - startTime);
3585 }
3586
3587 return OK;
3588}
3589
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003590void Camera3Device::RequestThread::requestExit() {
3591 // Call parent to set up shutdown
3592 Thread::requestExit();
3593 // The exit from any possible waits
3594 mDoPauseSignal.signal();
3595 mRequestSignal.signal();
3596}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003597
Chien-Yu Chend196d612015-06-22 19:49:01 -07003598
3599/**
3600 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3601 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3602 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3603 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3604 * request.
3605 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003606void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003607 request->mAeTriggerCancelOverride.applyAeLock = false;
3608 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3609
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003610 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003611 return;
3612 }
3613
3614 camera_metadata_entry_t aePrecaptureTrigger =
3615 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3616 if (aePrecaptureTrigger.count > 0 &&
3617 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3618 // Always override CANCEL to IDLE
3619 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3620 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3621 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3622 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3623 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3624
3625 if (mAeLockAvailable == true) {
3626 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3627 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3628 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3629 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3630 request->mAeTriggerCancelOverride.applyAeLock = true;
3631 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3632 }
3633 }
3634 }
3635}
3636
3637/**
3638 * Override result metadata for cancelling AE precapture trigger applied in
3639 * handleAePrecaptureCancelRequest().
3640 */
3641void Camera3Device::overrideResultForPrecaptureCancel(
3642 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3643 if (aeTriggerCancelOverride.applyAeLock) {
3644 // Only devices <= v3.2 should have this override
3645 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3646 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3647 }
3648
3649 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3650 // Only devices <= v3.2 should have this override
3651 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3652 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3653 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3654 }
3655}
3656
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003657void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003658 bool surfaceAbandoned = false;
3659 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003660 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003661 {
3662 Mutex::Autolock l(mRequestLock);
3663 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3664 // repeating requests.
3665 for (const auto& request : mRepeatingRequests) {
3666 for (const auto& s : request->mOutputStreams) {
3667 if (s->isAbandoned()) {
3668 surfaceAbandoned = true;
3669 clearRepeatingRequestsLocked(&lastFrameNumber);
3670 break;
3671 }
3672 }
3673 if (surfaceAbandoned) {
3674 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003675 }
3676 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003677 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003678 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003679
3680 if (listener != NULL && surfaceAbandoned) {
3681 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003682 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003683}
3684
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003685bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003686 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003687 status_t res;
3688
3689 // Handle paused state.
3690 if (waitIfPaused()) {
3691 return true;
3692 }
3693
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003694 // Wait for the next batch of requests.
3695 waitForNextRequestBatch();
3696 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003697 return true;
3698 }
3699
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003700 // Get the latest request ID, if any
3701 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003702 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003703 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003704 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003705 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003706 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003707 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3708 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003709 }
3710
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003712 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003713 if (res == TIMED_OUT) {
3714 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003715 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003716 // Check if any stream is abandoned.
3717 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003718 return true;
3719 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003720 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003721 return false;
3722 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003723
Zhijun Hecc27e112013-10-03 16:12:43 -07003724 // Inform waitUntilRequestProcessed thread of a new request ID
3725 {
3726 Mutex::Autolock al(mLatestRequestMutex);
3727
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003728 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003729 mLatestRequestSignal.signal();
3730 }
3731
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003732 // Submit a batch of requests to HAL.
3733 // Use flush lock only when submitting multilple requests in a batch.
3734 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3735 // which may take a long time to finish so synchronizing flush() and
3736 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3737 // For now, only synchronize for high speed recording and we should figure something out for
3738 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003739 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003740
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003741 if (useFlushLock) {
3742 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003743 }
3744
Zhijun Hef0645c12016-08-02 00:58:11 -07003745 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003746 mNextRequests.size());
3747 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003748 // Submit request and block until ready for next one
3749 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003750 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003751
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003752 if (res != OK) {
3753 // Should only get a failure here for malformed requests or device-level
3754 // errors, so consider all errors fatal. Bad metadata failures should
3755 // come through notify.
3756 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3757 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3758 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003759 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003760 if (useFlushLock) {
3761 mFlushLock.unlock();
3762 }
3763 return false;
3764 }
3765
3766 // Mark that the request has be submitted successfully.
3767 nextRequest.submitted = true;
3768
3769 // Update the latest request sent to HAL
3770 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3771 Mutex::Autolock al(mLatestRequestMutex);
3772
3773 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3774 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003775
3776 sp<Camera3Device> parent = mParent.promote();
3777 if (parent != NULL) {
3778 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3779 0, mLatestRequest);
3780 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003781 }
3782
3783 if (nextRequest.halRequest.settings != NULL) {
3784 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3785 }
3786
3787 // Remove any previously queued triggers (after unlock)
3788 res = removeTriggers(mPrevRequest);
3789 if (res != OK) {
3790 SET_ERR("RequestThread: Unable to remove triggers "
3791 "(capture request %d, HAL device: %s (%d)",
3792 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003793 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003794 if (useFlushLock) {
3795 mFlushLock.unlock();
3796 }
3797 return false;
3798 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003799 }
3800
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003801 if (useFlushLock) {
3802 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003803 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003804
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003805 // Unset as current request
3806 {
3807 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003808 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003809 }
3810
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003811 return true;
3812}
3813
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003814status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003815 ATRACE_CALL();
3816
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003817 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003818 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3819 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3820 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3821
3822 // Prepare a request to HAL
3823 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3824
3825 // Insert any queued triggers (before metadata is locked)
3826 status_t res = insertTriggers(captureRequest);
3827
3828 if (res < 0) {
3829 SET_ERR("RequestThread: Unable to insert triggers "
3830 "(capture request %d, HAL device: %s (%d)",
3831 halRequest->frame_number, strerror(-res), res);
3832 return INVALID_OPERATION;
3833 }
3834 int triggerCount = res;
3835 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3836 mPrevTriggers = triggerCount;
3837
3838 // If the request is the same as last, or we had triggers last time
3839 if (mPrevRequest != captureRequest || triggersMixedIn) {
3840 /**
3841 * HAL workaround:
3842 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3843 */
3844 res = addDummyTriggerIds(captureRequest);
3845 if (res != OK) {
3846 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3847 "(capture request %d, HAL device: %s (%d)",
3848 halRequest->frame_number, strerror(-res), res);
3849 return INVALID_OPERATION;
3850 }
3851
3852 /**
3853 * The request should be presorted so accesses in HAL
3854 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3855 */
3856 captureRequest->mSettings.sort();
3857 halRequest->settings = captureRequest->mSettings.getAndLock();
3858 mPrevRequest = captureRequest;
3859 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3860
3861 IF_ALOGV() {
3862 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3863 find_camera_metadata_ro_entry(
3864 halRequest->settings,
3865 ANDROID_CONTROL_AF_TRIGGER,
3866 &e
3867 );
3868 if (e.count > 0) {
3869 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3870 __FUNCTION__,
3871 halRequest->frame_number,
3872 e.data.u8[0]);
3873 }
3874 }
3875 } else {
3876 // leave request.settings NULL to indicate 'reuse latest given'
3877 ALOGVV("%s: Request settings are REUSED",
3878 __FUNCTION__);
3879 }
3880
3881 uint32_t totalNumBuffers = 0;
3882
3883 // Fill in buffers
3884 if (captureRequest->mInputStream != NULL) {
3885 halRequest->input_buffer = &captureRequest->mInputBuffer;
3886 totalNumBuffers += 1;
3887 } else {
3888 halRequest->input_buffer = NULL;
3889 }
3890
3891 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3892 captureRequest->mOutputStreams.size());
3893 halRequest->output_buffers = outputBuffers->array();
3894 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003895 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
3896
3897 // Prepare video buffers for high speed recording on the first video request.
3898 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3899 // Only try to prepare video stream on the first video request.
3900 mPrepareVideoStream = false;
3901
3902 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3903 while (res == NOT_ENOUGH_DATA) {
3904 res = outputStream->prepareNextBuffer();
3905 }
3906 if (res != OK) {
3907 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3908 __FUNCTION__, strerror(-res), res);
3909 outputStream->cancelPrepare();
3910 }
3911 }
3912
3913 res = outputStream->getBuffer(&outputBuffers->editItemAt(i));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003914 if (res != OK) {
3915 // Can't get output buffer from gralloc queue - this could be due to
3916 // abandoned queue or other consumer misbehavior, so not a fatal
3917 // error
3918 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3919 " %s (%d)", strerror(-res), res);
3920
3921 return TIMED_OUT;
3922 }
3923 halRequest->num_output_buffers++;
3924 }
3925 totalNumBuffers += halRequest->num_output_buffers;
3926
3927 // Log request in the in-flight queue
3928 sp<Camera3Device> parent = mParent.promote();
3929 if (parent == NULL) {
3930 // Should not happen, and nowhere to send errors to, so just log it
3931 CLOGE("RequestThread: Parent is gone");
3932 return INVALID_OPERATION;
3933 }
3934 res = parent->registerInFlight(halRequest->frame_number,
3935 totalNumBuffers, captureRequest->mResultExtras,
3936 /*hasInput*/halRequest->input_buffer != NULL,
3937 captureRequest->mAeTriggerCancelOverride);
3938 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3939 ", burstId = %" PRId32 ".",
3940 __FUNCTION__,
3941 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3942 captureRequest->mResultExtras.burstId);
3943 if (res != OK) {
3944 SET_ERR("RequestThread: Unable to register new in-flight request:"
3945 " %s (%d)", strerror(-res), res);
3946 return INVALID_OPERATION;
3947 }
3948 }
3949
3950 return OK;
3951}
3952
Igor Murashkin1e479c02013-09-06 16:55:14 -07003953CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
3954 Mutex::Autolock al(mLatestRequestMutex);
3955
3956 ALOGV("RequestThread::%s", __FUNCTION__);
3957
3958 return mLatestRequest;
3959}
3960
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003961bool Camera3Device::RequestThread::isStreamPending(
3962 sp<Camera3StreamInterface>& stream) {
3963 Mutex::Autolock l(mRequestLock);
3964
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003965 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003966 if (!nextRequest.submitted) {
3967 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3968 if (stream == s) return true;
3969 }
3970 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003971 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003972 }
3973
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003974 for (const auto& request : mRequestQueue) {
3975 for (const auto& s : request->mOutputStreams) {
3976 if (stream == s) return true;
3977 }
3978 if (stream == request->mInputStream) return true;
3979 }
3980
3981 for (const auto& request : mRepeatingRequests) {
3982 for (const auto& s : request->mOutputStreams) {
3983 if (stream == s) return true;
3984 }
3985 if (stream == request->mInputStream) return true;
3986 }
3987
3988 return false;
3989}
Jianing Weicb0652e2014-03-12 18:29:36 -07003990
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003991void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
3992 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003993 return;
3994 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003995
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003996 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003997 // Skip the ones that have been submitted successfully.
3998 if (nextRequest.submitted) {
3999 continue;
4000 }
4001
4002 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4003 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4004 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4005
4006 if (halRequest->settings != NULL) {
4007 captureRequest->mSettings.unlock(halRequest->settings);
4008 }
4009
4010 if (captureRequest->mInputStream != NULL) {
4011 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4012 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4013 }
4014
4015 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4016 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4017 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4018 }
4019
4020 if (sendRequestError) {
4021 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004022 sp<NotificationListener> listener = mListener.promote();
4023 if (listener != NULL) {
4024 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004025 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004026 captureRequest->mResultExtras);
4027 }
4028 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004029
4030 // Remove yet-to-be submitted inflight request from inflightMap
4031 {
4032 sp<Camera3Device> parent = mParent.promote();
4033 if (parent != NULL) {
4034 Mutex::Autolock l(parent->mInFlightLock);
4035 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4036 if (idx >= 0) {
4037 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4038 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4039 parent->removeInFlightMapEntryLocked(idx);
4040 }
4041 }
4042 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004043 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004044
4045 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004046 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004047}
4048
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004049void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004050 // Optimized a bit for the simple steady-state case (single repeating
4051 // request), to avoid putting that request in the queue temporarily.
4052 Mutex::Autolock l(mRequestLock);
4053
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004054 assert(mNextRequests.empty());
4055
4056 NextRequest nextRequest;
4057 nextRequest.captureRequest = waitForNextRequestLocked();
4058 if (nextRequest.captureRequest == nullptr) {
4059 return;
4060 }
4061
4062 nextRequest.halRequest = camera3_capture_request_t();
4063 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004064 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004065
4066 // Wait for additional requests
4067 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4068
4069 for (size_t i = 1; i < batchSize; i++) {
4070 NextRequest additionalRequest;
4071 additionalRequest.captureRequest = waitForNextRequestLocked();
4072 if (additionalRequest.captureRequest == nullptr) {
4073 break;
4074 }
4075
4076 additionalRequest.halRequest = camera3_capture_request_t();
4077 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004078 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004079 }
4080
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004081 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004082 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004083 mNextRequests.size(), batchSize);
4084 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004085 }
4086
4087 return;
4088}
4089
4090sp<Camera3Device::CaptureRequest>
4091 Camera3Device::RequestThread::waitForNextRequestLocked() {
4092 status_t res;
4093 sp<CaptureRequest> nextRequest;
4094
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004095 while (mRequestQueue.empty()) {
4096 if (!mRepeatingRequests.empty()) {
4097 // Always atomically enqueue all requests in a repeating request
4098 // list. Guarantees a complete in-sequence set of captures to
4099 // application.
4100 const RequestList &requests = mRepeatingRequests;
4101 RequestList::const_iterator firstRequest =
4102 requests.begin();
4103 nextRequest = *firstRequest;
4104 mRequestQueue.insert(mRequestQueue.end(),
4105 ++firstRequest,
4106 requests.end());
4107 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004108
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004109 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004110
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004111 break;
4112 }
4113
4114 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4115
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004116 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4117 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004118 Mutex::Autolock pl(mPauseLock);
4119 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004120 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004121 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004122 // Let the tracker know
4123 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4124 if (statusTracker != 0) {
4125 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4126 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004127 }
4128 // Stop waiting for now and let thread management happen
4129 return NULL;
4130 }
4131 }
4132
4133 if (nextRequest == NULL) {
4134 // Don't have a repeating request already in hand, so queue
4135 // must have an entry now.
4136 RequestList::iterator firstRequest =
4137 mRequestQueue.begin();
4138 nextRequest = *firstRequest;
4139 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004140 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4141 sp<NotificationListener> listener = mListener.promote();
4142 if (listener != NULL) {
4143 listener->notifyRequestQueueEmpty();
4144 }
4145 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004146 }
4147
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004148 // In case we've been unpaused by setPaused clearing mDoPause, need to
4149 // update internal pause state (capture/setRepeatingRequest unpause
4150 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004151 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004152 if (mPaused) {
4153 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4154 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4155 if (statusTracker != 0) {
4156 statusTracker->markComponentActive(mStatusId);
4157 }
4158 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004159 mPaused = false;
4160
4161 // Check if we've reconfigured since last time, and reset the preview
4162 // request if so. Can't use 'NULL request == repeat' across configure calls.
4163 if (mReconfigured) {
4164 mPrevRequest.clear();
4165 mReconfigured = false;
4166 }
4167
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004168 if (nextRequest != NULL) {
4169 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004170 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4171 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004172
4173 // Since RequestThread::clear() removes buffers from the input stream,
4174 // get the right buffer here before unlocking mRequestLock
4175 if (nextRequest->mInputStream != NULL) {
4176 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4177 if (res != OK) {
4178 // Can't get input buffer from gralloc queue - this could be due to
4179 // disconnected queue or other producer misbehavior, so not a fatal
4180 // error
4181 ALOGE("%s: Can't get input buffer, skipping request:"
4182 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004183
4184 sp<NotificationListener> listener = mListener.promote();
4185 if (listener != NULL) {
4186 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004187 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004188 nextRequest->mResultExtras);
4189 }
4190 return NULL;
4191 }
4192 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004193 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004194
4195 handleAePrecaptureCancelRequest(nextRequest);
4196
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 return nextRequest;
4198}
4199
4200bool Camera3Device::RequestThread::waitIfPaused() {
4201 status_t res;
4202 Mutex::Autolock l(mPauseLock);
4203 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004204 if (mPaused == false) {
4205 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004206 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4207 // Let the tracker know
4208 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4209 if (statusTracker != 0) {
4210 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4211 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004212 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004215 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004216 return true;
4217 }
4218 }
4219 // We don't set mPaused to false here, because waitForNextRequest needs
4220 // to further manage the paused state in case of starvation.
4221 return false;
4222}
4223
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004224void Camera3Device::RequestThread::unpauseForNewRequests() {
4225 // With work to do, mark thread as unpaused.
4226 // If paused by request (setPaused), don't resume, to avoid
4227 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004228 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004229 Mutex::Autolock p(mPauseLock);
4230 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004231 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4232 if (mPaused) {
4233 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4234 if (statusTracker != 0) {
4235 statusTracker->markComponentActive(mStatusId);
4236 }
4237 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004238 mPaused = false;
4239 }
4240}
4241
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004242void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4243 sp<Camera3Device> parent = mParent.promote();
4244 if (parent != NULL) {
4245 va_list args;
4246 va_start(args, fmt);
4247
4248 parent->setErrorStateV(fmt, args);
4249
4250 va_end(args);
4251 }
4252}
4253
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004254status_t Camera3Device::RequestThread::insertTriggers(
4255 const sp<CaptureRequest> &request) {
4256
4257 Mutex::Autolock al(mTriggerMutex);
4258
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004259 sp<Camera3Device> parent = mParent.promote();
4260 if (parent == NULL) {
4261 CLOGE("RequestThread: Parent is gone");
4262 return DEAD_OBJECT;
4263 }
4264
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004265 CameraMetadata &metadata = request->mSettings;
4266 size_t count = mTriggerMap.size();
4267
4268 for (size_t i = 0; i < count; ++i) {
4269 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004270 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004271
4272 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4273 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4274 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004275 if (isAeTrigger) {
4276 request->mResultExtras.precaptureTriggerId = triggerId;
4277 mCurrentPreCaptureTriggerId = triggerId;
4278 } else {
4279 request->mResultExtras.afTriggerId = triggerId;
4280 mCurrentAfTriggerId = triggerId;
4281 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004282 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4283 continue; // Trigger ID tag is deprecated since device HAL 3.2
4284 }
4285 }
4286
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004287 camera_metadata_entry entry = metadata.find(tag);
4288
4289 if (entry.count > 0) {
4290 /**
4291 * Already has an entry for this trigger in the request.
4292 * Rewrite it with our requested trigger value.
4293 */
4294 RequestTrigger oldTrigger = trigger;
4295
4296 oldTrigger.entryValue = entry.data.u8[0];
4297
4298 mTriggerReplacedMap.add(tag, oldTrigger);
4299 } else {
4300 /**
4301 * More typical, no trigger entry, so we just add it
4302 */
4303 mTriggerRemovedMap.add(tag, trigger);
4304 }
4305
4306 status_t res;
4307
4308 switch (trigger.getTagType()) {
4309 case TYPE_BYTE: {
4310 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4311 res = metadata.update(tag,
4312 &entryValue,
4313 /*count*/1);
4314 break;
4315 }
4316 case TYPE_INT32:
4317 res = metadata.update(tag,
4318 &trigger.entryValue,
4319 /*count*/1);
4320 break;
4321 default:
4322 ALOGE("%s: Type not supported: 0x%x",
4323 __FUNCTION__,
4324 trigger.getTagType());
4325 return INVALID_OPERATION;
4326 }
4327
4328 if (res != OK) {
4329 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4330 ", value %d", __FUNCTION__, trigger.getTagName(),
4331 trigger.entryValue);
4332 return res;
4333 }
4334
4335 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4336 trigger.getTagName(),
4337 trigger.entryValue);
4338 }
4339
4340 mTriggerMap.clear();
4341
4342 return count;
4343}
4344
4345status_t Camera3Device::RequestThread::removeTriggers(
4346 const sp<CaptureRequest> &request) {
4347 Mutex::Autolock al(mTriggerMutex);
4348
4349 CameraMetadata &metadata = request->mSettings;
4350
4351 /**
4352 * Replace all old entries with their old values.
4353 */
4354 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4355 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4356
4357 status_t res;
4358
4359 uint32_t tag = trigger.metadataTag;
4360 switch (trigger.getTagType()) {
4361 case TYPE_BYTE: {
4362 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4363 res = metadata.update(tag,
4364 &entryValue,
4365 /*count*/1);
4366 break;
4367 }
4368 case TYPE_INT32:
4369 res = metadata.update(tag,
4370 &trigger.entryValue,
4371 /*count*/1);
4372 break;
4373 default:
4374 ALOGE("%s: Type not supported: 0x%x",
4375 __FUNCTION__,
4376 trigger.getTagType());
4377 return INVALID_OPERATION;
4378 }
4379
4380 if (res != OK) {
4381 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4382 ", trigger value %d", __FUNCTION__,
4383 trigger.getTagName(), trigger.entryValue);
4384 return res;
4385 }
4386 }
4387 mTriggerReplacedMap.clear();
4388
4389 /**
4390 * Remove all new entries.
4391 */
4392 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4393 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4394 status_t res = metadata.erase(trigger.metadataTag);
4395
4396 if (res != OK) {
4397 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4398 ", trigger value %d", __FUNCTION__,
4399 trigger.getTagName(), trigger.entryValue);
4400 return res;
4401 }
4402 }
4403 mTriggerRemovedMap.clear();
4404
4405 return OK;
4406}
4407
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004408status_t Camera3Device::RequestThread::addDummyTriggerIds(
4409 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004410 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004411 static const int32_t dummyTriggerId = 1;
4412 status_t res;
4413
4414 CameraMetadata &metadata = request->mSettings;
4415
4416 // If AF trigger is active, insert a dummy AF trigger ID if none already
4417 // exists
4418 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4419 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4420 if (afTrigger.count > 0 &&
4421 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4422 afId.count == 0) {
4423 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4424 if (res != OK) return res;
4425 }
4426
4427 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4428 // if none already exists
4429 camera_metadata_entry pcTrigger =
4430 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4431 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4432 if (pcTrigger.count > 0 &&
4433 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4434 pcId.count == 0) {
4435 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4436 &dummyTriggerId, 1);
4437 if (res != OK) return res;
4438 }
4439
4440 return OK;
4441}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004442
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004443/**
4444 * PreparerThread inner class methods
4445 */
4446
4447Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004448 Thread(/*canCallJava*/false), mListener(nullptr),
4449 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004450}
4451
4452Camera3Device::PreparerThread::~PreparerThread() {
4453 Thread::requestExitAndWait();
4454 if (mCurrentStream != nullptr) {
4455 mCurrentStream->cancelPrepare();
4456 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4457 mCurrentStream.clear();
4458 }
4459 clear();
4460}
4461
Ruben Brunkc78ac262015-08-13 17:58:46 -07004462status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004463 status_t res;
4464
4465 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004466 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004467
Ruben Brunkc78ac262015-08-13 17:58:46 -07004468 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004469 if (res == OK) {
4470 // No preparation needed, fire listener right off
4471 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004472 if (listener != NULL) {
4473 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004474 }
4475 return OK;
4476 } else if (res != NOT_ENOUGH_DATA) {
4477 return res;
4478 }
4479
4480 // Need to prepare, start up thread if necessary
4481 if (!mActive) {
4482 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4483 // isn't running
4484 Thread::requestExitAndWait();
4485 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4486 if (res != OK) {
4487 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004488 if (listener != NULL) {
4489 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004490 }
4491 return res;
4492 }
4493 mCancelNow = false;
4494 mActive = true;
4495 ALOGV("%s: Preparer stream started", __FUNCTION__);
4496 }
4497
4498 // queue up the work
4499 mPendingStreams.push_back(stream);
4500 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4501
4502 return OK;
4503}
4504
4505status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004506 Mutex::Autolock l(mLock);
4507
4508 for (const auto& stream : mPendingStreams) {
4509 stream->cancelPrepare();
4510 }
4511 mPendingStreams.clear();
4512 mCancelNow = true;
4513
4514 return OK;
4515}
4516
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004517void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004518 Mutex::Autolock l(mLock);
4519 mListener = listener;
4520}
4521
4522bool Camera3Device::PreparerThread::threadLoop() {
4523 status_t res;
4524 {
4525 Mutex::Autolock l(mLock);
4526 if (mCurrentStream == nullptr) {
4527 // End thread if done with work
4528 if (mPendingStreams.empty()) {
4529 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4530 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4531 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4532 mActive = false;
4533 return false;
4534 }
4535
4536 // Get next stream to prepare
4537 auto it = mPendingStreams.begin();
4538 mCurrentStream = *it;
4539 mPendingStreams.erase(it);
4540 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4541 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4542 } else if (mCancelNow) {
4543 mCurrentStream->cancelPrepare();
4544 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4545 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4546 mCurrentStream.clear();
4547 mCancelNow = false;
4548 return true;
4549 }
4550 }
4551
4552 res = mCurrentStream->prepareNextBuffer();
4553 if (res == NOT_ENOUGH_DATA) return true;
4554 if (res != OK) {
4555 // Something bad happened; try to recover by cancelling prepare and
4556 // signalling listener anyway
4557 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4558 mCurrentStream->getId(), res, strerror(-res));
4559 mCurrentStream->cancelPrepare();
4560 }
4561
4562 // This stream has finished, notify listener
4563 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004564 sp<NotificationListener> listener = mListener.promote();
4565 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004566 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4567 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004568 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004569 }
4570
4571 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4572 mCurrentStream.clear();
4573
4574 return true;
4575}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004576
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004577/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004578 * Static callback forwarding methods from HAL to instance
4579 */
4580
4581void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4582 const camera3_capture_result *result) {
4583 Camera3Device *d =
4584 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004585
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004586 d->processCaptureResult(result);
4587}
4588
4589void Camera3Device::sNotify(const camera3_callback_ops *cb,
4590 const camera3_notify_msg *msg) {
4591 Camera3Device *d =
4592 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4593 d->notify(msg);
4594}
4595
4596}; // namespace android