blob: ae62e749d2683e14179d1c7d0b6ee65aedc8722d [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
54#include "device3/Camera3ZslStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070055#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070056#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070057#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080058
59using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080060using namespace android::hardware::camera;
61using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080062
63namespace android {
64
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080065Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080066 mId(id),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mListener(NULL)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080078{
79 ATRACE_CALL();
80 camera3_callback_ops::notify = &sNotify;
81 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080082 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080083}
84
85Camera3Device::~Camera3Device()
86{
87 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080088 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080089 disconnect();
90}
91
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080093 return mId;
94}
95
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080096/**
97 * CameraDeviceBase interface
98 */
99
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800100status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700103 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800104 Mutex::Autolock l(mLock);
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800107 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700108 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109 return INVALID_OPERATION;
110 }
111
112 /** Open HAL device */
113
114 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800115
116 camera3_device_t *device;
117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118 ATRACE_BEGIN("CameraHal::open");
119 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800120 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800121 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800122
123 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700124 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800125 return res;
126 }
127
128 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700130 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700131 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800133 device->common.version);
134 device->common.close(&device->common);
135 return BAD_VALUE;
136 }
137
138 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800140 if (res != OK) return res;
141
142 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700143 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
144 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700145 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800146 device->common.close(&device->common);
147 return BAD_VALUE;
148 }
149
150 /** Initialize device with callback functions */
151
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800152 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800153 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700154 ATRACE_END();
155
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800156 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700157 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
158 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800159 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800160 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800161 }
162
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800163 /** Everything is good to go */
164
165 mDeviceVersion = device->common.version;
166 mDeviceInfo = info.static_camera_characteristics;
167 mInterface = std::make_unique<HalInterface>(device);
168
169 return initializeCommonLocked();
170}
171
172status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
173 ATRACE_CALL();
174 Mutex::Autolock il(mInterfaceLock);
175 Mutex::Autolock l(mLock);
176
177 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
178 if (mStatus != STATUS_UNINITIALIZED) {
179 CLOGE("Already initialized!");
180 return INVALID_OPERATION;
181 }
182 if (manager == nullptr) return INVALID_OPERATION;
183
184 sp<ICameraDeviceSession> session;
185 ATRACE_BEGIN("CameraHal::openSession");
186 status_t res = manager->openSession(String8::std_string(mId), this,
187 /*out*/ &session);
188 ATRACE_END();
189 if (res != OK) {
190 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
191 return res;
192 }
193
194 res = manager->getCameraCharacteristics(String8::std_string(mId), &mDeviceInfo);
195 if (res != OK) {
196 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
197 session->close();
198 return res;
199 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800200
201 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
202 // for now use 3_4 to keep legacy devices working
203 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800204 mInterface = std::make_unique<HalInterface>(session);
205
206 return initializeCommonLocked();
207}
208
209status_t Camera3Device::initializeCommonLocked() {
210
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700211 /** Start up status tracker thread */
212 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800213 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700214 if (res != OK) {
215 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
216 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800217 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700218 mStatusTracker.clear();
219 return res;
220 }
221
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700222 /** Register in-flight map to the status tracker */
223 mInFlightStatusId = mStatusTracker->addComponent();
224
Zhijun He125684a2015-12-26 15:07:30 -0800225 /** Create buffer manager */
226 mBufferManager = new Camera3BufferManager();
227
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700228 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800229 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
230 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
231 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700232 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
233 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
234 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800235
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700236 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800237 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
238 aeLockAvailable);
239 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800240 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700241 SET_ERR_L("Unable to start request queue thread: %s (%d)",
242 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800243 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800244 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800245 return res;
246 }
247
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700248 mPreparerThread = new PreparerThread();
249
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700250 // Determine whether we need to derive sensitivity boost values for older devices.
251 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
252 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800253 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700254 mDerivePostRawSensKey = true;
255 }
256
Ruben Brunk183f0562015-08-12 12:55:02 -0700257 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800258 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700259 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700260 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800262
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800263 // Measure the clock domain offset between camera and video/hw_composer
264 camera_metadata_entry timestampSource =
265 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
266 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
267 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
268 mTimestampOffset = getMonoToBoottimeOffset();
269 }
270
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700271 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700272 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
273 camera_metadata_entry partialResultsCount =
274 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
275 if (partialResultsCount.count > 0) {
276 mNumPartialResults = partialResultsCount.data.i32[0];
277 mUsePartialResult = (mNumPartialResults > 1);
278 }
279 } else {
280 camera_metadata_entry partialResultsQuirk =
281 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
282 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
283 mUsePartialResult = true;
284 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700285 }
286
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700287 camera_metadata_entry configs =
288 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
289 for (uint32_t i = 0; i < configs.count; i += 4) {
290 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
291 configs.data.i32[i + 3] ==
292 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
293 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
294 configs.data.i32[i + 2]));
295 }
296 }
297
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800298 return OK;
299}
300
301status_t Camera3Device::disconnect() {
302 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700303 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700305 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800306
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700307 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800308
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 {
310 Mutex::Autolock l(mLock);
311 if (mStatus == STATUS_UNINITIALIZED) return res;
312
313 if (mStatus == STATUS_ACTIVE ||
314 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
315 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700316 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700318 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 } else {
320 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
321 if (res != OK) {
322 SET_ERR_L("Timeout waiting for HAL to drain");
323 // Continue to close device even in case of error
324 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 if (mStatus == STATUS_ERROR) {
329 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700330 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331
332 if (mStatusTracker != NULL) {
333 mStatusTracker->requestExit();
334 }
335
336 if (mRequestThread != NULL) {
337 mRequestThread->requestExit();
338 }
339
340 mOutputStreams.clear();
341 mInputStream.clear();
342 }
343
344 // Joining done without holding mLock, otherwise deadlocks may ensue
345 // as the threads try to access parent state
346 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
347 // HAL may be in a bad state, so waiting for request thread
348 // (which may be stuck in the HAL processCaptureRequest call)
349 // could be dangerous.
350 mRequestThread->join();
351 }
352
353 if (mStatusTracker != NULL) {
354 mStatusTracker->join();
355 }
356
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700358 {
359 Mutex::Autolock l(mLock);
360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800361 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700362 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800363 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800365 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800367
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700368 // Call close without internal mutex held, as the HAL close may need to
369 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800370 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700371
372 {
373 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800374 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700375 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700376 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800377
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700378 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700379 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800380}
381
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382// For dumping/debugging only -
383// try to acquire a lock a few times, eventually give up to proceed with
384// debug/dump operations
385bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
386 bool gotLock = false;
387 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
388 if (lock.tryLock() == NO_ERROR) {
389 gotLock = true;
390 break;
391 } else {
392 usleep(kDumpSleepDuration);
393 }
394 }
395 return gotLock;
396}
397
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700398Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
399 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
400 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
401 const int STREAM_CONFIGURATION_SIZE = 4;
402 const int STREAM_FORMAT_OFFSET = 0;
403 const int STREAM_WIDTH_OFFSET = 1;
404 const int STREAM_HEIGHT_OFFSET = 2;
405 const int STREAM_IS_INPUT_OFFSET = 3;
406 camera_metadata_ro_entry_t availableStreamConfigs =
407 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
408 if (availableStreamConfigs.count == 0 ||
409 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
410 return Size(0, 0);
411 }
412
413 // Get max jpeg size (area-wise).
414 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
415 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
416 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
417 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
418 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
419 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
420 && format == HAL_PIXEL_FORMAT_BLOB &&
421 (width * height > maxJpegWidth * maxJpegHeight)) {
422 maxJpegWidth = width;
423 maxJpegHeight = height;
424 }
425 }
426 } else {
427 camera_metadata_ro_entry availableJpegSizes =
428 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
429 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
430 return Size(0, 0);
431 }
432
433 // Get max jpeg size (area-wise).
434 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
435 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
436 > (maxJpegWidth * maxJpegHeight)) {
437 maxJpegWidth = availableJpegSizes.data.i32[i];
438 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
439 }
440 }
441 }
442 return Size(maxJpegWidth, maxJpegHeight);
443}
444
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800445nsecs_t Camera3Device::getMonoToBoottimeOffset() {
446 // try three times to get the clock offset, choose the one
447 // with the minimum gap in measurements.
448 const int tries = 3;
449 nsecs_t bestGap, measured;
450 for (int i = 0; i < tries; ++i) {
451 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
452 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
453 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
454 const nsecs_t gap = tmono2 - tmono;
455 if (i == 0 || gap < bestGap) {
456 bestGap = gap;
457 measured = tbase - ((tmono + tmono2) >> 1);
458 }
459 }
460 return measured;
461}
462
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700463/**
464 * Map Android N dataspace definitions back to Android M definitions, for
465 * use with HALv3.3 or older.
466 *
467 * Only map where correspondences exist, and otherwise preserve the value.
468 */
469android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
470 switch (dataSpace) {
471 case HAL_DATASPACE_V0_SRGB_LINEAR:
472 return HAL_DATASPACE_SRGB_LINEAR;
473 case HAL_DATASPACE_V0_SRGB:
474 return HAL_DATASPACE_SRGB;
475 case HAL_DATASPACE_V0_JFIF:
476 return HAL_DATASPACE_JFIF;
477 case HAL_DATASPACE_V0_BT601_625:
478 return HAL_DATASPACE_BT601_625;
479 case HAL_DATASPACE_V0_BT601_525:
480 return HAL_DATASPACE_BT601_525;
481 case HAL_DATASPACE_V0_BT709:
482 return HAL_DATASPACE_BT709;
483 default:
484 return dataSpace;
485 }
486}
487
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
489 int frameworkFormat) {
490 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
491}
492
493DataspaceFlags Camera3Device::mapToHidlDataspace(
494 android_dataspace dataSpace) {
495 return dataSpace;
496}
497
498ConsumerUsageFlags Camera3Device::mapToConsumerUsage(
499 uint32_t usage) {
500 return usage;
501}
502
503StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
504 switch (rotation) {
505 case CAMERA3_STREAM_ROTATION_0:
506 return StreamRotation::ROTATION_0;
507 case CAMERA3_STREAM_ROTATION_90:
508 return StreamRotation::ROTATION_90;
509 case CAMERA3_STREAM_ROTATION_180:
510 return StreamRotation::ROTATION_180;
511 case CAMERA3_STREAM_ROTATION_270:
512 return StreamRotation::ROTATION_270;
513 }
514 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
515 return StreamRotation::ROTATION_0;
516}
517
518StreamConfigurationMode Camera3Device::mapToStreamConfigurationMode(
519 camera3_stream_configuration_mode_t operationMode) {
520 switch(operationMode) {
521 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
522 return StreamConfigurationMode::NORMAL_MODE;
523 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
524 return StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
525 case CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START:
526 // Needs to be mapped by vendor extensions
527 break;
528 }
529 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
530 return StreamConfigurationMode::NORMAL_MODE;
531}
532
533camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
534 switch (status) {
535 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
536 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
537 }
538 return CAMERA3_BUFFER_STATUS_ERROR;
539}
540
541int Camera3Device::mapToFrameworkFormat(
542 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
543 return static_cast<uint32_t>(pixelFormat);
544}
545
546uint32_t Camera3Device::mapConsumerToFrameworkUsage(
547 ConsumerUsageFlags usage) {
548 return usage;
549}
550
551uint32_t Camera3Device::mapProducerToFrameworkUsage(
552 ProducerUsageFlags usage) {
553 return usage;
554}
555
Zhijun Hef7da0962014-04-24 13:27:56 -0700556ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700557 // Get max jpeg size (area-wise).
558 Size maxJpegResolution = getMaxJpegResolution();
559 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
561 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700562 return BAD_VALUE;
563 }
564
Zhijun Hef7da0962014-04-24 13:27:56 -0700565 // Get max jpeg buffer size
566 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700567 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
568 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800569 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
570 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700571 return BAD_VALUE;
572 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700573 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800574 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700575
576 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700577 float scaleFactor = ((float) (width * height)) /
578 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800579 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
580 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 if (jpegBufferSize > maxJpegBufferSize) {
582 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700583 }
584
585 return jpegBufferSize;
586}
587
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700588ssize_t Camera3Device::getPointCloudBufferSize() const {
589 const int FLOATS_PER_POINT=4;
590 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
591 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800592 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
593 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700594 return BAD_VALUE;
595 }
596 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
597 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
598 return maxBytesForPointCloud;
599}
600
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800602 const int PER_CONFIGURATION_SIZE = 3;
603 const int WIDTH_OFFSET = 0;
604 const int HEIGHT_OFFSET = 1;
605 const int SIZE_OFFSET = 2;
606 camera_metadata_ro_entry rawOpaqueSizes =
607 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800608 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800609 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800610 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
611 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800612 return BAD_VALUE;
613 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700614
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800615 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
616 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
617 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
618 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
619 }
620 }
621
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800622 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
623 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800624 return BAD_VALUE;
625}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700626
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800627status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
628 ATRACE_CALL();
629 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700630
631 // Try to lock, but continue in case of failure (to avoid blocking in
632 // deadlocks)
633 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
634 bool gotLock = tryLockSpinRightRound(mLock);
635
636 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
638 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700639 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
641 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700642
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800643 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700644
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800645 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700646 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800647 int n = args.size();
648 for (int i = 0; i < n; i++) {
649 if (args[i] == templatesOption) {
650 dumpTemplates = true;
651 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700652 if (args[i] == monitorOption) {
653 if (i + 1 < n) {
654 String8 monitorTags = String8(args[i + 1]);
655 if (monitorTags == "off") {
656 mTagMonitor.disableMonitoring();
657 } else {
658 mTagMonitor.parseTagsToMonitor(monitorTags);
659 }
660 } else {
661 mTagMonitor.disableMonitoring();
662 }
663 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800664 }
665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800666 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 const char *status =
669 mStatus == STATUS_ERROR ? "ERROR" :
670 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700671 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
672 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800673 mStatus == STATUS_ACTIVE ? "ACTIVE" :
674 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700675
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800676 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700677 if (mStatus == STATUS_ERROR) {
678 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
679 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680 lines.appendFormat(" Stream configuration:\n");
Zhijun He1fa89992015-06-01 15:44:31 -0700681 lines.appendFormat(" Operation mode: %s \n", mIsConstrainedHighSpeedConfiguration ?
Eino-Ville Talvala9a179412015-06-09 13:15:16 -0700682 "CONSTRAINED HIGH SPEED VIDEO" : "NORMAL");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800683
684 if (mInputStream != NULL) {
685 write(fd, lines.string(), lines.size());
686 mInputStream->dump(fd, args);
687 } else {
688 lines.appendFormat(" No input stream.\n");
689 write(fd, lines.string(), lines.size());
690 }
691 for (size_t i = 0; i < mOutputStreams.size(); i++) {
692 mOutputStreams[i]->dump(fd,args);
693 }
694
Zhijun He431503c2016-03-07 17:30:16 -0800695 if (mBufferManager != NULL) {
696 lines = String8(" Camera3 Buffer Manager:\n");
697 write(fd, lines.string(), lines.size());
698 mBufferManager->dump(fd, args);
699 }
Zhijun He125684a2015-12-26 15:07:30 -0800700
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700701 lines = String8(" In-flight requests:\n");
702 if (mInFlightMap.size() == 0) {
703 lines.append(" None\n");
704 } else {
705 for (size_t i = 0; i < mInFlightMap.size(); i++) {
706 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700707 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700708 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800709 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700710 r.numBuffersLeft);
711 }
712 }
713 write(fd, lines.string(), lines.size());
714
Igor Murashkin1e479c02013-09-06 16:55:14 -0700715 {
716 lines = String8(" Last request sent:\n");
717 write(fd, lines.string(), lines.size());
718
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700720 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
721 }
722
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800723 if (dumpTemplates) {
724 const char *templateNames[] = {
725 "TEMPLATE_PREVIEW",
726 "TEMPLATE_STILL_CAPTURE",
727 "TEMPLATE_VIDEO_RECORD",
728 "TEMPLATE_VIDEO_SNAPSHOT",
729 "TEMPLATE_ZERO_SHUTTER_LAG",
730 "TEMPLATE_MANUAL"
731 };
732
733 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800734 camera_metadata_t *templateRequest = nullptr;
735 mInterface->constructDefaultRequestSettings(
736 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800737 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800738 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800739 lines.append(" Not supported\n");
740 write(fd, lines.string(), lines.size());
741 } else {
742 write(fd, lines.string(), lines.size());
743 dump_indented_camera_metadata(templateRequest,
744 fd, /*verbosity*/2, /*indentation*/8);
745 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800746 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800747 }
748 }
749
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700750 mTagMonitor.dumpMonitoredMetadata(fd);
751
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 if (mInterface->valid()) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800754 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800755 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800756 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700758 if (gotLock) mLock.unlock();
759 if (gotInterfaceLock) mInterfaceLock.unlock();
760
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761 return OK;
762}
763
764const CameraMetadata& Camera3Device::info() const {
765 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800766 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
767 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700768 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800769 mStatus == STATUS_ERROR ?
770 "when in error state" : "before init");
771 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772 return mDeviceInfo;
773}
774
Jianing Wei90e59c92014-03-12 18:29:36 -0700775status_t Camera3Device::checkStatusOkToCaptureLocked() {
776 switch (mStatus) {
777 case STATUS_ERROR:
778 CLOGE("Device has encountered a serious error");
779 return INVALID_OPERATION;
780 case STATUS_UNINITIALIZED:
781 CLOGE("Device not initialized");
782 return INVALID_OPERATION;
783 case STATUS_UNCONFIGURED:
784 case STATUS_CONFIGURED:
785 case STATUS_ACTIVE:
786 // OK
787 break;
788 default:
789 SET_ERR_L("Unexpected status: %d", mStatus);
790 return INVALID_OPERATION;
791 }
792 return OK;
793}
794
795status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 const List<const CameraMetadata> &metadataList,
797 const std::list<const SurfaceMap> &surfaceMaps,
798 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700799 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700800 if (requestList == NULL) {
801 CLOGE("requestList cannot be NULL.");
802 return BAD_VALUE;
803 }
804
Jianing Weicb0652e2014-03-12 18:29:36 -0700805 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
807 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
808 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
809 ++metadataIt, ++surfaceMapIt) {
810 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 if (newRequest == 0) {
812 CLOGE("Can't create capture request");
813 return BAD_VALUE;
814 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700815
Shuzhen Wang9d066012016-09-30 11:30:20 -0700816 newRequest->mRepeating = repeating;
817
Jianing Weicb0652e2014-03-12 18:29:36 -0700818 // Setup burst Id and request Id
819 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
821 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700822 CLOGE("RequestID entry exists; but must not be empty in metadata");
823 return BAD_VALUE;
824 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700825 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700826 } else {
827 CLOGE("RequestID does not exist in metadata");
828 return BAD_VALUE;
829 }
830
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700832
833 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
836 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
837 return BAD_VALUE;
838 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700839
840 // Setup batch size if this is a high speed video recording request.
841 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
842 auto firstRequest = requestList->begin();
843 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
844 if (outputStream->isVideoStream()) {
845 (*firstRequest)->mBatchSize = requestList->size();
846 break;
847 }
848 }
849 }
850
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 return OK;
852}
853
Jianing Weicb0652e2014-03-12 18:29:36 -0700854status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700857 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
859 convertToRequestList(requests, surfaceMaps, request);
860
861 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
862}
863
864void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
865 std::list<const SurfaceMap>& surfaceMaps,
866 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700867 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868
869 SurfaceMap surfaceMap;
870 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
871 // With no surface list passed in, stream and surface will have 1-to-1
872 // mapping. So the surface index is 0 for each stream in the surfaceMap.
873 for (size_t i = 0; i < streams.count; i++) {
874 surfaceMap[streams.data.i32[i]].push_back(0);
875 }
876 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877}
878
Jianing Wei90e59c92014-03-12 18:29:36 -0700879status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700880 const List<const CameraMetadata> &requests,
881 const std::list<const SurfaceMap> &surfaceMaps,
882 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700883 /*out*/
884 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 ATRACE_CALL();
886 Mutex::Autolock il(mInterfaceLock);
887 Mutex::Autolock l(mLock);
888
889 status_t res = checkStatusOkToCaptureLocked();
890 if (res != OK) {
891 // error logged by previous call
892 return res;
893 }
894
895 RequestList requestList;
896
Shuzhen Wang0129d522016-10-30 22:43:41 -0700897 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
898 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 if (res != OK) {
900 // error logged by previous call
901 return res;
902 }
903
904 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700905 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700906 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700907 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700908 }
909
910 if (res == OK) {
911 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
912 if (res != OK) {
913 SET_ERR_L("Can't transition to active in %f seconds!",
914 kActiveTimeout/1e9);
915 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800916 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700917 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 } else {
919 CLOGE("Cannot queue request. Impossible.");
920 return BAD_VALUE;
921 }
922
923 return res;
924}
925
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926hardware::Return<void> Camera3Device::processCaptureResult(
927 const device::V3_2::CaptureResult& result) {
928 camera3_capture_result r;
929 status_t res;
930 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800931 if (result.result.size() != 0) {
932 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
933 size_t expected_metadata_size = result.result.size();
934 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
935 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
936 __FUNCTION__, result.frameNumber, strerror(-res), res);
937 return hardware::Void();
938 }
939 } else {
940 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800941 }
942
943 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
944 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
945 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
946 auto& bDst = outputBuffers[i];
947 const StreamBuffer &bSrc = result.outputBuffers[i];
948
949 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
950 if (idx == -1) {
951 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
952 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
953 return hardware::Void();
954 }
955 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
956
957 buffer_handle_t *buffer;
958 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId,
959 &buffer);
960 if (res != OK) {
961 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
962 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
963 return hardware::Void();
964 }
965 bDst.buffer = buffer;
966 bDst.status = mapHidlBufferStatus(bSrc.status);
967 bDst.acquire_fence = -1;
968 if (bSrc.releaseFence == nullptr) {
969 bDst.release_fence = -1;
970 } else if (bSrc.releaseFence->numFds == 1) {
971 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
972 } else {
973 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
974 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
975 return hardware::Void();
976 }
977 }
978 r.num_output_buffers = outputBuffers.size();
979 r.output_buffers = outputBuffers.data();
980
981 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800982 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800983 r.input_buffer = nullptr;
984 } else {
985 if (mInputStream->getId() != result.inputBuffer.streamId) {
986 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
987 result.frameNumber, result.inputBuffer.streamId);
988 return hardware::Void();
989 }
990 inputBuffer.stream = mInputStream->asHalStream();
991 buffer_handle_t *buffer;
992 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
993 &buffer);
994 if (res != OK) {
995 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
996 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
997 return hardware::Void();
998 }
999 inputBuffer.buffer = buffer;
1000 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1001 inputBuffer.acquire_fence = -1;
1002 if (result.inputBuffer.releaseFence == nullptr) {
1003 inputBuffer.release_fence = -1;
1004 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1005 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1006 } else {
1007 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1008 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
1009 return hardware::Void();
1010 }
1011 r.input_buffer = &inputBuffer;
1012 }
1013
1014 r.partial_result = result.partialResult;
1015
1016 processCaptureResult(&r);
1017
1018 return hardware::Void();
1019}
1020
1021hardware::Return<void> Camera3Device::notify(
1022 const NotifyMsg& msg) {
1023 camera3_notify_msg m;
1024 switch (msg.type) {
1025 case MsgType::ERROR:
1026 m.type = CAMERA3_MSG_ERROR;
1027 m.message.error.frame_number = msg.msg.error.frameNumber;
1028 if (msg.msg.error.errorStreamId >= 0) {
1029 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
1030 if (idx == -1) {
1031 ALOGE("%s: Frame %d: Invalid error stream id %d",
1032 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
1033 return hardware::Void();
1034 }
1035 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1036 } else {
1037 m.message.error.error_stream = nullptr;
1038 }
1039 switch (msg.msg.error.errorCode) {
1040 case ErrorCode::ERROR_DEVICE:
1041 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1042 break;
1043 case ErrorCode::ERROR_REQUEST:
1044 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1045 break;
1046 case ErrorCode::ERROR_RESULT:
1047 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1048 break;
1049 case ErrorCode::ERROR_BUFFER:
1050 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1051 break;
1052 }
1053 break;
1054 case MsgType::SHUTTER:
1055 m.type = CAMERA3_MSG_SHUTTER;
1056 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1057 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1058 break;
1059 }
1060 notify(&m);
1061
1062 return hardware::Void();
1063}
1064
Jianing Weicb0652e2014-03-12 18:29:36 -07001065status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001066 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001067 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001068 ATRACE_CALL();
1069
Shuzhen Wang0129d522016-10-30 22:43:41 -07001070 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001071}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001072
Jianing Weicb0652e2014-03-12 18:29:36 -07001073status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1074 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001075 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001076
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001077 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001078 std::list<const SurfaceMap> surfaceMaps;
1079 convertToRequestList(requests, surfaceMaps, request);
1080
1081 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1082 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083}
1084
Jianing Weicb0652e2014-03-12 18:29:36 -07001085status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001086 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001087 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001088 ATRACE_CALL();
1089
Shuzhen Wang0129d522016-10-30 22:43:41 -07001090 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001091}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001092
1093sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001094 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001095 status_t res;
1096
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001097 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001098 res = configureStreamsLocked();
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001099 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001101 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001102 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001103 } else if (mStatus == STATUS_UNCONFIGURED) {
1104 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001105 CLOGE("No streams configured");
1106 return NULL;
1107 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001108 }
1109
Shuzhen Wang0129d522016-10-30 22:43:41 -07001110 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001111 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001112}
1113
Jianing Weicb0652e2014-03-12 18:29:36 -07001114status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001115 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001116 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001118
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001119 switch (mStatus) {
1120 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001121 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001122 return INVALID_OPERATION;
1123 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001124 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001125 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001126 case STATUS_UNCONFIGURED:
1127 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128 case STATUS_ACTIVE:
1129 // OK
1130 break;
1131 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001132 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001133 return INVALID_OPERATION;
1134 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001135 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001136
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001137 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001138}
1139
1140status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1141 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001142 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001143
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001144 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001145}
1146
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001147status_t Camera3Device::createInputStream(
1148 uint32_t width, uint32_t height, int format, int *id) {
1149 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001150 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001151 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001152 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1153 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001154
1155 status_t res;
1156 bool wasActive = false;
1157
1158 switch (mStatus) {
1159 case STATUS_ERROR:
1160 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1161 return INVALID_OPERATION;
1162 case STATUS_UNINITIALIZED:
1163 ALOGE("%s: Device not initialized", __FUNCTION__);
1164 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001165 case STATUS_UNCONFIGURED:
1166 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001167 // OK
1168 break;
1169 case STATUS_ACTIVE:
1170 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001171 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001172 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001174 return res;
1175 }
1176 wasActive = true;
1177 break;
1178 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001179 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001180 return INVALID_OPERATION;
1181 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001182 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001183
1184 if (mInputStream != 0) {
1185 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1186 return INVALID_OPERATION;
1187 }
1188
1189 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1190 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001192
1193 mInputStream = newStream;
1194
1195 *id = mNextStreamId++;
1196
1197 // Continue captures if active at start
1198 if (wasActive) {
1199 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1200 res = configureStreamsLocked();
1201 if (res != OK) {
1202 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1203 __FUNCTION__, mNextStreamId, strerror(-res), res);
1204 return res;
1205 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001207 }
1208
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001209 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001210 return OK;
1211}
1212
Igor Murashkin2fba5842013-04-22 14:03:54 -07001213
1214status_t Camera3Device::createZslStream(
1215 uint32_t width, uint32_t height,
1216 int depth,
1217 /*out*/
1218 int *id,
1219 sp<Camera3ZslStream>* zslStream) {
1220 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001222 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001223 ALOGV("Camera %s: Creating ZSL stream %d: %d x %d, depth %d",
1224 mId.string(), mNextStreamId, width, height, depth);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001225
1226 status_t res;
1227 bool wasActive = false;
1228
1229 switch (mStatus) {
1230 case STATUS_ERROR:
1231 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1232 return INVALID_OPERATION;
1233 case STATUS_UNINITIALIZED:
1234 ALOGE("%s: Device not initialized", __FUNCTION__);
1235 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 case STATUS_UNCONFIGURED:
1237 case STATUS_CONFIGURED:
Igor Murashkin2fba5842013-04-22 14:03:54 -07001238 // OK
1239 break;
1240 case STATUS_ACTIVE:
1241 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 res = internalPauseAndWaitLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001243 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001244 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin2fba5842013-04-22 14:03:54 -07001245 return res;
1246 }
1247 wasActive = true;
1248 break;
1249 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 SET_ERR_L("Unexpected status: %d", mStatus);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001251 return INVALID_OPERATION;
1252 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001254
1255 if (mInputStream != 0) {
1256 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1257 return INVALID_OPERATION;
1258 }
1259
1260 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
1261 width, height, depth);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin2fba5842013-04-22 14:03:54 -07001263
1264 res = mOutputStreams.add(mNextStreamId, newStream);
1265 if (res < 0) {
1266 ALOGE("%s: Can't add new stream to set: %s (%d)",
1267 __FUNCTION__, strerror(-res), res);
1268 return res;
1269 }
1270 mInputStream = newStream;
1271
Yuvraj Pasie5e3d082014-04-15 18:37:45 +05301272 mNeedConfig = true;
1273
Igor Murashkin2fba5842013-04-22 14:03:54 -07001274 *id = mNextStreamId++;
1275 *zslStream = newStream;
1276
1277 // Continue captures if active at start
1278 if (wasActive) {
1279 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1280 res = configureStreamsLocked();
1281 if (res != OK) {
1282 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1283 __FUNCTION__, mNextStreamId, strerror(-res), res);
1284 return res;
1285 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 internalResumeLocked();
Igor Murashkin2fba5842013-04-22 14:03:54 -07001287 }
1288
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001289 ALOGV("Camera %s: Created ZSL stream", mId.string());
Igor Murashkin2fba5842013-04-22 14:03:54 -07001290 return OK;
1291}
1292
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001293status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001294 uint32_t width, uint32_t height, int format,
1295 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
1296 int streamSetId, uint32_t consumerUsage) {
1297 ATRACE_CALL();
1298
1299 if (consumer == nullptr) {
1300 ALOGE("%s: consumer must not be null", __FUNCTION__);
1301 return BAD_VALUE;
1302 }
1303
1304 std::vector<sp<Surface>> consumers;
1305 consumers.push_back(consumer);
1306
1307 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
1308 format, dataSpace, rotation, id, streamSetId, consumerUsage);
1309}
1310
1311status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1312 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1313 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
1314 int streamSetId, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001315 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
1319 " consumer usage 0x%x", mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Zhijun He5d677d12016-05-29 16:52:39 -07001320 consumerUsage);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001321
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001322 status_t res;
1323 bool wasActive = false;
1324
1325 switch (mStatus) {
1326 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001327 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001328 return INVALID_OPERATION;
1329 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001330 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001332 case STATUS_UNCONFIGURED:
1333 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001334 // OK
1335 break;
1336 case STATUS_ACTIVE:
1337 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001338 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001339 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001340 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 return res;
1342 }
1343 wasActive = true;
1344 break;
1345 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001346 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 return INVALID_OPERATION;
1348 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001349 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350
1351 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001352 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001353 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001354 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001355 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1356 }
Zhijun He5d677d12016-05-29 16:52:39 -07001357
Shuzhen Wang0129d522016-10-30 22:43:41 -07001358 if (consumers.size() == 0 && !hasDeferredConsumer) {
1359 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1360 return BAD_VALUE;
1361 }
Zhijun He5d677d12016-05-29 16:52:39 -07001362 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1363 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001364 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001365 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1366 return BAD_VALUE;
1367 }
1368
Shuzhen Wang0129d522016-10-30 22:43:41 -07001369 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001370 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1371 return BAD_VALUE;
1372 }
1373
Shuzhen Wang0129d522016-10-30 22:43:41 -07001374 bool streamSharing = consumers.size() > 1 || (consumers.size() > 0 && hasDeferredConsumer);
1375
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001376 // Use legacy dataspace values for older HALs
1377 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1378 dataSpace = mapToLegacyDataspace(dataSpace);
1379 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001381 ssize_t blobBufferSize;
1382 if (dataSpace != HAL_DATASPACE_DEPTH) {
1383 blobBufferSize = getJpegBufferSize(width, height);
1384 if (blobBufferSize <= 0) {
1385 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1386 return BAD_VALUE;
1387 }
1388 } else {
1389 blobBufferSize = getPointCloudBufferSize();
1390 if (blobBufferSize <= 0) {
1391 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1392 return BAD_VALUE;
1393 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001394 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001395 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001396 width, height, blobBufferSize, format, dataSpace, rotation,
1397 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001398 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1399 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1400 if (rawOpaqueBufferSize <= 0) {
1401 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1402 return BAD_VALUE;
1403 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001404 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001405 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1406 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001407 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001408 newStream = new Camera3OutputStream(mNextStreamId,
1409 width, height, format, consumerUsage, dataSpace, rotation,
1410 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001411 } else if (streamSharing) {
1412 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1413 hasDeferredConsumer, width, height, format, consumerUsage,
1414 dataSpace, rotation, mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001416 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001417 width, height, format, dataSpace, rotation,
1418 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001420 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001421
Zhijun He125684a2015-12-26 15:07:30 -08001422 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001423 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1424 * requires buffers to be statically allocated for internal static buffer registration, while
1425 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1426 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001427 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001428 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001429 newStream->setBufferManager(mBufferManager);
1430 }
1431
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001432 res = mOutputStreams.add(mNextStreamId, newStream);
1433 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001434 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435 return res;
1436 }
1437
1438 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001439 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440
1441 // Continue captures if active at start
1442 if (wasActive) {
1443 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1444 res = configureStreamsLocked();
1445 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001446 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1447 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 return res;
1449 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001450 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454}
1455
1456status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
1457 ATRACE_CALL();
1458 (void)outputId; (void)id;
1459
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001460 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001461 return INVALID_OPERATION;
1462}
1463
1464
1465status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001466 uint32_t *width, uint32_t *height,
1467 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001468 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 switch (mStatus) {
1473 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001474 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 return INVALID_OPERATION;
1476 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001477 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001479 case STATUS_UNCONFIGURED:
1480 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 case STATUS_ACTIVE:
1482 // OK
1483 break;
1484 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001485 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 return INVALID_OPERATION;
1487 }
1488
1489 ssize_t idx = mOutputStreams.indexOfKey(id);
1490 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001491 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 return idx;
1493 }
1494
1495 if (width) *width = mOutputStreams[idx]->getWidth();
1496 if (height) *height = mOutputStreams[idx]->getHeight();
1497 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001498 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001500}
1501
1502status_t Camera3Device::setStreamTransform(int id,
1503 int transform) {
1504 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 switch (mStatus) {
1509 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001510 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 return INVALID_OPERATION;
1512 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001513 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 case STATUS_UNCONFIGURED:
1516 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 case STATUS_ACTIVE:
1518 // OK
1519 break;
1520 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001521 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return INVALID_OPERATION;
1523 }
1524
1525 ssize_t idx = mOutputStreams.indexOfKey(id);
1526 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 CLOGE("Stream %d does not exist",
1528 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 return BAD_VALUE;
1530 }
1531
1532 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533}
1534
1535status_t Camera3Device::deleteStream(int id) {
1536 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 Mutex::Autolock l(mLock);
1539 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001541 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001542
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 // CameraDevice semantics require device to already be idle before
1544 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001546 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001547 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 }
1549
Igor Murashkin2fba5842013-04-22 14:03:54 -07001550 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001551 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 if (mInputStream != NULL && id == mInputStream->getId()) {
1553 deletedStream = mInputStream;
1554 mInputStream.clear();
1555 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001556 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001557 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return BAD_VALUE;
1559 }
Zhijun He5f446352014-01-22 09:49:33 -08001560 }
1561
1562 // Delete output stream or the output part of a bi-directional stream.
1563 if (outputStreamIdx != NAME_NOT_FOUND) {
1564 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 mOutputStreams.removeItem(id);
1566 }
1567
1568 // Free up the stream endpoint so that it can be used by some other stream
1569 res = deletedStream->disconnect();
1570 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 // fall through since we want to still list the stream as deleted.
1573 }
1574 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001575 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576
1577 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001578}
1579
1580status_t Camera3Device::deleteReprocessStream(int id) {
1581 ATRACE_CALL();
1582 (void)id;
1583
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001584 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001585 return INVALID_OPERATION;
1586}
1587
Zhijun He1fa89992015-06-01 15:44:31 -07001588status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001589 ATRACE_CALL();
1590 ALOGV("%s: E", __FUNCTION__);
1591
1592 Mutex::Autolock il(mInterfaceLock);
1593 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001594
1595 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) {
1596 mNeedConfig = true;
1597 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
1598 }
Igor Murashkine2d167e2014-08-19 16:19:59 -07001599
1600 return configureStreamsLocked();
1601}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001602
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001603status_t Camera3Device::getInputBufferProducer(
1604 sp<IGraphicBufferProducer> *producer) {
1605 Mutex::Autolock il(mInterfaceLock);
1606 Mutex::Autolock l(mLock);
1607
1608 if (producer == NULL) {
1609 return BAD_VALUE;
1610 } else if (mInputStream == NULL) {
1611 return INVALID_OPERATION;
1612 }
1613
1614 return mInputStream->getInputBufferProducer(producer);
1615}
1616
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617status_t Camera3Device::createDefaultRequest(int templateId,
1618 CameraMetadata *request) {
1619 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001620 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001621
1622 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1623 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1624 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1625 return BAD_VALUE;
1626 }
1627
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001628 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 Mutex::Autolock l(mLock);
1630
1631 switch (mStatus) {
1632 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001633 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001634 return INVALID_OPERATION;
1635 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001636 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001637 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 case STATUS_UNCONFIGURED:
1639 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001640 case STATUS_ACTIVE:
1641 // OK
1642 break;
1643 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001644 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001645 return INVALID_OPERATION;
1646 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647
Zhijun Hea1530f12014-09-14 12:44:20 -07001648 if (!mRequestTemplateCache[templateId].isEmpty()) {
1649 *request = mRequestTemplateCache[templateId];
1650 return OK;
1651 }
1652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001653 camera_metadata_t *rawRequest;
1654 status_t res = mInterface->constructDefaultRequestSettings(
1655 (camera3_request_template_t) templateId, &rawRequest);
1656 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001657 ALOGI("%s: template %d is not supported on this camera device",
1658 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001659 return res;
1660 } else if (res != OK) {
1661 CLOGE("Unable to construct request template %d: %s (%d)",
1662 templateId, strerror(-res), res);
1663 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001664 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001665
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001666 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001667
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001668 // Derive some new keys for backward compatibility
1669 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1670 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1671 int32_t defaultBoost[1] = {100};
1672 mRequestTemplateCache[templateId].update(
1673 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1674 defaultBoost, 1);
1675 }
1676
1677 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001678 return OK;
1679}
1680
1681status_t Camera3Device::waitUntilDrained() {
1682 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001684 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Zhijun He69a37482014-03-23 18:44:49 -07001686 return waitUntilDrainedLocked();
1687}
1688
1689status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001690 switch (mStatus) {
1691 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001692 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001693 ALOGV("%s: Already idle", __FUNCTION__);
1694 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 case STATUS_CONFIGURED:
1696 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001697 case STATUS_ERROR:
1698 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001699 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001700 break;
1701 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001702 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001703 return INVALID_OPERATION;
1704 }
1705
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001706 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001707 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001708 if (res != OK) {
1709 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1710 res);
1711 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001712 return res;
1713}
1714
Ruben Brunk183f0562015-08-12 12:55:02 -07001715
1716void Camera3Device::internalUpdateStatusLocked(Status status) {
1717 mStatus = status;
1718 mRecentStatusUpdates.add(mStatus);
1719 mStatusChanged.broadcast();
1720}
1721
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722// Pause to reconfigure
1723status_t Camera3Device::internalPauseAndWaitLocked() {
1724 mRequestThread->setPaused(true);
1725 mPauseStateNotify = true;
1726
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001727 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001728 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1729 if (res != OK) {
1730 SET_ERR_L("Can't idle device in %f seconds!",
1731 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732 }
1733
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001734 return res;
1735}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001737// Resume after internalPauseAndWaitLocked
1738status_t Camera3Device::internalResumeLocked() {
1739 status_t res;
1740
1741 mRequestThread->setPaused(false);
1742
1743 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1744 if (res != OK) {
1745 SET_ERR_L("Can't transition to active in %f seconds!",
1746 kActiveTimeout/1e9);
1747 }
1748 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001749 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750}
1751
Ruben Brunk183f0562015-08-12 12:55:02 -07001752status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001753 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001754
1755 size_t startIndex = 0;
1756 if (mStatusWaiters == 0) {
1757 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1758 // this status list
1759 mRecentStatusUpdates.clear();
1760 } else {
1761 // If other threads are waiting on updates to this status list, set the position of the
1762 // first element that this list will check rather than clearing the list.
1763 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001764 }
1765
Ruben Brunk183f0562015-08-12 12:55:02 -07001766 mStatusWaiters++;
1767
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 bool stateSeen = false;
1769 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001770 if (active == (mStatus == STATUS_ACTIVE)) {
1771 // Desired state is current
1772 break;
1773 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774
1775 res = mStatusChanged.waitRelative(mLock, timeout);
1776 if (res != OK) break;
1777
Ruben Brunk183f0562015-08-12 12:55:02 -07001778 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1779 // transitions.
1780 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1781 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1782 __FUNCTION__);
1783
1784 // Encountered desired state since we began waiting
1785 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001786 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1787 stateSeen = true;
1788 break;
1789 }
1790 }
1791 } while (!stateSeen);
1792
Ruben Brunk183f0562015-08-12 12:55:02 -07001793 mStatusWaiters--;
1794
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795 return res;
1796}
1797
1798
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001799status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001800 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001801 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001802
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001803 if (listener != NULL && mListener != NULL) {
1804 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1805 }
1806 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001807 mRequestThread->setNotificationListener(listener);
1808 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001809
1810 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811}
1812
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001813bool Camera3Device::willNotify3A() {
1814 return false;
1815}
1816
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001817status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001818 status_t res;
1819 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001821 while (mResultQueue.empty()) {
1822 res = mResultSignal.waitRelative(mOutputLock, timeout);
1823 if (res == TIMED_OUT) {
1824 return res;
1825 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001826 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1827 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001828 return res;
1829 }
1830 }
1831 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001832}
1833
Jianing Weicb0652e2014-03-12 18:29:36 -07001834status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001835 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001836 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001837
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001838 if (mResultQueue.empty()) {
1839 return NOT_ENOUGH_DATA;
1840 }
1841
Jianing Weicb0652e2014-03-12 18:29:36 -07001842 if (frame == NULL) {
1843 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1844 return BAD_VALUE;
1845 }
1846
1847 CaptureResult &result = *(mResultQueue.begin());
1848 frame->mResultExtras = result.mResultExtras;
1849 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001850 mResultQueue.erase(mResultQueue.begin());
1851
1852 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001853}
1854
1855status_t Camera3Device::triggerAutofocus(uint32_t id) {
1856 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001857 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001858
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001859 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1860 // Mix-in this trigger into the next request and only the next request.
1861 RequestTrigger trigger[] = {
1862 {
1863 ANDROID_CONTROL_AF_TRIGGER,
1864 ANDROID_CONTROL_AF_TRIGGER_START
1865 },
1866 {
1867 ANDROID_CONTROL_AF_TRIGGER_ID,
1868 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001869 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001870 };
1871
1872 return mRequestThread->queueTrigger(trigger,
1873 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874}
1875
1876status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1877 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001879
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001880 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1881 // Mix-in this trigger into the next request and only the next request.
1882 RequestTrigger trigger[] = {
1883 {
1884 ANDROID_CONTROL_AF_TRIGGER,
1885 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1886 },
1887 {
1888 ANDROID_CONTROL_AF_TRIGGER_ID,
1889 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001890 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001891 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001893 return mRequestThread->queueTrigger(trigger,
1894 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895}
1896
1897status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001901 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1902 // Mix-in this trigger into the next request and only the next request.
1903 RequestTrigger trigger[] = {
1904 {
1905 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1906 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1907 },
1908 {
1909 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1910 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001911 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001912 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001914 return mRequestThread->queueTrigger(trigger,
1915 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916}
1917
1918status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1919 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1920 ATRACE_CALL();
1921 (void)reprocessStreamId; (void)buffer; (void)listener;
1922
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001923 CLOGE("Unimplemented");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924 return INVALID_OPERATION;
1925}
1926
Jianing Weicb0652e2014-03-12 18:29:36 -07001927status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001928 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001929 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001930 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001931
Zhijun He7ef20392014-04-21 16:04:17 -07001932 {
1933 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001934 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001935 }
1936
Zhijun He491e3412013-12-27 10:57:44 -08001937 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001938 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001939 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001940 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001941 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001942 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001943 }
1944
1945 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001946}
1947
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001948status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001949 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1950}
1951
1952status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001953 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001954 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001955 Mutex::Autolock il(mInterfaceLock);
1956 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001957
1958 sp<Camera3StreamInterface> stream;
1959 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1960 if (outputStreamIdx == NAME_NOT_FOUND) {
1961 CLOGE("Stream %d does not exist", streamId);
1962 return BAD_VALUE;
1963 }
1964
1965 stream = mOutputStreams.editValueAt(outputStreamIdx);
1966
1967 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001968 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001969 return BAD_VALUE;
1970 }
1971
1972 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001973 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001974 return BAD_VALUE;
1975 }
1976
Ruben Brunkc78ac262015-08-13 17:58:46 -07001977 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001978}
1979
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001980status_t Camera3Device::tearDown(int streamId) {
1981 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001982 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001983 Mutex::Autolock il(mInterfaceLock);
1984 Mutex::Autolock l(mLock);
1985
1986 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1987 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001988 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001989 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001990 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001991 return NO_INIT;
1992 }
1993
1994 sp<Camera3StreamInterface> stream;
1995 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1996 if (outputStreamIdx == NAME_NOT_FOUND) {
1997 CLOGE("Stream %d does not exist", streamId);
1998 return BAD_VALUE;
1999 }
2000
2001 stream = mOutputStreams.editValueAt(outputStreamIdx);
2002
2003 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2004 CLOGE("Stream %d is a target of a in-progress request", streamId);
2005 return BAD_VALUE;
2006 }
2007
2008 return stream->tearDown();
2009}
2010
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002011status_t Camera3Device::addBufferListenerForStream(int streamId,
2012 wp<Camera3StreamBufferListener> listener) {
2013 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002014 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002015 Mutex::Autolock il(mInterfaceLock);
2016 Mutex::Autolock l(mLock);
2017
2018 sp<Camera3StreamInterface> stream;
2019 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2020 if (outputStreamIdx == NAME_NOT_FOUND) {
2021 CLOGE("Stream %d does not exist", streamId);
2022 return BAD_VALUE;
2023 }
2024
2025 stream = mOutputStreams.editValueAt(outputStreamIdx);
2026 stream->addBufferListener(listener);
2027
2028 return OK;
2029}
2030
Zhijun He204e3292014-07-14 17:09:23 -07002031uint32_t Camera3Device::getDeviceVersion() {
2032 ATRACE_CALL();
2033 Mutex::Autolock il(mInterfaceLock);
2034 return mDeviceVersion;
2035}
2036
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002038 * Methods called by subclasses
2039 */
2040
2041void Camera3Device::notifyStatus(bool idle) {
2042 {
2043 // Need mLock to safely update state and synchronize to current
2044 // state of methods in flight.
2045 Mutex::Autolock l(mLock);
2046 // We can get various system-idle notices from the status tracker
2047 // while starting up. Only care about them if we've actually sent
2048 // in some requests recently.
2049 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2050 return;
2051 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002052 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002053 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07002054 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002055
2056 // Skip notifying listener if we're doing some user-transparent
2057 // state changes
2058 if (mPauseStateNotify) return;
2059 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002060
2061 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002062 {
2063 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002064 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065 }
2066 if (idle && listener != NULL) {
2067 listener->notifyIdle();
2068 }
2069}
2070
Zhijun He5d677d12016-05-29 16:52:39 -07002071status_t Camera3Device::setConsumerSurface(int streamId, sp<Surface> consumer) {
2072 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002073 ALOGV("%s: Camera %s: set consumer surface for stream %d", __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002074 Mutex::Autolock il(mInterfaceLock);
2075 Mutex::Autolock l(mLock);
2076
2077 if (consumer == nullptr) {
2078 CLOGE("Null consumer is passed!");
2079 return BAD_VALUE;
2080 }
2081
2082 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2083 if (idx == NAME_NOT_FOUND) {
2084 CLOGE("Stream %d is unknown", streamId);
2085 return idx;
2086 }
2087 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2088 status_t res = stream->setConsumer(consumer);
2089 if (res != OK) {
2090 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2091 return res;
2092 }
2093
Shuzhen Wang0129d522016-10-30 22:43:41 -07002094 if (stream->isConsumerConfigurationDeferred()) {
2095 if (!stream->isConfiguring()) {
2096 CLOGE("Stream %d was already fully configured.", streamId);
2097 return INVALID_OPERATION;
2098 }
Zhijun He5d677d12016-05-29 16:52:39 -07002099
Shuzhen Wang0129d522016-10-30 22:43:41 -07002100 res = stream->finishConfiguration();
2101 if (res != OK) {
2102 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2103 stream->getId(), strerror(-res), res);
2104 return res;
2105 }
Zhijun He5d677d12016-05-29 16:52:39 -07002106 }
2107
2108 return OK;
2109}
2110
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002111/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 * Camera3Device private methods
2113 */
2114
2115sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002116 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 ATRACE_CALL();
2118 status_t res;
2119
2120 sp<CaptureRequest> newRequest = new CaptureRequest;
2121 newRequest->mSettings = request;
2122
2123 camera_metadata_entry_t inputStreams =
2124 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2125 if (inputStreams.count > 0) {
2126 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002127 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002128 CLOGE("Request references unknown input stream %d",
2129 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 return NULL;
2131 }
2132 // Lazy completion of stream configuration (allocation/registration)
2133 // on first use
2134 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002135 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002137 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002139 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002140 return NULL;
2141 }
2142 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002143 // Check if stream is being prepared
2144 if (mInputStream->isPreparing()) {
2145 CLOGE("Request references an input stream that's being prepared!");
2146 return NULL;
2147 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148
2149 newRequest->mInputStream = mInputStream;
2150 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2151 }
2152
2153 camera_metadata_entry_t streams =
2154 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2155 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002156 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002157 return NULL;
2158 }
2159
2160 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002161 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002163 CLOGE("Request references unknown stream %d",
2164 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 return NULL;
2166 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002167 sp<Camera3OutputStreamInterface> stream =
2168 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169
Zhijun He5d677d12016-05-29 16:52:39 -07002170 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002171 auto iter = surfaceMap.find(streams.data.i32[i]);
2172 if (iter != surfaceMap.end()) {
2173 const std::vector<size_t>& surfaces = iter->second;
2174 for (const auto& surface : surfaces) {
2175 if (stream->isConsumerConfigurationDeferred(surface)) {
2176 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2177 "due to deferred consumer", stream->getId(), surface);
2178 return NULL;
2179 }
2180 }
2181 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002182 }
2183
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002184 // Lazy completion of stream configuration (allocation/registration)
2185 // on first use
2186 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002187 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002188 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002189 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2190 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191 return NULL;
2192 }
2193 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002194 // Check if stream is being prepared
2195 if (stream->isPreparing()) {
2196 CLOGE("Request references an output stream that's being prepared!");
2197 return NULL;
2198 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002199
2200 newRequest->mOutputStreams.push(stream);
2201 }
2202 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002203 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002204
2205 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002206}
2207
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002208bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2209 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2210 Size size = mSupportedOpaqueInputSizes[i];
2211 if (size.width == width && size.height == height) {
2212 return true;
2213 }
2214 }
2215
2216 return false;
2217}
2218
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002219void Camera3Device::cancelStreamsConfigurationLocked() {
2220 int res = OK;
2221 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2222 res = mInputStream->cancelConfiguration();
2223 if (res != OK) {
2224 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2225 mInputStream->getId(), strerror(-res), res);
2226 }
2227 }
2228
2229 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2230 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2231 if (outputStream->isConfiguring()) {
2232 res = outputStream->cancelConfiguration();
2233 if (res != OK) {
2234 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2235 outputStream->getId(), strerror(-res), res);
2236 }
2237 }
2238 }
2239
2240 // Return state to that at start of call, so that future configures
2241 // properly clean things up
2242 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2243 mNeedConfig = true;
2244}
2245
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246status_t Camera3Device::configureStreamsLocked() {
2247 ATRACE_CALL();
2248 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002249
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002250 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002251 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 return INVALID_OPERATION;
2253 }
2254
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002255 if (!mNeedConfig) {
2256 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2257 return OK;
2258 }
2259
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002260 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2261 // adding a dummy stream instead.
2262 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2263 if (mOutputStreams.size() == 0) {
2264 addDummyStreamLocked();
2265 } else {
2266 tryRemoveDummyStreamLocked();
2267 }
2268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002269 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002270 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002271
2272 camera3_stream_configuration config;
Zhijun He1fa89992015-06-01 15:44:31 -07002273 config.operation_mode = mIsConstrainedHighSpeedConfiguration ?
2274 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE :
2275 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2277
2278 Vector<camera3_stream_t*> streams;
2279 streams.setCapacity(config.num_streams);
2280
2281 if (mInputStream != NULL) {
2282 camera3_stream_t *inputStream;
2283 inputStream = mInputStream->startConfiguration();
2284 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002285 CLOGE("Can't start input stream configuration");
2286 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287 return INVALID_OPERATION;
2288 }
2289 streams.add(inputStream);
2290 }
2291
2292 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002293
2294 // Don't configure bidi streams twice, nor add them twice to the list
2295 if (mOutputStreams[i].get() ==
2296 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2297
2298 config.num_streams--;
2299 continue;
2300 }
2301
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302 camera3_stream_t *outputStream;
2303 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2304 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002305 CLOGE("Can't start output stream configuration");
2306 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 return INVALID_OPERATION;
2308 }
2309 streams.add(outputStream);
2310 }
2311
2312 config.streams = streams.editArray();
2313
2314 // Do the HAL configuration; will potentially touch stream
2315 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002316
2317 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002319 if (res == BAD_VALUE) {
2320 // HAL rejected this set of streams as unsupported, clean up config
2321 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002322 CLOGE("Set of requested inputs/outputs not supported by HAL");
2323 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002324 return BAD_VALUE;
2325 } else if (res != OK) {
2326 // Some other kind of error from configure_streams - this is not
2327 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002328 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2329 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002330 return res;
2331 }
2332
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002333 // Finish all stream configuration immediately.
2334 // TODO: Try to relax this later back to lazy completion, which should be
2335 // faster
2336
Igor Murashkin073f8572013-05-02 14:59:28 -07002337 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002338 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002339 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002340 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002341 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002342 cancelStreamsConfigurationLocked();
2343 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002344 }
2345 }
2346
2347 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002348 sp<Camera3OutputStreamInterface> outputStream =
2349 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002350 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002351 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002352 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002353 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002354 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002355 cancelStreamsConfigurationLocked();
2356 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002357 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002358 }
2359 }
2360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 // Request thread needs to know to avoid using repeat-last-settings protocol
2362 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002363 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364
Zhijun He90f7c372016-08-16 16:19:43 -07002365 char value[PROPERTY_VALUE_MAX];
2366 property_get("camera.fifo.disable", value, "0");
2367 int32_t disableFifo = atoi(value);
2368 if (disableFifo != 1) {
2369 // Boost priority of request thread to SCHED_FIFO.
2370 pid_t requestThreadTid = mRequestThread->getTid();
2371 res = requestPriority(getpid(), requestThreadTid,
2372 kRequestThreadPriority, /*asynchronous*/ false);
2373 if (res != OK) {
2374 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2375 strerror(-res), res);
2376 } else {
2377 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2378 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002379 }
2380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002381 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002383 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384
Ruben Brunk183f0562015-08-12 12:55:02 -07002385 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2386 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002388 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002389
Zhijun He0a210512014-07-24 13:45:15 -07002390 // tear down the deleted streams after configure streams.
2391 mDeletedStreams.clear();
2392
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002394}
2395
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002396status_t Camera3Device::addDummyStreamLocked() {
2397 ATRACE_CALL();
2398 status_t res;
2399
2400 if (mDummyStreamId != NO_STREAM) {
2401 // Should never be adding a second dummy stream when one is already
2402 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002403 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2404 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002405 return INVALID_OPERATION;
2406 }
2407
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002408 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002409
2410 sp<Camera3OutputStreamInterface> dummyStream =
2411 new Camera3DummyStream(mNextStreamId);
2412
2413 res = mOutputStreams.add(mNextStreamId, dummyStream);
2414 if (res < 0) {
2415 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2416 return res;
2417 }
2418
2419 mDummyStreamId = mNextStreamId;
2420 mNextStreamId++;
2421
2422 return OK;
2423}
2424
2425status_t Camera3Device::tryRemoveDummyStreamLocked() {
2426 ATRACE_CALL();
2427 status_t res;
2428
2429 if (mDummyStreamId == NO_STREAM) return OK;
2430 if (mOutputStreams.size() == 1) return OK;
2431
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002432 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002433
2434 // Ok, have a dummy stream and there's at least one other output stream,
2435 // so remove the dummy
2436
2437 sp<Camera3StreamInterface> deletedStream;
2438 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2439 if (outputStreamIdx == NAME_NOT_FOUND) {
2440 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2441 return INVALID_OPERATION;
2442 }
2443
2444 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2445 mOutputStreams.removeItemsAt(outputStreamIdx);
2446
2447 // Free up the stream endpoint so that it can be used by some other stream
2448 res = deletedStream->disconnect();
2449 if (res != OK) {
2450 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2451 // fall through since we want to still list the stream as deleted.
2452 }
2453 mDeletedStreams.add(deletedStream);
2454 mDummyStreamId = NO_STREAM;
2455
2456 return res;
2457}
2458
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002459void Camera3Device::setErrorState(const char *fmt, ...) {
2460 Mutex::Autolock l(mLock);
2461 va_list args;
2462 va_start(args, fmt);
2463
2464 setErrorStateLockedV(fmt, args);
2465
2466 va_end(args);
2467}
2468
2469void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2470 Mutex::Autolock l(mLock);
2471 setErrorStateLockedV(fmt, args);
2472}
2473
2474void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2475 va_list args;
2476 va_start(args, fmt);
2477
2478 setErrorStateLockedV(fmt, args);
2479
2480 va_end(args);
2481}
2482
2483void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002484 // Print out all error messages to log
2485 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002486 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002487
2488 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002489 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002490
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002491 mErrorCause = errorCause;
2492
2493 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002494 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002495
2496 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002497 sp<NotificationListener> listener = mListener.promote();
2498 if (listener != NULL) {
2499 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002500 CaptureResultExtras());
2501 }
2502
2503 // Save stack trace. View by dumping it later.
2504 CameraTraces::saveTrace();
2505 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002506}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002507
2508/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002509 * In-flight request management
2510 */
2511
Jianing Weicb0652e2014-03-12 18:29:36 -07002512status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002513 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2514 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002515 ATRACE_CALL();
2516 Mutex::Autolock l(mInFlightLock);
2517
2518 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002519 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2520 aeTriggerCancelOverride));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002521 if (res < 0) return res;
2522
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002523 if (mInFlightMap.size() == 1) {
2524 mStatusTracker->markComponentActive(mInFlightStatusId);
2525 }
2526
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002527 return OK;
2528}
2529
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002530void Camera3Device::returnOutputBuffers(
2531 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2532 nsecs_t timestamp) {
2533 for (size_t i = 0; i < numBuffers; i++)
2534 {
2535 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2536 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2537 // Note: stream may be deallocated at this point, if this buffer was
2538 // the last reference to it.
2539 if (res != OK) {
2540 ALOGE("Can't return buffer to its stream: %s (%d)",
2541 strerror(-res), res);
2542 }
2543 }
2544}
2545
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002546void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2547 mInFlightMap.removeItemsAt(idx, 1);
2548
2549 // Indicate idle inFlightMap to the status tracker
2550 if (mInFlightMap.size() == 0) {
2551 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2552 }
2553}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002554
2555void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2556
2557 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2558 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2559
2560 nsecs_t sensorTimestamp = request.sensorTimestamp;
2561 nsecs_t shutterTimestamp = request.shutterTimestamp;
2562
2563 // Check if it's okay to remove the request from InFlightMap:
2564 // In the case of a successful request:
2565 // all input and output buffers, all result metadata, shutter callback
2566 // arrived.
2567 // In the case of a unsuccessful request:
2568 // all input and output buffers arrived.
2569 if (request.numBuffersLeft == 0 &&
2570 (request.requestStatus != OK ||
2571 (request.haveResultMetadata && shutterTimestamp != 0))) {
2572 ATRACE_ASYNC_END("frame capture", frameNumber);
2573
2574 // Sanity check - if sensor timestamp matches shutter timestamp
2575 if (request.requestStatus == OK &&
2576 sensorTimestamp != shutterTimestamp) {
2577 SET_ERR("sensor timestamp (%" PRId64
2578 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2579 sensorTimestamp, frameNumber, shutterTimestamp);
2580 }
2581
2582 // for an unsuccessful request, it may have pending output buffers to
2583 // return.
2584 assert(request.requestStatus != OK ||
2585 request.pendingOutputBuffers.size() == 0);
2586 returnOutputBuffers(request.pendingOutputBuffers.array(),
2587 request.pendingOutputBuffers.size(), 0);
2588
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002589 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002590 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2591 }
2592
2593 // Sanity check - if we have too many in-flight frames, something has
2594 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002595 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002596 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002597 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2598 kInFlightWarnLimitHighSpeed) {
2599 CLOGE("In-flight list too large for high speed configuration: %zu",
2600 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002601 }
2602}
2603
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002604void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2605 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2606 if (result == nullptr) return;
2607
2608 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2609 (int32_t*)&frameNumber, 1) != OK) {
2610 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2611 return;
2612 }
2613
2614 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2615 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2616 return;
2617 }
2618
2619 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2620
2621 // Valid result, insert into queue
2622 List<CaptureResult>::iterator queuedResult =
2623 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2624 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2625 ", burstId = %" PRId32, __FUNCTION__,
2626 queuedResult->mResultExtras.requestId,
2627 queuedResult->mResultExtras.frameNumber,
2628 queuedResult->mResultExtras.burstId);
2629
2630 mResultSignal.signal();
2631}
2632
2633
2634void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2635 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2636 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2637 Mutex::Autolock l(mOutputLock);
2638
2639 CaptureResult captureResult;
2640 captureResult.mResultExtras = resultExtras;
2641 captureResult.mMetadata = partialResult;
2642
2643 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2644}
2645
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002646
2647void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2648 CaptureResultExtras &resultExtras,
2649 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002650 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002651 bool reprocess,
2652 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002653 if (pendingMetadata.isEmpty())
2654 return;
2655
2656 Mutex::Autolock l(mOutputLock);
2657
2658 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002659 if (reprocess) {
2660 if (frameNumber < mNextReprocessResultFrameNumber) {
2661 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002662 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002663 frameNumber, mNextReprocessResultFrameNumber);
2664 return;
2665 }
2666 mNextReprocessResultFrameNumber = frameNumber + 1;
2667 } else {
2668 if (frameNumber < mNextResultFrameNumber) {
2669 SET_ERR("Out-of-order capture result metadata submitted! "
2670 "(got frame number %d, expecting %d)",
2671 frameNumber, mNextResultFrameNumber);
2672 return;
2673 }
2674 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002675 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002676
2677 CaptureResult captureResult;
2678 captureResult.mResultExtras = resultExtras;
2679 captureResult.mMetadata = pendingMetadata;
2680
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002681 // Append any previous partials to form a complete result
2682 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2683 captureResult.mMetadata.append(collectedPartialResult);
2684 }
2685
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002686 // Derive some new keys for backward compaibility
2687 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2688 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2689 int32_t defaultBoost[1] = {100};
2690 captureResult.mMetadata.update(
2691 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2692 defaultBoost, 1);
2693 }
2694
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002695 captureResult.mMetadata.sort();
2696
2697 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002698 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2699 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002700 SET_ERR("No timestamp provided by HAL for frame %d!",
2701 frameNumber);
2702 return;
2703 }
2704
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002705 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2706 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2707
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002708 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002709}
2710
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002711/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002712 * Camera HAL device callback methods
2713 */
2714
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002715void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002716 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002717
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002718 status_t res;
2719
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002720 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002721 if (result->result == NULL && result->num_output_buffers == 0 &&
2722 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723 SET_ERR("No result data provided by HAL for frame %d",
2724 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002725 return;
2726 }
Zhijun He204e3292014-07-14 17:09:23 -07002727
2728 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2729 // partial_result to 1 when metadata is included in this result.
2730 if (!mUsePartialResult &&
2731 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2732 result->result != NULL &&
2733 result->partial_result != 1) {
2734 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2735 " if partial result is not supported",
2736 frameNumber, result->partial_result);
2737 return;
2738 }
2739
2740 bool isPartialResult = false;
2741 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002742 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002743 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002744
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002745 // Get shutter timestamp and resultExtras from list of in-flight requests,
2746 // where it was added by the shutter notification for this frame. If the
2747 // shutter timestamp isn't received yet, append the output buffers to the
2748 // in-flight request and they will be returned when the shutter timestamp
2749 // arrives. Update the in-flight status and remove the in-flight entry if
2750 // all result data and shutter timestamp have been received.
2751 nsecs_t shutterTimestamp = 0;
2752
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002753 {
2754 Mutex::Autolock l(mInFlightLock);
2755 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2756 if (idx == NAME_NOT_FOUND) {
2757 SET_ERR("Unknown frame number for capture result: %d",
2758 frameNumber);
2759 return;
2760 }
2761 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002762 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2763 ", frameNumber = %" PRId64 ", burstId = %" PRId32
2764 ", partialResultCount = %d",
2765 __FUNCTION__, request.resultExtras.requestId,
2766 request.resultExtras.frameNumber, request.resultExtras.burstId,
2767 result->partial_result);
2768 // Always update the partial count to the latest one if it's not 0
2769 // (buffers only). When framework aggregates adjacent partial results
2770 // into one, the latest partial count will be used.
2771 if (result->partial_result != 0)
2772 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002773
2774 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002775 if (mUsePartialResult && result->result != NULL) {
2776 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2777 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2778 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2779 " the range of [1, %d] when metadata is included in the result",
2780 frameNumber, result->partial_result, mNumPartialResults);
2781 return;
2782 }
2783 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002784 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002785 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002786 }
Zhijun He204e3292014-07-14 17:09:23 -07002787 } else {
2788 camera_metadata_ro_entry_t partialResultEntry;
2789 res = find_camera_metadata_ro_entry(result->result,
2790 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2791 if (res != NAME_NOT_FOUND &&
2792 partialResultEntry.count > 0 &&
2793 partialResultEntry.data.u8[0] ==
2794 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2795 // A partial result. Flag this as such, and collect this
2796 // set of metadata into the in-flight entry.
2797 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002798 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002799 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002800 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002801 ANDROID_QUIRKS_PARTIAL_RESULT);
2802 }
2803 }
2804
2805 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002806 // Send partial capture result
2807 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2808 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002809 }
2810 }
2811
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002812 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002813 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002814
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002815 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002816 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002817 if (request.haveResultMetadata) {
2818 SET_ERR("Called multiple times with metadata for frame %d",
2819 frameNumber);
2820 return;
2821 }
Zhijun He204e3292014-07-14 17:09:23 -07002822 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002823 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002824 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002825 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002826 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002827 request.haveResultMetadata = true;
2828 }
2829
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002830 uint32_t numBuffersReturned = result->num_output_buffers;
2831 if (result->input_buffer != NULL) {
2832 if (hasInputBufferInRequest) {
2833 numBuffersReturned += 1;
2834 } else {
2835 ALOGW("%s: Input buffer should be NULL if there is no input"
2836 " buffer sent in the request",
2837 __FUNCTION__);
2838 }
2839 }
2840 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002841 if (request.numBuffersLeft < 0) {
2842 SET_ERR("Too many buffers returned for frame %d",
2843 frameNumber);
2844 return;
2845 }
2846
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002847 camera_metadata_ro_entry_t entry;
2848 res = find_camera_metadata_ro_entry(result->result,
2849 ANDROID_SENSOR_TIMESTAMP, &entry);
2850 if (res == OK && entry.count == 1) {
2851 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002852 }
2853
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002854 // If shutter event isn't received yet, append the output buffers to
2855 // the in-flight request. Otherwise, return the output buffers to
2856 // streams.
2857 if (shutterTimestamp == 0) {
2858 request.pendingOutputBuffers.appendArray(result->output_buffers,
2859 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002860 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002861 returnOutputBuffers(result->output_buffers,
2862 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002863 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002864
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002865 if (result->result != NULL && !isPartialResult) {
2866 if (shutterTimestamp == 0) {
2867 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002868 request.collectedPartialResult = collectedPartialResult;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002869 } else {
2870 CameraMetadata metadata;
2871 metadata = result->result;
2872 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002873 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2874 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002875 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002876 }
2877
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002878 removeInFlightRequestIfReadyLocked(idx);
2879 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002880
Zhijun Hef0d962a2014-06-30 10:24:11 -07002881 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002882 if (hasInputBufferInRequest) {
2883 Camera3Stream *stream =
2884 Camera3Stream::cast(result->input_buffer->stream);
2885 res = stream->returnInputBuffer(*(result->input_buffer));
2886 // Note: stream may be deallocated at this point, if this buffer was the
2887 // last reference to it.
2888 if (res != OK) {
2889 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2890 " its stream:%s (%d)", __FUNCTION__,
2891 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002892 }
2893 } else {
2894 ALOGW("%s: Input buffer should be NULL if there is no input"
2895 " buffer sent in the request, skipping input buffer return.",
2896 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002897 }
2898 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002899}
2900
2901void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002902 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002903 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002904 {
2905 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002906 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002907 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002908
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002909 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002910 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002911 return;
2912 }
2913
2914 switch (msg->type) {
2915 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002916 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002917 break;
2918 }
2919 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002920 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002921 break;
2922 }
2923 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002924 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002925 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002926 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002927}
2928
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002929void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002930 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931
2932 // Map camera HAL error codes to ICameraDeviceCallback error codes
2933 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002934 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002935 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002936 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002937 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002938 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002939 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002941 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002942 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002943 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002944 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002945 };
2946
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002948 ((msg.error_code >= 0) &&
2949 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2950 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002951 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002952
2953 int streamId = 0;
2954 if (msg.error_stream != NULL) {
2955 Camera3Stream *stream =
2956 Camera3Stream::cast(msg.error_stream);
2957 streamId = stream->getId();
2958 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002959 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2960 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002961 streamId, msg.error_code);
2962
2963 CaptureResultExtras resultExtras;
2964 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002965 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002966 // SET_ERR calls notifyError
2967 SET_ERR("Camera HAL reported serious device error");
2968 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2970 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2971 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002972 {
2973 Mutex::Autolock l(mInFlightLock);
2974 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2975 if (idx >= 0) {
2976 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2977 r.requestStatus = msg.error_code;
2978 resultExtras = r.resultExtras;
2979 } else {
2980 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002981 ALOGE("Camera %s: %s: cannot find in-flight request on "
2982 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002983 resultExtras.frameNumber);
2984 }
2985 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002986 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002987 if (listener != NULL) {
2988 listener->notifyError(errorCode, resultExtras);
2989 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002991 }
2992 break;
2993 default:
2994 // SET_ERR calls notifyError
2995 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2996 break;
2997 }
2998}
2999
3000void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003001 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003002 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003003
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003004 // Set timestamp for the request in the in-flight tracking
3005 // and get the request ID to send upstream
3006 {
3007 Mutex::Autolock l(mInFlightLock);
3008 idx = mInFlightMap.indexOfKey(msg.frame_number);
3009 if (idx >= 0) {
3010 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003011
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003012 // Verify ordering of shutter notifications
3013 {
3014 Mutex::Autolock l(mOutputLock);
3015 // TODO: need to track errors for tighter bounds on expected frame number.
3016 if (r.hasInputBuffer) {
3017 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3018 SET_ERR("Shutter notification out-of-order. Expected "
3019 "notification for frame %d, got frame %d",
3020 mNextReprocessShutterFrameNumber, msg.frame_number);
3021 return;
3022 }
3023 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3024 } else {
3025 if (msg.frame_number < mNextShutterFrameNumber) {
3026 SET_ERR("Shutter notification out-of-order. Expected "
3027 "notification for frame %d, got frame %d",
3028 mNextShutterFrameNumber, msg.frame_number);
3029 return;
3030 }
3031 mNextShutterFrameNumber = msg.frame_number + 1;
3032 }
3033 }
3034
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003035 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
3036 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003037 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
3038 // Call listener, if any
3039 if (listener != NULL) {
3040 listener->notifyShutter(r.resultExtras, msg.timestamp);
3041 }
3042
3043 r.shutterTimestamp = msg.timestamp;
3044
3045 // send pending result and buffers
3046 sendCaptureResult(r.pendingMetadata, r.resultExtras,
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003047 r.collectedPartialResult, msg.frame_number,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003048 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003049 returnOutputBuffers(r.pendingOutputBuffers.array(),
3050 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3051 r.pendingOutputBuffers.clear();
3052
3053 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003054 }
3055 }
3056 if (idx < 0) {
3057 SET_ERR("Shutter notification for non-existent frame number %d",
3058 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003059 }
3060}
3061
3062
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003063CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003064 ALOGV("%s", __FUNCTION__);
3065
Igor Murashkin1e479c02013-09-06 16:55:14 -07003066 CameraMetadata retVal;
3067
3068 if (mRequestThread != NULL) {
3069 retVal = mRequestThread->getLatestRequest();
3070 }
3071
Igor Murashkin1e479c02013-09-06 16:55:14 -07003072 return retVal;
3073}
3074
Jianing Weicb0652e2014-03-12 18:29:36 -07003075
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003076void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3077 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3078 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3079}
3080
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003081/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003082 * HalInterface inner class methods
3083 */
3084
3085Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3086 mHal3Device(device) {}
3087
3088Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3089 mHal3Device(nullptr),
3090 mHidlSession(session) {}
3091
3092Camera3Device::HalInterface::HalInterface() :
3093 mHal3Device(nullptr) {}
3094
3095Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
3096 mHal3Device(other.mHal3Device), mHidlSession(other.mHidlSession) {}
3097
3098bool Camera3Device::HalInterface::valid() {
3099 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3100}
3101
3102void Camera3Device::HalInterface::clear() {
3103 mHal3Device = nullptr;
3104 mHidlSession.clear();
3105}
3106
3107status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3108 camera3_request_template_t templateId,
3109 /*out*/ camera_metadata_t **requestTemplate) {
3110 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3111 if (!valid()) return INVALID_OPERATION;
3112 status_t res = OK;
3113
3114 if (mHal3Device != nullptr) {
3115 const camera_metadata *r;
3116 r = mHal3Device->ops->construct_default_request_settings(
3117 mHal3Device, templateId);
3118 if (r == nullptr) return BAD_VALUE;
3119 *requestTemplate = clone_camera_metadata(r);
3120 if (requestTemplate == nullptr) {
3121 ALOGE("%s: Unable to clone camera metadata received from HAL",
3122 __FUNCTION__);
3123 return INVALID_OPERATION;
3124 }
3125 } else {
3126 common::V1_0::Status status;
3127 RequestTemplate id;
3128 switch (templateId) {
3129 case CAMERA3_TEMPLATE_PREVIEW:
3130 id = RequestTemplate::PREVIEW;
3131 break;
3132 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3133 id = RequestTemplate::STILL_CAPTURE;
3134 break;
3135 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3136 id = RequestTemplate::VIDEO_RECORD;
3137 break;
3138 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3139 id = RequestTemplate::VIDEO_SNAPSHOT;
3140 break;
3141 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3142 id = RequestTemplate::ZERO_SHUTTER_LAG;
3143 break;
3144 case CAMERA3_TEMPLATE_MANUAL:
3145 id = RequestTemplate::MANUAL;
3146 break;
3147 default:
3148 // Unknown template ID
3149 return BAD_VALUE;
3150 }
3151 mHidlSession->constructDefaultRequestSettings(id,
3152 [&status, &requestTemplate]
3153 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3154 status = s;
3155 if (status == common::V1_0::Status::OK) {
3156 const camera_metadata *r =
3157 reinterpret_cast<const camera_metadata_t*>(request.data());
3158 size_t expectedSize = request.size();
3159 int ret = validate_camera_metadata_structure(r, &expectedSize);
3160 if (ret == OK) {
3161 *requestTemplate = clone_camera_metadata(r);
3162 if (*requestTemplate == nullptr) {
3163 ALOGE("%s: Unable to clone camera metadata received from HAL",
3164 __FUNCTION__);
3165 status = common::V1_0::Status::INTERNAL_ERROR;
3166 }
3167 } else {
3168 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3169 status = common::V1_0::Status::INTERNAL_ERROR;
3170 }
3171 }
3172 });
3173 res = CameraProviderManager::mapToStatusT(status);
3174 }
3175 return res;
3176}
3177
3178status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3179 ATRACE_NAME("CameraHal::configureStreams");
3180 if (!valid()) return INVALID_OPERATION;
3181 status_t res = OK;
3182
3183 if (mHal3Device != nullptr) {
3184 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3185 } else {
3186 // Convert stream config to HIDL
3187
3188 StreamConfiguration requestedConfiguration;
3189 requestedConfiguration.streams.resize(config->num_streams);
3190 for (size_t i = 0; i < config->num_streams; i++) {
3191 Stream &dst = requestedConfiguration.streams[i];
3192 camera3_stream_t *src = config->streams[i];
3193
3194 int streamId = Camera3Stream::cast(src)->getId();
3195 StreamType streamType;
3196 switch (src->stream_type) {
3197 case CAMERA3_STREAM_OUTPUT:
3198 streamType = StreamType::OUTPUT;
3199 break;
3200 case CAMERA3_STREAM_INPUT:
3201 streamType = StreamType::INPUT;
3202 break;
3203 default:
3204 ALOGE("%s: Stream %d: Unsupported stream type %d",
3205 __FUNCTION__, streamId, config->streams[i]->stream_type);
3206 return BAD_VALUE;
3207 }
3208 dst.id = streamId;
3209 dst.streamType = streamType;
3210 dst.width = src->width;
3211 dst.height = src->height;
3212 dst.format = mapToPixelFormat(src->format);
3213 dst.usage = mapToConsumerUsage(src->usage);
3214 dst.dataSpace = mapToHidlDataspace(src->data_space);
3215 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3216 }
3217 requestedConfiguration.operationMode = mapToStreamConfigurationMode(
3218 (camera3_stream_configuration_mode_t) config->operation_mode);
3219
3220 // Invoke configureStreams
3221
3222 HalStreamConfiguration finalConfiguration;
3223 common::V1_0::Status status;
3224 mHidlSession->configureStreams(requestedConfiguration,
3225 [&status, &finalConfiguration]
3226 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3227 finalConfiguration = halConfiguration;
3228 status = s;
3229 });
3230 if (status != common::V1_0::Status::OK ) {
3231 return CameraProviderManager::mapToStatusT(status);
3232 }
3233
3234 // And convert output stream configuration from HIDL
3235
3236 for (size_t i = 0; i < config->num_streams; i++) {
3237 camera3_stream_t *dst = config->streams[i];
3238 int streamId = Camera3Stream::cast(dst)->getId();
3239
3240 // Start scan at i, with the assumption that the stream order matches
3241 size_t realIdx = i;
3242 bool found = false;
3243 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3244 if (finalConfiguration.streams[realIdx].id == streamId) {
3245 found = true;
3246 break;
3247 }
3248 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3249 }
3250 if (!found) {
3251 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3252 __FUNCTION__, streamId);
3253 return INVALID_OPERATION;
3254 }
3255 HalStream &src = finalConfiguration.streams[realIdx];
3256
3257 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3258 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3259 if (dst->format != overrideFormat) {
3260 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3261 streamId, dst->format);
3262 }
3263 } else {
3264 // Override allowed with IMPLEMENTATION_DEFINED
3265 dst->format = overrideFormat;
3266 }
3267
3268 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3269 if (src.producerUsage != 0) {
3270 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3271 __FUNCTION__, streamId);
3272 return INVALID_OPERATION;
3273 }
3274 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
3275 } else {
3276 // OUTPUT
3277 if (src.consumerUsage != 0) {
3278 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3279 __FUNCTION__, streamId);
3280 return INVALID_OPERATION;
3281 }
3282 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
3283 }
3284 dst->max_buffers = src.maxBuffers;
3285 }
3286 }
3287 return res;
3288}
3289
3290status_t Camera3Device::HalInterface::processCaptureRequest(
3291 camera3_capture_request_t *request) {
3292 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003293 if (!valid()) return INVALID_OPERATION;
3294 status_t res = OK;
3295
3296 if (mHal3Device != nullptr) {
3297 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3298 } else {
3299 device::V3_2::CaptureRequest captureRequest;
3300 captureRequest.frameNumber = request->frame_number;
3301 std::vector<native_handle_t*> handlesCreated;
3302 // A null request settings maps to a size-0 CameraMetadata
3303 if (request->settings != nullptr) {
3304 captureRequest.settings.setToExternal(
3305 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3306 get_camera_metadata_size(request->settings));
3307 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003308
3309 {
3310 std::lock_guard<std::mutex> lock(mInflightLock);
3311 if (request->input_buffer != nullptr) {
3312 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3313 captureRequest.inputBuffer.streamId = streamId;
3314 captureRequest.inputBuffer.buffer = *(request->input_buffer->buffer);
3315 captureRequest.inputBuffer.status = BufferStatus::OK;
3316 native_handle_t *acquireFence = nullptr;
3317 if (request->input_buffer->acquire_fence != -1) {
3318 acquireFence = native_handle_create(1,0);
3319 acquireFence->data[0] = request->input_buffer->acquire_fence;
3320 handlesCreated.push_back(acquireFence);
3321 }
3322 captureRequest.inputBuffer.acquireFence = acquireFence;
3323 captureRequest.inputBuffer.releaseFence = nullptr;
3324
3325 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3326 request->input_buffer->buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003327 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003328
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003329 captureRequest.outputBuffers.resize(request->num_output_buffers);
3330 for (size_t i = 0; i < request->num_output_buffers; i++) {
3331 const camera3_stream_buffer_t *src = request->output_buffers + i;
3332 StreamBuffer &dst = captureRequest.outputBuffers[i];
3333 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3334 dst.streamId = streamId;
3335 dst.buffer = *(src->buffer);
3336 dst.status = BufferStatus::OK;
3337 native_handle_t *acquireFence = nullptr;
3338 if (src->acquire_fence != -1) {
3339 acquireFence = native_handle_create(1,0);
3340 acquireFence->data[0] = src->acquire_fence;
3341 handlesCreated.push_back(acquireFence);
3342 }
3343 dst.acquireFence = acquireFence;
3344 dst.releaseFence = nullptr;
3345
3346 pushInflightBufferLocked(captureRequest.frameNumber, streamId,
3347 src->buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003348 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003349 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003350 common::V1_0::Status status = mHidlSession->processCaptureRequest(captureRequest);
3351
3352 for (auto& handle : handlesCreated) {
3353 native_handle_delete(handle);
3354 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003355 res = CameraProviderManager::mapToStatusT(status);
3356 }
3357 return res;
3358}
3359
3360status_t Camera3Device::HalInterface::flush() {
3361 ATRACE_NAME("CameraHal::flush");
3362 if (!valid()) return INVALID_OPERATION;
3363 status_t res = OK;
3364
3365 if (mHal3Device != nullptr) {
3366 res = mHal3Device->ops->flush(mHal3Device);
3367 } else {
3368 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3369 }
3370 return res;
3371}
3372
3373status_t Camera3Device::HalInterface::dump(int fd) {
3374 ATRACE_NAME("CameraHal::dump");
3375 if (!valid()) return INVALID_OPERATION;
3376 status_t res = OK;
3377
3378 if (mHal3Device != nullptr) {
3379 mHal3Device->ops->dump(mHal3Device, fd);
3380 } else {
3381 // Handled by CameraProviderManager::dump
3382 }
3383 return res;
3384}
3385
3386status_t Camera3Device::HalInterface::close() {
3387 ATRACE_NAME("CameraHal::close()");
3388 if (!valid()) return INVALID_OPERATION;
3389 status_t res = OK;
3390
3391 if (mHal3Device != nullptr) {
3392 mHal3Device->common.close(&mHal3Device->common);
3393 } else {
3394 mHidlSession->close();
3395 }
3396 return res;
3397}
3398
3399status_t Camera3Device::HalInterface::pushInflightBufferLocked(
3400 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
3401 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3402 mInflightBufferMap[key] = buffer;
3403 return OK;
3404}
3405
3406status_t Camera3Device::HalInterface::popInflightBuffer(
3407 int32_t frameNumber, int32_t streamId, /*out*/ buffer_handle_t **buffer) {
3408 std::lock_guard<std::mutex> lock(mInflightLock);
3409
3410 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3411 auto it = mInflightBufferMap.find(key);
3412 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
3413 *buffer = it->second;
3414 mInflightBufferMap.erase(it);
3415 return OK;
3416}
3417
3418/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003419 * RequestThread inner class methods
3420 */
3421
3422Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003423 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003424 HalInterface* interface,
3425 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003426 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003427 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003428 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003429 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003430 mInterface(interface),
3431 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003432 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003433 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003434 mReconfigured(false),
3435 mDoPause(false),
3436 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003437 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003438 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003439 mCurrentAfTriggerId(0),
3440 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003441 mRepeatingLastFrameNumber(
3442 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003443 mAeLockAvailable(aeLockAvailable),
3444 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003445 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446}
3447
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003448Camera3Device::RequestThread::~RequestThread() {}
3449
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003450void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003451 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003452 Mutex::Autolock l(mRequestLock);
3453 mListener = listener;
3454}
3455
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003456void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003457 Mutex::Autolock l(mRequestLock);
3458 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003459 // Prepare video stream for high speed recording.
3460 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003461}
3462
Jianing Wei90e59c92014-03-12 18:29:36 -07003463status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003464 List<sp<CaptureRequest> > &requests,
3465 /*out*/
3466 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003467 Mutex::Autolock l(mRequestLock);
3468 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3469 ++it) {
3470 mRequestQueue.push_back(*it);
3471 }
3472
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003473 if (lastFrameNumber != NULL) {
3474 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3475 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3476 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3477 *lastFrameNumber);
3478 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003479
Jianing Wei90e59c92014-03-12 18:29:36 -07003480 unpauseForNewRequests();
3481
3482 return OK;
3483}
3484
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003485
3486status_t Camera3Device::RequestThread::queueTrigger(
3487 RequestTrigger trigger[],
3488 size_t count) {
3489
3490 Mutex::Autolock l(mTriggerMutex);
3491 status_t ret;
3492
3493 for (size_t i = 0; i < count; ++i) {
3494 ret = queueTriggerLocked(trigger[i]);
3495
3496 if (ret != OK) {
3497 return ret;
3498 }
3499 }
3500
3501 return OK;
3502}
3503
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003504const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3505 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003506 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003507 if (d != nullptr) return d->mId;
3508 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003509}
3510
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003511status_t Camera3Device::RequestThread::queueTriggerLocked(
3512 RequestTrigger trigger) {
3513
3514 uint32_t tag = trigger.metadataTag;
3515 ssize_t index = mTriggerMap.indexOfKey(tag);
3516
3517 switch (trigger.getTagType()) {
3518 case TYPE_BYTE:
3519 // fall-through
3520 case TYPE_INT32:
3521 break;
3522 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003523 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3524 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003525 return INVALID_OPERATION;
3526 }
3527
3528 /**
3529 * Collect only the latest trigger, since we only have 1 field
3530 * in the request settings per trigger tag, and can't send more than 1
3531 * trigger per request.
3532 */
3533 if (index != NAME_NOT_FOUND) {
3534 mTriggerMap.editValueAt(index) = trigger;
3535 } else {
3536 mTriggerMap.add(tag, trigger);
3537 }
3538
3539 return OK;
3540}
3541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003542status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003543 const RequestList &requests,
3544 /*out*/
3545 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003546 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003547 if (lastFrameNumber != NULL) {
3548 *lastFrameNumber = mRepeatingLastFrameNumber;
3549 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003550 mRepeatingRequests.clear();
3551 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3552 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003553
3554 unpauseForNewRequests();
3555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003556 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003557 return OK;
3558}
3559
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003560bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003561 if (mRepeatingRequests.empty()) {
3562 return false;
3563 }
3564 int32_t requestId = requestIn->mResultExtras.requestId;
3565 const RequestList &repeatRequests = mRepeatingRequests;
3566 // All repeating requests are guaranteed to have same id so only check first quest
3567 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3568 return (firstRequest->mResultExtras.requestId == requestId);
3569}
3570
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003571status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003572 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003573 return clearRepeatingRequestsLocked(lastFrameNumber);
3574
3575}
3576
3577status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003578 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003579 if (lastFrameNumber != NULL) {
3580 *lastFrameNumber = mRepeatingLastFrameNumber;
3581 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003582 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003583 return OK;
3584}
3585
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003586status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003587 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003588 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003589 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003590
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003591 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003592
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003593 // Send errors for all requests pending in the request queue, including
3594 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003595 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003596 if (listener != NULL) {
3597 for (RequestList::iterator it = mRequestQueue.begin();
3598 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003599 // Abort the input buffers for reprocess requests.
3600 if ((*it)->mInputStream != NULL) {
3601 camera3_stream_buffer_t inputBuffer;
3602 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3603 if (res != OK) {
3604 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3605 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3606 } else {
3607 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3608 if (res != OK) {
3609 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3610 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3611 }
3612 }
3613 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003614 // Set the frame number this request would have had, if it
3615 // had been submitted; this frame number will not be reused.
3616 // The requestId and burstId fields were set when the request was
3617 // submitted originally (in convertMetadataListToRequestListLocked)
3618 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003619 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003620 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003621 }
3622 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003623 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003624
3625 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003626 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003627 if (lastFrameNumber != NULL) {
3628 *lastFrameNumber = mRepeatingLastFrameNumber;
3629 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003630 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003631 return OK;
3632}
3633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003634status_t Camera3Device::RequestThread::flush() {
3635 ATRACE_CALL();
3636 Mutex::Autolock l(mFlushLock);
3637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003638 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3639 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 }
3641
3642 return -ENOTSUP;
3643}
3644
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003645void Camera3Device::RequestThread::setPaused(bool paused) {
3646 Mutex::Autolock l(mPauseLock);
3647 mDoPause = paused;
3648 mDoPauseSignal.signal();
3649}
3650
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003651status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3652 int32_t requestId, nsecs_t timeout) {
3653 Mutex::Autolock l(mLatestRequestMutex);
3654 status_t res;
3655 while (mLatestRequestId != requestId) {
3656 nsecs_t startTime = systemTime();
3657
3658 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3659 if (res != OK) return res;
3660
3661 timeout -= (systemTime() - startTime);
3662 }
3663
3664 return OK;
3665}
3666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003667void Camera3Device::RequestThread::requestExit() {
3668 // Call parent to set up shutdown
3669 Thread::requestExit();
3670 // The exit from any possible waits
3671 mDoPauseSignal.signal();
3672 mRequestSignal.signal();
3673}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003674
Chien-Yu Chend196d612015-06-22 19:49:01 -07003675
3676/**
3677 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3678 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3679 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3680 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3681 * request.
3682 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003683void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003684 request->mAeTriggerCancelOverride.applyAeLock = false;
3685 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3686
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003687 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003688 return;
3689 }
3690
3691 camera_metadata_entry_t aePrecaptureTrigger =
3692 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3693 if (aePrecaptureTrigger.count > 0 &&
3694 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3695 // Always override CANCEL to IDLE
3696 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3697 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3698 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3699 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3700 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3701
3702 if (mAeLockAvailable == true) {
3703 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3704 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3705 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3706 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3707 request->mAeTriggerCancelOverride.applyAeLock = true;
3708 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3709 }
3710 }
3711 }
3712}
3713
3714/**
3715 * Override result metadata for cancelling AE precapture trigger applied in
3716 * handleAePrecaptureCancelRequest().
3717 */
3718void Camera3Device::overrideResultForPrecaptureCancel(
3719 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3720 if (aeTriggerCancelOverride.applyAeLock) {
3721 // Only devices <= v3.2 should have this override
3722 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3723 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3724 }
3725
3726 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3727 // Only devices <= v3.2 should have this override
3728 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3729 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3730 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3731 }
3732}
3733
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003734void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003735 bool surfaceAbandoned = false;
3736 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003737 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003738 {
3739 Mutex::Autolock l(mRequestLock);
3740 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3741 // repeating requests.
3742 for (const auto& request : mRepeatingRequests) {
3743 for (const auto& s : request->mOutputStreams) {
3744 if (s->isAbandoned()) {
3745 surfaceAbandoned = true;
3746 clearRepeatingRequestsLocked(&lastFrameNumber);
3747 break;
3748 }
3749 }
3750 if (surfaceAbandoned) {
3751 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003752 }
3753 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003754 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003755 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003756
3757 if (listener != NULL && surfaceAbandoned) {
3758 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003759 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003760}
3761
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003762bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003763 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003764 status_t res;
3765
3766 // Handle paused state.
3767 if (waitIfPaused()) {
3768 return true;
3769 }
3770
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003771 // Wait for the next batch of requests.
3772 waitForNextRequestBatch();
3773 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003774 return true;
3775 }
3776
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003777 // Get the latest request ID, if any
3778 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003779 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003780 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003781 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003782 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003783 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003784 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3785 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003786 }
3787
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003788 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003789 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003790 if (res == TIMED_OUT) {
3791 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003792 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003793 // Check if any stream is abandoned.
3794 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003795 return true;
3796 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003797 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003798 return false;
3799 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003800
Zhijun Hecc27e112013-10-03 16:12:43 -07003801 // Inform waitUntilRequestProcessed thread of a new request ID
3802 {
3803 Mutex::Autolock al(mLatestRequestMutex);
3804
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003805 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003806 mLatestRequestSignal.signal();
3807 }
3808
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003809 // Submit a batch of requests to HAL.
3810 // Use flush lock only when submitting multilple requests in a batch.
3811 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3812 // which may take a long time to finish so synchronizing flush() and
3813 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3814 // For now, only synchronize for high speed recording and we should figure something out for
3815 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003816 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003817
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003818 if (useFlushLock) {
3819 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003820 }
3821
Zhijun Hef0645c12016-08-02 00:58:11 -07003822 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003823 mNextRequests.size());
3824 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003825 // Submit request and block until ready for next one
3826 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003827 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003828
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003829 if (res != OK) {
3830 // Should only get a failure here for malformed requests or device-level
3831 // errors, so consider all errors fatal. Bad metadata failures should
3832 // come through notify.
3833 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3834 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3835 res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003836 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003837 if (useFlushLock) {
3838 mFlushLock.unlock();
3839 }
3840 return false;
3841 }
3842
3843 // Mark that the request has be submitted successfully.
3844 nextRequest.submitted = true;
3845
3846 // Update the latest request sent to HAL
3847 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3848 Mutex::Autolock al(mLatestRequestMutex);
3849
3850 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3851 mLatestRequest.acquire(cloned);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003852
3853 sp<Camera3Device> parent = mParent.promote();
3854 if (parent != NULL) {
3855 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3856 0, mLatestRequest);
3857 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003858 }
3859
3860 if (nextRequest.halRequest.settings != NULL) {
3861 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3862 }
3863
3864 // Remove any previously queued triggers (after unlock)
3865 res = removeTriggers(mPrevRequest);
3866 if (res != OK) {
3867 SET_ERR("RequestThread: Unable to remove triggers "
3868 "(capture request %d, HAL device: %s (%d)",
3869 nextRequest.halRequest.frame_number, strerror(-res), res);
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003870 cleanUpFailedRequests(/*sendRequestError*/ false);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003871 if (useFlushLock) {
3872 mFlushLock.unlock();
3873 }
3874 return false;
3875 }
Igor Murashkin1e479c02013-09-06 16:55:14 -07003876 }
3877
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003878 if (useFlushLock) {
3879 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003880 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003881
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003882 // Unset as current request
3883 {
3884 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003885 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003886 }
3887
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003888 return true;
3889}
3890
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003891status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003892 ATRACE_CALL();
3893
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003894 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003895 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3896 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3897 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3898
3899 // Prepare a request to HAL
3900 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3901
3902 // Insert any queued triggers (before metadata is locked)
3903 status_t res = insertTriggers(captureRequest);
3904
3905 if (res < 0) {
3906 SET_ERR("RequestThread: Unable to insert triggers "
3907 "(capture request %d, HAL device: %s (%d)",
3908 halRequest->frame_number, strerror(-res), res);
3909 return INVALID_OPERATION;
3910 }
3911 int triggerCount = res;
3912 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3913 mPrevTriggers = triggerCount;
3914
3915 // If the request is the same as last, or we had triggers last time
3916 if (mPrevRequest != captureRequest || triggersMixedIn) {
3917 /**
3918 * HAL workaround:
3919 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3920 */
3921 res = addDummyTriggerIds(captureRequest);
3922 if (res != OK) {
3923 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3924 "(capture request %d, HAL device: %s (%d)",
3925 halRequest->frame_number, strerror(-res), res);
3926 return INVALID_OPERATION;
3927 }
3928
3929 /**
3930 * The request should be presorted so accesses in HAL
3931 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3932 */
3933 captureRequest->mSettings.sort();
3934 halRequest->settings = captureRequest->mSettings.getAndLock();
3935 mPrevRequest = captureRequest;
3936 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3937
3938 IF_ALOGV() {
3939 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3940 find_camera_metadata_ro_entry(
3941 halRequest->settings,
3942 ANDROID_CONTROL_AF_TRIGGER,
3943 &e
3944 );
3945 if (e.count > 0) {
3946 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3947 __FUNCTION__,
3948 halRequest->frame_number,
3949 e.data.u8[0]);
3950 }
3951 }
3952 } else {
3953 // leave request.settings NULL to indicate 'reuse latest given'
3954 ALOGVV("%s: Request settings are REUSED",
3955 __FUNCTION__);
3956 }
3957
3958 uint32_t totalNumBuffers = 0;
3959
3960 // Fill in buffers
3961 if (captureRequest->mInputStream != NULL) {
3962 halRequest->input_buffer = &captureRequest->mInputBuffer;
3963 totalNumBuffers += 1;
3964 } else {
3965 halRequest->input_buffer = NULL;
3966 }
3967
3968 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3969 captureRequest->mOutputStreams.size());
3970 halRequest->output_buffers = outputBuffers->array();
3971 for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003972 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(i);
3973
3974 // Prepare video buffers for high speed recording on the first video request.
3975 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3976 // Only try to prepare video stream on the first video request.
3977 mPrepareVideoStream = false;
3978
3979 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3980 while (res == NOT_ENOUGH_DATA) {
3981 res = outputStream->prepareNextBuffer();
3982 }
3983 if (res != OK) {
3984 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3985 __FUNCTION__, strerror(-res), res);
3986 outputStream->cancelPrepare();
3987 }
3988 }
3989
3990 res = outputStream->getBuffer(&outputBuffers->editItemAt(i));
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003991 if (res != OK) {
3992 // Can't get output buffer from gralloc queue - this could be due to
3993 // abandoned queue or other consumer misbehavior, so not a fatal
3994 // error
3995 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3996 " %s (%d)", strerror(-res), res);
3997
3998 return TIMED_OUT;
3999 }
4000 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004001
4002 res = outputStream->notifyRequestedSurfaces(halRequest->frame_number,
4003 captureRequest->mOutputSurfaces[i]);
4004 if (res != OK) {
4005 ALOGE("RequestThread: Cannot register output surfaces: %s (%d)",
4006 strerror(-res), res);
4007 return INVALID_OPERATION;
4008 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004009 }
4010 totalNumBuffers += halRequest->num_output_buffers;
4011
4012 // Log request in the in-flight queue
4013 sp<Camera3Device> parent = mParent.promote();
4014 if (parent == NULL) {
4015 // Should not happen, and nowhere to send errors to, so just log it
4016 CLOGE("RequestThread: Parent is gone");
4017 return INVALID_OPERATION;
4018 }
4019 res = parent->registerInFlight(halRequest->frame_number,
4020 totalNumBuffers, captureRequest->mResultExtras,
4021 /*hasInput*/halRequest->input_buffer != NULL,
4022 captureRequest->mAeTriggerCancelOverride);
4023 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4024 ", burstId = %" PRId32 ".",
4025 __FUNCTION__,
4026 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4027 captureRequest->mResultExtras.burstId);
4028 if (res != OK) {
4029 SET_ERR("RequestThread: Unable to register new in-flight request:"
4030 " %s (%d)", strerror(-res), res);
4031 return INVALID_OPERATION;
4032 }
4033 }
4034
4035 return OK;
4036}
4037
Igor Murashkin1e479c02013-09-06 16:55:14 -07004038CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4039 Mutex::Autolock al(mLatestRequestMutex);
4040
4041 ALOGV("RequestThread::%s", __FUNCTION__);
4042
4043 return mLatestRequest;
4044}
4045
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004046bool Camera3Device::RequestThread::isStreamPending(
4047 sp<Camera3StreamInterface>& stream) {
4048 Mutex::Autolock l(mRequestLock);
4049
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004050 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004051 if (!nextRequest.submitted) {
4052 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4053 if (stream == s) return true;
4054 }
4055 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004056 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004057 }
4058
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004059 for (const auto& request : mRequestQueue) {
4060 for (const auto& s : request->mOutputStreams) {
4061 if (stream == s) return true;
4062 }
4063 if (stream == request->mInputStream) return true;
4064 }
4065
4066 for (const auto& request : mRepeatingRequests) {
4067 for (const auto& s : request->mOutputStreams) {
4068 if (stream == s) return true;
4069 }
4070 if (stream == request->mInputStream) return true;
4071 }
4072
4073 return false;
4074}
Jianing Weicb0652e2014-03-12 18:29:36 -07004075
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004076void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4077 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004078 return;
4079 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004080
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004081 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004082 // Skip the ones that have been submitted successfully.
4083 if (nextRequest.submitted) {
4084 continue;
4085 }
4086
4087 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4088 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4089 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4090
4091 if (halRequest->settings != NULL) {
4092 captureRequest->mSettings.unlock(halRequest->settings);
4093 }
4094
4095 if (captureRequest->mInputStream != NULL) {
4096 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4097 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4098 }
4099
4100 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4101 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4102 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4103 }
4104
4105 if (sendRequestError) {
4106 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004107 sp<NotificationListener> listener = mListener.promote();
4108 if (listener != NULL) {
4109 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004110 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004111 captureRequest->mResultExtras);
4112 }
4113 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004114
4115 // Remove yet-to-be submitted inflight request from inflightMap
4116 {
4117 sp<Camera3Device> parent = mParent.promote();
4118 if (parent != NULL) {
4119 Mutex::Autolock l(parent->mInFlightLock);
4120 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4121 if (idx >= 0) {
4122 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4123 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4124 parent->removeInFlightMapEntryLocked(idx);
4125 }
4126 }
4127 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004128 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004129
4130 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004132}
4133
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004134void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004135 // Optimized a bit for the simple steady-state case (single repeating
4136 // request), to avoid putting that request in the queue temporarily.
4137 Mutex::Autolock l(mRequestLock);
4138
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004139 assert(mNextRequests.empty());
4140
4141 NextRequest nextRequest;
4142 nextRequest.captureRequest = waitForNextRequestLocked();
4143 if (nextRequest.captureRequest == nullptr) {
4144 return;
4145 }
4146
4147 nextRequest.halRequest = camera3_capture_request_t();
4148 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004149 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004150
4151 // Wait for additional requests
4152 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4153
4154 for (size_t i = 1; i < batchSize; i++) {
4155 NextRequest additionalRequest;
4156 additionalRequest.captureRequest = waitForNextRequestLocked();
4157 if (additionalRequest.captureRequest == nullptr) {
4158 break;
4159 }
4160
4161 additionalRequest.halRequest = camera3_capture_request_t();
4162 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004163 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004164 }
4165
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004166 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004167 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004168 mNextRequests.size(), batchSize);
4169 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004170 }
4171
4172 return;
4173}
4174
4175sp<Camera3Device::CaptureRequest>
4176 Camera3Device::RequestThread::waitForNextRequestLocked() {
4177 status_t res;
4178 sp<CaptureRequest> nextRequest;
4179
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 while (mRequestQueue.empty()) {
4181 if (!mRepeatingRequests.empty()) {
4182 // Always atomically enqueue all requests in a repeating request
4183 // list. Guarantees a complete in-sequence set of captures to
4184 // application.
4185 const RequestList &requests = mRepeatingRequests;
4186 RequestList::const_iterator firstRequest =
4187 requests.begin();
4188 nextRequest = *firstRequest;
4189 mRequestQueue.insert(mRequestQueue.end(),
4190 ++firstRequest,
4191 requests.end());
4192 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004193
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004194 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004195
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196 break;
4197 }
4198
4199 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4200
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004201 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4202 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004203 Mutex::Autolock pl(mPauseLock);
4204 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004205 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004206 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004207 // 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 }
4213 // Stop waiting for now and let thread management happen
4214 return NULL;
4215 }
4216 }
4217
4218 if (nextRequest == NULL) {
4219 // Don't have a repeating request already in hand, so queue
4220 // must have an entry now.
4221 RequestList::iterator firstRequest =
4222 mRequestQueue.begin();
4223 nextRequest = *firstRequest;
4224 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004225 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4226 sp<NotificationListener> listener = mListener.promote();
4227 if (listener != NULL) {
4228 listener->notifyRequestQueueEmpty();
4229 }
4230 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004231 }
4232
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004233 // In case we've been unpaused by setPaused clearing mDoPause, need to
4234 // update internal pause state (capture/setRepeatingRequest unpause
4235 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004236 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004237 if (mPaused) {
4238 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4239 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4240 if (statusTracker != 0) {
4241 statusTracker->markComponentActive(mStatusId);
4242 }
4243 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004244 mPaused = false;
4245
4246 // Check if we've reconfigured since last time, and reset the preview
4247 // request if so. Can't use 'NULL request == repeat' across configure calls.
4248 if (mReconfigured) {
4249 mPrevRequest.clear();
4250 mReconfigured = false;
4251 }
4252
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004253 if (nextRequest != NULL) {
4254 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004255 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4256 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004257
4258 // Since RequestThread::clear() removes buffers from the input stream,
4259 // get the right buffer here before unlocking mRequestLock
4260 if (nextRequest->mInputStream != NULL) {
4261 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4262 if (res != OK) {
4263 // Can't get input buffer from gralloc queue - this could be due to
4264 // disconnected queue or other producer misbehavior, so not a fatal
4265 // error
4266 ALOGE("%s: Can't get input buffer, skipping request:"
4267 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004268
4269 sp<NotificationListener> listener = mListener.promote();
4270 if (listener != NULL) {
4271 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004272 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004273 nextRequest->mResultExtras);
4274 }
4275 return NULL;
4276 }
4277 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004278 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004279
4280 handleAePrecaptureCancelRequest(nextRequest);
4281
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004282 return nextRequest;
4283}
4284
4285bool Camera3Device::RequestThread::waitIfPaused() {
4286 status_t res;
4287 Mutex::Autolock l(mPauseLock);
4288 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004289 if (mPaused == false) {
4290 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004291 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4292 // Let the tracker know
4293 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4294 if (statusTracker != 0) {
4295 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4296 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004298
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004300 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 return true;
4302 }
4303 }
4304 // We don't set mPaused to false here, because waitForNextRequest needs
4305 // to further manage the paused state in case of starvation.
4306 return false;
4307}
4308
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004309void Camera3Device::RequestThread::unpauseForNewRequests() {
4310 // With work to do, mark thread as unpaused.
4311 // If paused by request (setPaused), don't resume, to avoid
4312 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004313 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004314 Mutex::Autolock p(mPauseLock);
4315 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004316 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4317 if (mPaused) {
4318 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4319 if (statusTracker != 0) {
4320 statusTracker->markComponentActive(mStatusId);
4321 }
4322 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004323 mPaused = false;
4324 }
4325}
4326
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004327void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4328 sp<Camera3Device> parent = mParent.promote();
4329 if (parent != NULL) {
4330 va_list args;
4331 va_start(args, fmt);
4332
4333 parent->setErrorStateV(fmt, args);
4334
4335 va_end(args);
4336 }
4337}
4338
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004339status_t Camera3Device::RequestThread::insertTriggers(
4340 const sp<CaptureRequest> &request) {
4341
4342 Mutex::Autolock al(mTriggerMutex);
4343
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004344 sp<Camera3Device> parent = mParent.promote();
4345 if (parent == NULL) {
4346 CLOGE("RequestThread: Parent is gone");
4347 return DEAD_OBJECT;
4348 }
4349
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004350 CameraMetadata &metadata = request->mSettings;
4351 size_t count = mTriggerMap.size();
4352
4353 for (size_t i = 0; i < count; ++i) {
4354 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004355 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004356
4357 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4358 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4359 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004360 if (isAeTrigger) {
4361 request->mResultExtras.precaptureTriggerId = triggerId;
4362 mCurrentPreCaptureTriggerId = triggerId;
4363 } else {
4364 request->mResultExtras.afTriggerId = triggerId;
4365 mCurrentAfTriggerId = triggerId;
4366 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004367 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4368 continue; // Trigger ID tag is deprecated since device HAL 3.2
4369 }
4370 }
4371
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004372 camera_metadata_entry entry = metadata.find(tag);
4373
4374 if (entry.count > 0) {
4375 /**
4376 * Already has an entry for this trigger in the request.
4377 * Rewrite it with our requested trigger value.
4378 */
4379 RequestTrigger oldTrigger = trigger;
4380
4381 oldTrigger.entryValue = entry.data.u8[0];
4382
4383 mTriggerReplacedMap.add(tag, oldTrigger);
4384 } else {
4385 /**
4386 * More typical, no trigger entry, so we just add it
4387 */
4388 mTriggerRemovedMap.add(tag, trigger);
4389 }
4390
4391 status_t res;
4392
4393 switch (trigger.getTagType()) {
4394 case TYPE_BYTE: {
4395 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4396 res = metadata.update(tag,
4397 &entryValue,
4398 /*count*/1);
4399 break;
4400 }
4401 case TYPE_INT32:
4402 res = metadata.update(tag,
4403 &trigger.entryValue,
4404 /*count*/1);
4405 break;
4406 default:
4407 ALOGE("%s: Type not supported: 0x%x",
4408 __FUNCTION__,
4409 trigger.getTagType());
4410 return INVALID_OPERATION;
4411 }
4412
4413 if (res != OK) {
4414 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4415 ", value %d", __FUNCTION__, trigger.getTagName(),
4416 trigger.entryValue);
4417 return res;
4418 }
4419
4420 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4421 trigger.getTagName(),
4422 trigger.entryValue);
4423 }
4424
4425 mTriggerMap.clear();
4426
4427 return count;
4428}
4429
4430status_t Camera3Device::RequestThread::removeTriggers(
4431 const sp<CaptureRequest> &request) {
4432 Mutex::Autolock al(mTriggerMutex);
4433
4434 CameraMetadata &metadata = request->mSettings;
4435
4436 /**
4437 * Replace all old entries with their old values.
4438 */
4439 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4440 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4441
4442 status_t res;
4443
4444 uint32_t tag = trigger.metadataTag;
4445 switch (trigger.getTagType()) {
4446 case TYPE_BYTE: {
4447 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4448 res = metadata.update(tag,
4449 &entryValue,
4450 /*count*/1);
4451 break;
4452 }
4453 case TYPE_INT32:
4454 res = metadata.update(tag,
4455 &trigger.entryValue,
4456 /*count*/1);
4457 break;
4458 default:
4459 ALOGE("%s: Type not supported: 0x%x",
4460 __FUNCTION__,
4461 trigger.getTagType());
4462 return INVALID_OPERATION;
4463 }
4464
4465 if (res != OK) {
4466 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4467 ", trigger value %d", __FUNCTION__,
4468 trigger.getTagName(), trigger.entryValue);
4469 return res;
4470 }
4471 }
4472 mTriggerReplacedMap.clear();
4473
4474 /**
4475 * Remove all new entries.
4476 */
4477 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4478 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4479 status_t res = metadata.erase(trigger.metadataTag);
4480
4481 if (res != OK) {
4482 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4483 ", trigger value %d", __FUNCTION__,
4484 trigger.getTagName(), trigger.entryValue);
4485 return res;
4486 }
4487 }
4488 mTriggerRemovedMap.clear();
4489
4490 return OK;
4491}
4492
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004493status_t Camera3Device::RequestThread::addDummyTriggerIds(
4494 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004495 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004496 static const int32_t dummyTriggerId = 1;
4497 status_t res;
4498
4499 CameraMetadata &metadata = request->mSettings;
4500
4501 // If AF trigger is active, insert a dummy AF trigger ID if none already
4502 // exists
4503 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4504 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4505 if (afTrigger.count > 0 &&
4506 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4507 afId.count == 0) {
4508 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4509 if (res != OK) return res;
4510 }
4511
4512 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4513 // if none already exists
4514 camera_metadata_entry pcTrigger =
4515 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4516 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4517 if (pcTrigger.count > 0 &&
4518 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4519 pcId.count == 0) {
4520 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4521 &dummyTriggerId, 1);
4522 if (res != OK) return res;
4523 }
4524
4525 return OK;
4526}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004527
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004528/**
4529 * PreparerThread inner class methods
4530 */
4531
4532Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004533 Thread(/*canCallJava*/false), mListener(nullptr),
4534 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004535}
4536
4537Camera3Device::PreparerThread::~PreparerThread() {
4538 Thread::requestExitAndWait();
4539 if (mCurrentStream != nullptr) {
4540 mCurrentStream->cancelPrepare();
4541 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4542 mCurrentStream.clear();
4543 }
4544 clear();
4545}
4546
Ruben Brunkc78ac262015-08-13 17:58:46 -07004547status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004548 status_t res;
4549
4550 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004551 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004552
Ruben Brunkc78ac262015-08-13 17:58:46 -07004553 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004554 if (res == OK) {
4555 // No preparation needed, fire listener right off
4556 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004557 if (listener != NULL) {
4558 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004559 }
4560 return OK;
4561 } else if (res != NOT_ENOUGH_DATA) {
4562 return res;
4563 }
4564
4565 // Need to prepare, start up thread if necessary
4566 if (!mActive) {
4567 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4568 // isn't running
4569 Thread::requestExitAndWait();
4570 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4571 if (res != OK) {
4572 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004573 if (listener != NULL) {
4574 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004575 }
4576 return res;
4577 }
4578 mCancelNow = false;
4579 mActive = true;
4580 ALOGV("%s: Preparer stream started", __FUNCTION__);
4581 }
4582
4583 // queue up the work
4584 mPendingStreams.push_back(stream);
4585 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4586
4587 return OK;
4588}
4589
4590status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004591 Mutex::Autolock l(mLock);
4592
4593 for (const auto& stream : mPendingStreams) {
4594 stream->cancelPrepare();
4595 }
4596 mPendingStreams.clear();
4597 mCancelNow = true;
4598
4599 return OK;
4600}
4601
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004602void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004603 Mutex::Autolock l(mLock);
4604 mListener = listener;
4605}
4606
4607bool Camera3Device::PreparerThread::threadLoop() {
4608 status_t res;
4609 {
4610 Mutex::Autolock l(mLock);
4611 if (mCurrentStream == nullptr) {
4612 // End thread if done with work
4613 if (mPendingStreams.empty()) {
4614 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4615 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4616 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4617 mActive = false;
4618 return false;
4619 }
4620
4621 // Get next stream to prepare
4622 auto it = mPendingStreams.begin();
4623 mCurrentStream = *it;
4624 mPendingStreams.erase(it);
4625 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4626 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4627 } else if (mCancelNow) {
4628 mCurrentStream->cancelPrepare();
4629 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4630 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4631 mCurrentStream.clear();
4632 mCancelNow = false;
4633 return true;
4634 }
4635 }
4636
4637 res = mCurrentStream->prepareNextBuffer();
4638 if (res == NOT_ENOUGH_DATA) return true;
4639 if (res != OK) {
4640 // Something bad happened; try to recover by cancelling prepare and
4641 // signalling listener anyway
4642 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4643 mCurrentStream->getId(), res, strerror(-res));
4644 mCurrentStream->cancelPrepare();
4645 }
4646
4647 // This stream has finished, notify listener
4648 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004649 sp<NotificationListener> listener = mListener.promote();
4650 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004651 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4652 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004653 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004654 }
4655
4656 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4657 mCurrentStream.clear();
4658
4659 return true;
4660}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004661
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004662/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004663 * Static callback forwarding methods from HAL to instance
4664 */
4665
4666void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4667 const camera3_capture_result *result) {
4668 Camera3Device *d =
4669 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004670
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004671 d->processCaptureResult(result);
4672}
4673
4674void Camera3Device::sNotify(const camera3_callback_ops *cb,
4675 const camera3_notify_msg *msg) {
4676 Camera3Device *d =
4677 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4678 d->notify(msg);
4679}
4680
4681}; // namespace android