blob: c35dab6abd926c114aa16de4850b1a74f08323a0 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000077 mListener(NULL),
78 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080079{
80 ATRACE_CALL();
81 camera3_callback_ops::notify = &sNotify;
82 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080083 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084}
85
86Camera3Device::~Camera3Device()
87{
88 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080089 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080090 disconnect();
91}
92
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080094 return mId;
95}
96
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080097/**
98 * CameraDeviceBase interface
99 */
100
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800101status_t Camera3Device::initialize(CameraModule *module)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102{
103 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700104 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800105 Mutex::Autolock l(mLock);
106
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Initializing device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800108 if (mStatus != STATUS_UNINITIALIZED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700109 CLOGE("Already initialized!");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110 return INVALID_OPERATION;
111 }
112
113 /** Open HAL device */
114
115 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800116
117 camera3_device_t *device;
118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119 ATRACE_BEGIN("CameraHal::open");
120 res = module->open(mId.string(),
Chien-Yu Chend231fd62015-02-25 16:04:22 -0800121 reinterpret_cast<hw_device_t**>(&device));
Zhijun He213ce792013-11-19 08:45:15 -0800122 ATRACE_END();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800123
124 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700125 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800126 return res;
127 }
128
129 /** Cross-check device version */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700131 SET_ERR_L("Could not open camera: "
Zhijun He95dd5ba2014-03-26 18:18:00 -0700132 "Camera device should be at least %x, reports %x instead",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 CAMERA_DEVICE_API_VERSION_3_2,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800134 device->common.version);
135 device->common.close(&device->common);
136 return BAD_VALUE;
137 }
138
139 camera_info info;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800140 res = module->getCameraInfo(atoi(mId), &info);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800141 if (res != OK) return res;
142
143 if (info.device_version != device->common.version) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700144 SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
145 " and device version (%x).",
Zhijun He95dd5ba2014-03-26 18:18:00 -0700146 info.device_version, device->common.version);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800147 device->common.close(&device->common);
148 return BAD_VALUE;
149 }
150
151 /** Initialize device with callback functions */
152
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800153 ATRACE_BEGIN("CameraHal::initialize");
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800154 res = device->ops->initialize(device, this);
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -0700155 ATRACE_END();
156
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800157 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700158 SET_ERR_L("Unable to initialize HAL device: %s (%d)",
159 strerror(-res), res);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800160 device->common.close(&device->common);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800161 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800162 }
163
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800164 /** Everything is good to go */
165
166 mDeviceVersion = device->common.version;
167 mDeviceInfo = info.static_camera_characteristics;
168 mInterface = std::make_unique<HalInterface>(device);
169
170 return initializeCommonLocked();
171}
172
173status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
174 ATRACE_CALL();
175 Mutex::Autolock il(mInterfaceLock);
176 Mutex::Autolock l(mLock);
177
178 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
179 if (mStatus != STATUS_UNINITIALIZED) {
180 CLOGE("Already initialized!");
181 return INVALID_OPERATION;
182 }
183 if (manager == nullptr) return INVALID_OPERATION;
184
185 sp<ICameraDeviceSession> session;
186 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800187 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 /*out*/ &session);
189 ATRACE_END();
190 if (res != OK) {
191 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
192 return res;
193 }
194
Steven Moreland5ff9c912017-03-09 23:13:00 -0800195 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800196 if (res != OK) {
197 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
198 session->close();
199 return res;
200 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800201
202 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
203 // for now use 3_4 to keep legacy devices working
204 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800205 mInterface = std::make_unique<HalInterface>(session);
Emilian Peev71c73a22017-03-21 16:35:51 +0000206 std::string providerType;
207 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800208
209 return initializeCommonLocked();
210}
211
212status_t Camera3Device::initializeCommonLocked() {
213
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700214 /** Start up status tracker thread */
215 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800216 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700217 if (res != OK) {
218 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
219 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800220 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700221 mStatusTracker.clear();
222 return res;
223 }
224
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700225 /** Register in-flight map to the status tracker */
226 mInFlightStatusId = mStatusTracker->addComponent();
227
Zhijun He125684a2015-12-26 15:07:30 -0800228 /** Create buffer manager */
229 mBufferManager = new Camera3BufferManager();
230
Emilian Peev71c73a22017-03-21 16:35:51 +0000231 mTagMonitor.initialize(mVendorTagId);
232
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700233 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
235 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
236 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700237 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
238 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
239 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800240
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700241 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800242 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
243 aeLockAvailable);
244 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800245 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700246 SET_ERR_L("Unable to start request queue thread: %s (%d)",
247 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800249 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800250 return res;
251 }
252
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700253 mPreparerThread = new PreparerThread();
254
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700255 // Determine whether we need to derive sensitivity boost values for older devices.
256 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
257 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800258 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700259 mDerivePostRawSensKey = true;
260 }
261
Ruben Brunk183f0562015-08-12 12:55:02 -0700262 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800263 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700264 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700265 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700266 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800267
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800268 // Measure the clock domain offset between camera and video/hw_composer
269 camera_metadata_entry timestampSource =
270 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
271 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
272 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
273 mTimestampOffset = getMonoToBoottimeOffset();
274 }
275
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700276 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700277 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
278 camera_metadata_entry partialResultsCount =
279 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
280 if (partialResultsCount.count > 0) {
281 mNumPartialResults = partialResultsCount.data.i32[0];
282 mUsePartialResult = (mNumPartialResults > 1);
283 }
284 } else {
285 camera_metadata_entry partialResultsQuirk =
286 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
287 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
288 mUsePartialResult = true;
289 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700290 }
291
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700292 camera_metadata_entry configs =
293 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
294 for (uint32_t i = 0; i < configs.count; i += 4) {
295 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
296 configs.data.i32[i + 3] ==
297 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
298 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
299 configs.data.i32[i + 2]));
300 }
301 }
302
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800303 return OK;
304}
305
306status_t Camera3Device::disconnect() {
307 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800309
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700310 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800311
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700312 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800313
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 {
315 Mutex::Autolock l(mLock);
316 if (mStatus == STATUS_UNINITIALIZED) return res;
317
318 if (mStatus == STATUS_ACTIVE ||
319 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
320 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700321 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700322 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700323 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 } else {
325 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
326 if (res != OK) {
327 SET_ERR_L("Timeout waiting for HAL to drain");
328 // Continue to close device even in case of error
329 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700330 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800331 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800332
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700333 if (mStatus == STATUS_ERROR) {
334 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700335 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700336
337 if (mStatusTracker != NULL) {
338 mStatusTracker->requestExit();
339 }
340
341 if (mRequestThread != NULL) {
342 mRequestThread->requestExit();
343 }
344
345 mOutputStreams.clear();
346 mInputStream.clear();
347 }
348
349 // Joining done without holding mLock, otherwise deadlocks may ensue
350 // as the threads try to access parent state
351 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
352 // HAL may be in a bad state, so waiting for request thread
353 // (which may be stuck in the HAL processCaptureRequest call)
354 // could be dangerous.
355 mRequestThread->join();
356 }
357
358 if (mStatusTracker != NULL) {
359 mStatusTracker->join();
360 }
361
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800362 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363 {
364 Mutex::Autolock l(mLock);
365
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800366 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800368 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800369
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800370 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700371 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800372
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700373 // Call close without internal mutex held, as the HAL close may need to
374 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800375 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700376
377 {
378 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800379 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700380 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800382
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700383 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700384 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800385}
386
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700387// For dumping/debugging only -
388// try to acquire a lock a few times, eventually give up to proceed with
389// debug/dump operations
390bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
391 bool gotLock = false;
392 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
393 if (lock.tryLock() == NO_ERROR) {
394 gotLock = true;
395 break;
396 } else {
397 usleep(kDumpSleepDuration);
398 }
399 }
400 return gotLock;
401}
402
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700403Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
404 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
405 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
406 const int STREAM_CONFIGURATION_SIZE = 4;
407 const int STREAM_FORMAT_OFFSET = 0;
408 const int STREAM_WIDTH_OFFSET = 1;
409 const int STREAM_HEIGHT_OFFSET = 2;
410 const int STREAM_IS_INPUT_OFFSET = 3;
411 camera_metadata_ro_entry_t availableStreamConfigs =
412 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
413 if (availableStreamConfigs.count == 0 ||
414 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
415 return Size(0, 0);
416 }
417
418 // Get max jpeg size (area-wise).
419 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
420 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
421 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
422 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
423 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
424 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
425 && format == HAL_PIXEL_FORMAT_BLOB &&
426 (width * height > maxJpegWidth * maxJpegHeight)) {
427 maxJpegWidth = width;
428 maxJpegHeight = height;
429 }
430 }
431 } else {
432 camera_metadata_ro_entry availableJpegSizes =
433 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
434 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
435 return Size(0, 0);
436 }
437
438 // Get max jpeg size (area-wise).
439 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
440 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
441 > (maxJpegWidth * maxJpegHeight)) {
442 maxJpegWidth = availableJpegSizes.data.i32[i];
443 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
444 }
445 }
446 }
447 return Size(maxJpegWidth, maxJpegHeight);
448}
449
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800450nsecs_t Camera3Device::getMonoToBoottimeOffset() {
451 // try three times to get the clock offset, choose the one
452 // with the minimum gap in measurements.
453 const int tries = 3;
454 nsecs_t bestGap, measured;
455 for (int i = 0; i < tries; ++i) {
456 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
457 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
458 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
459 const nsecs_t gap = tmono2 - tmono;
460 if (i == 0 || gap < bestGap) {
461 bestGap = gap;
462 measured = tbase - ((tmono + tmono2) >> 1);
463 }
464 }
465 return measured;
466}
467
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700468/**
469 * Map Android N dataspace definitions back to Android M definitions, for
470 * use with HALv3.3 or older.
471 *
472 * Only map where correspondences exist, and otherwise preserve the value.
473 */
474android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
475 switch (dataSpace) {
476 case HAL_DATASPACE_V0_SRGB_LINEAR:
477 return HAL_DATASPACE_SRGB_LINEAR;
478 case HAL_DATASPACE_V0_SRGB:
479 return HAL_DATASPACE_SRGB;
480 case HAL_DATASPACE_V0_JFIF:
481 return HAL_DATASPACE_JFIF;
482 case HAL_DATASPACE_V0_BT601_625:
483 return HAL_DATASPACE_BT601_625;
484 case HAL_DATASPACE_V0_BT601_525:
485 return HAL_DATASPACE_BT601_525;
486 case HAL_DATASPACE_V0_BT709:
487 return HAL_DATASPACE_BT709;
488 default:
489 return dataSpace;
490 }
491}
492
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800493hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
494 int frameworkFormat) {
495 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
496}
497
498DataspaceFlags Camera3Device::mapToHidlDataspace(
499 android_dataspace dataSpace) {
500 return dataSpace;
501}
502
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700503ConsumerUsageFlags Camera3Device::mapToConsumerUsage(
504 uint32_t usage) {
505 return usage;
506}
507
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800508StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
509 switch (rotation) {
510 case CAMERA3_STREAM_ROTATION_0:
511 return StreamRotation::ROTATION_0;
512 case CAMERA3_STREAM_ROTATION_90:
513 return StreamRotation::ROTATION_90;
514 case CAMERA3_STREAM_ROTATION_180:
515 return StreamRotation::ROTATION_180;
516 case CAMERA3_STREAM_ROTATION_270:
517 return StreamRotation::ROTATION_270;
518 }
519 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
520 return StreamRotation::ROTATION_0;
521}
522
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800523status_t Camera3Device::mapToStreamConfigurationMode(
524 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
525 if (mode == nullptr) return BAD_VALUE;
526 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
527 switch(operationMode) {
528 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
529 *mode = StreamConfigurationMode::NORMAL_MODE;
530 break;
531 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
532 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
533 break;
534 default:
535 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
536 return BAD_VALUE;
537 }
538 } else {
539 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800540 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800541 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800542}
543
544camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
545 switch (status) {
546 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
547 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
548 }
549 return CAMERA3_BUFFER_STATUS_ERROR;
550}
551
552int Camera3Device::mapToFrameworkFormat(
553 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
554 return static_cast<uint32_t>(pixelFormat);
555}
556
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700557uint32_t Camera3Device::mapConsumerToFrameworkUsage(
558 ConsumerUsageFlags usage) {
559 return usage;
560}
561
562uint32_t Camera3Device::mapProducerToFrameworkUsage(
563 ProducerUsageFlags usage) {
564 return usage;
565}
566
Zhijun Hef7da0962014-04-24 13:27:56 -0700567ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700568 // Get max jpeg size (area-wise).
569 Size maxJpegResolution = getMaxJpegResolution();
570 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800571 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
572 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700573 return BAD_VALUE;
574 }
575
Zhijun Hef7da0962014-04-24 13:27:56 -0700576 // Get max jpeg buffer size
577 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700578 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
579 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
581 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700582 return BAD_VALUE;
583 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700584 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800585 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700586
587 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700588 float scaleFactor = ((float) (width * height)) /
589 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800590 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
591 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700592 if (jpegBufferSize > maxJpegBufferSize) {
593 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700594 }
595
596 return jpegBufferSize;
597}
598
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700599ssize_t Camera3Device::getPointCloudBufferSize() const {
600 const int FLOATS_PER_POINT=4;
601 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
602 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
604 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700605 return BAD_VALUE;
606 }
607 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
608 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
609 return maxBytesForPointCloud;
610}
611
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800612ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800613 const int PER_CONFIGURATION_SIZE = 3;
614 const int WIDTH_OFFSET = 0;
615 const int HEIGHT_OFFSET = 1;
616 const int SIZE_OFFSET = 2;
617 camera_metadata_ro_entry rawOpaqueSizes =
618 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800619 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800620 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
622 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800623 return BAD_VALUE;
624 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700625
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800626 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
627 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
628 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
629 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
630 }
631 }
632
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
634 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800635 return BAD_VALUE;
636}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800638status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
639 ATRACE_CALL();
640 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700641
642 // Try to lock, but continue in case of failure (to avoid blocking in
643 // deadlocks)
644 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
645 bool gotLock = tryLockSpinRightRound(mLock);
646
647 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800648 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
649 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700650 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800651 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
652 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700653
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800654 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700655
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800656 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700657 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800658 int n = args.size();
659 for (int i = 0; i < n; i++) {
660 if (args[i] == templatesOption) {
661 dumpTemplates = true;
662 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700663 if (args[i] == monitorOption) {
664 if (i + 1 < n) {
665 String8 monitorTags = String8(args[i + 1]);
666 if (monitorTags == "off") {
667 mTagMonitor.disableMonitoring();
668 } else {
669 mTagMonitor.parseTagsToMonitor(monitorTags);
670 }
671 } else {
672 mTagMonitor.disableMonitoring();
673 }
674 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800675 }
676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800678
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800679 const char *status =
680 mStatus == STATUS_ERROR ? "ERROR" :
681 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700682 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
683 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800684 mStatus == STATUS_ACTIVE ? "ACTIVE" :
685 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700686
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800687 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700688 if (mStatus == STATUS_ERROR) {
689 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
690 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800691 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800692 const char *mode =
693 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
694 mOperatingMode == static_cast<int>(
695 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
696 "CUSTOM";
697 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800698
699 if (mInputStream != NULL) {
700 write(fd, lines.string(), lines.size());
701 mInputStream->dump(fd, args);
702 } else {
703 lines.appendFormat(" No input stream.\n");
704 write(fd, lines.string(), lines.size());
705 }
706 for (size_t i = 0; i < mOutputStreams.size(); i++) {
707 mOutputStreams[i]->dump(fd,args);
708 }
709
Zhijun He431503c2016-03-07 17:30:16 -0800710 if (mBufferManager != NULL) {
711 lines = String8(" Camera3 Buffer Manager:\n");
712 write(fd, lines.string(), lines.size());
713 mBufferManager->dump(fd, args);
714 }
Zhijun He125684a2015-12-26 15:07:30 -0800715
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700716 lines = String8(" In-flight requests:\n");
717 if (mInFlightMap.size() == 0) {
718 lines.append(" None\n");
719 } else {
720 for (size_t i = 0; i < mInFlightMap.size(); i++) {
721 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700722 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700723 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800724 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700725 r.numBuffersLeft);
726 }
727 }
728 write(fd, lines.string(), lines.size());
729
Igor Murashkin1e479c02013-09-06 16:55:14 -0700730 {
731 lines = String8(" Last request sent:\n");
732 write(fd, lines.string(), lines.size());
733
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700734 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700735 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
736 }
737
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800738 if (dumpTemplates) {
739 const char *templateNames[] = {
740 "TEMPLATE_PREVIEW",
741 "TEMPLATE_STILL_CAPTURE",
742 "TEMPLATE_VIDEO_RECORD",
743 "TEMPLATE_VIDEO_SNAPSHOT",
744 "TEMPLATE_ZERO_SHUTTER_LAG",
745 "TEMPLATE_MANUAL"
746 };
747
748 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800749 camera_metadata_t *templateRequest = nullptr;
750 mInterface->constructDefaultRequestSettings(
751 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800752 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800753 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800754 lines.append(" Not supported\n");
755 write(fd, lines.string(), lines.size());
756 } else {
757 write(fd, lines.string(), lines.size());
758 dump_indented_camera_metadata(templateRequest,
759 fd, /*verbosity*/2, /*indentation*/8);
760 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800761 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800762 }
763 }
764
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700765 mTagMonitor.dumpMonitoredMetadata(fd);
766
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800767 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800768 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800769 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800771 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700773 if (gotLock) mLock.unlock();
774 if (gotInterfaceLock) mInterfaceLock.unlock();
775
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800776 return OK;
777}
778
779const CameraMetadata& Camera3Device::info() const {
780 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800781 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
782 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700783 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800784 mStatus == STATUS_ERROR ?
785 "when in error state" : "before init");
786 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800787 return mDeviceInfo;
788}
789
Jianing Wei90e59c92014-03-12 18:29:36 -0700790status_t Camera3Device::checkStatusOkToCaptureLocked() {
791 switch (mStatus) {
792 case STATUS_ERROR:
793 CLOGE("Device has encountered a serious error");
794 return INVALID_OPERATION;
795 case STATUS_UNINITIALIZED:
796 CLOGE("Device not initialized");
797 return INVALID_OPERATION;
798 case STATUS_UNCONFIGURED:
799 case STATUS_CONFIGURED:
800 case STATUS_ACTIVE:
801 // OK
802 break;
803 default:
804 SET_ERR_L("Unexpected status: %d", mStatus);
805 return INVALID_OPERATION;
806 }
807 return OK;
808}
809
810status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811 const List<const CameraMetadata> &metadataList,
812 const std::list<const SurfaceMap> &surfaceMaps,
813 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700814 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700815 if (requestList == NULL) {
816 CLOGE("requestList cannot be NULL.");
817 return BAD_VALUE;
818 }
819
Jianing Weicb0652e2014-03-12 18:29:36 -0700820 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700821 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
822 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
823 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
824 ++metadataIt, ++surfaceMapIt) {
825 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 if (newRequest == 0) {
827 CLOGE("Can't create capture request");
828 return BAD_VALUE;
829 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700830
Shuzhen Wang9d066012016-09-30 11:30:20 -0700831 newRequest->mRepeating = repeating;
832
Jianing Weicb0652e2014-03-12 18:29:36 -0700833 // Setup burst Id and request Id
834 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
836 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700837 CLOGE("RequestID entry exists; but must not be empty in metadata");
838 return BAD_VALUE;
839 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700840 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700841 } else {
842 CLOGE("RequestID does not exist in metadata");
843 return BAD_VALUE;
844 }
845
Jianing Wei90e59c92014-03-12 18:29:36 -0700846 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700847
848 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700849 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700850 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
851 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
852 return BAD_VALUE;
853 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700854
855 // Setup batch size if this is a high speed video recording request.
856 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
857 auto firstRequest = requestList->begin();
858 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
859 if (outputStream->isVideoStream()) {
860 (*firstRequest)->mBatchSize = requestList->size();
861 break;
862 }
863 }
864 }
865
Jianing Wei90e59c92014-03-12 18:29:36 -0700866 return OK;
867}
868
Jianing Weicb0652e2014-03-12 18:29:36 -0700869status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800870 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800871
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700872 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700873 std::list<const SurfaceMap> surfaceMaps;
874 convertToRequestList(requests, surfaceMaps, request);
875
876 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
877}
878
879void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
880 std::list<const SurfaceMap>& surfaceMaps,
881 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700882 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700883
884 SurfaceMap surfaceMap;
885 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
886 // With no surface list passed in, stream and surface will have 1-to-1
887 // mapping. So the surface index is 0 for each stream in the surfaceMap.
888 for (size_t i = 0; i < streams.count; i++) {
889 surfaceMap[streams.data.i32[i]].push_back(0);
890 }
891 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800892}
893
Jianing Wei90e59c92014-03-12 18:29:36 -0700894status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700895 const List<const CameraMetadata> &requests,
896 const std::list<const SurfaceMap> &surfaceMaps,
897 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700898 /*out*/
899 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700900 ATRACE_CALL();
901 Mutex::Autolock il(mInterfaceLock);
902 Mutex::Autolock l(mLock);
903
904 status_t res = checkStatusOkToCaptureLocked();
905 if (res != OK) {
906 // error logged by previous call
907 return res;
908 }
909
910 RequestList requestList;
911
Shuzhen Wang0129d522016-10-30 22:43:41 -0700912 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
913 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700914 if (res != OK) {
915 // error logged by previous call
916 return res;
917 }
918
919 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700920 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700922 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700923 }
924
925 if (res == OK) {
926 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
927 if (res != OK) {
928 SET_ERR_L("Can't transition to active in %f seconds!",
929 kActiveTimeout/1e9);
930 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700932 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700933 } else {
934 CLOGE("Cannot queue request. Impossible.");
935 return BAD_VALUE;
936 }
937
938 return res;
939}
940
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800941
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800942hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800943 const hardware::hidl_vec<
944 hardware::camera::device::V3_2::CaptureResult>& results) {
945 for (const auto& result : results) {
946 processOneCaptureResult(result);
947 }
948 return hardware::Void();
949}
950
951void Camera3Device::processOneCaptureResult(
952 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800953 camera3_capture_result r;
954 status_t res;
955 r.frame_number = result.frameNumber;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800956 if (result.result.size() != 0) {
957 r.result = reinterpret_cast<const camera_metadata_t*>(result.result.data());
958 size_t expected_metadata_size = result.result.size();
959 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
960 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
961 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800962 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800963 }
964 } else {
965 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800966 }
967
968 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
969 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
970 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
971 auto& bDst = outputBuffers[i];
972 const StreamBuffer &bSrc = result.outputBuffers[i];
973
974 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100975 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800976 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
977 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800978 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800979 }
980 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
981
982 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800983 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800984 if (res != OK) {
985 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
986 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800987 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800988 }
989 bDst.buffer = buffer;
990 bDst.status = mapHidlBufferStatus(bSrc.status);
991 bDst.acquire_fence = -1;
992 if (bSrc.releaseFence == nullptr) {
993 bDst.release_fence = -1;
994 } else if (bSrc.releaseFence->numFds == 1) {
995 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
996 } else {
997 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
998 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800999 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 }
1001 }
1002 r.num_output_buffers = outputBuffers.size();
1003 r.output_buffers = outputBuffers.data();
1004
1005 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001006 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001007 r.input_buffer = nullptr;
1008 } else {
1009 if (mInputStream->getId() != result.inputBuffer.streamId) {
1010 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1011 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001012 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001013 }
1014 inputBuffer.stream = mInputStream->asHalStream();
1015 buffer_handle_t *buffer;
1016 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1017 &buffer);
1018 if (res != OK) {
1019 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1020 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001021 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001022 }
1023 inputBuffer.buffer = buffer;
1024 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1025 inputBuffer.acquire_fence = -1;
1026 if (result.inputBuffer.releaseFence == nullptr) {
1027 inputBuffer.release_fence = -1;
1028 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1029 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1030 } else {
1031 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1032 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001033 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001034 }
1035 r.input_buffer = &inputBuffer;
1036 }
1037
1038 r.partial_result = result.partialResult;
1039
1040 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001041}
1042
1043hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001044 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1045 for (const auto& msg : msgs) {
1046 notify(msg);
1047 }
1048 return hardware::Void();
1049}
1050
1051void Camera3Device::notify(
1052 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1053
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001054 camera3_notify_msg m;
1055 switch (msg.type) {
1056 case MsgType::ERROR:
1057 m.type = CAMERA3_MSG_ERROR;
1058 m.message.error.frame_number = msg.msg.error.frameNumber;
1059 if (msg.msg.error.errorStreamId >= 0) {
1060 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001061 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001062 ALOGE("%s: Frame %d: Invalid error stream id %d",
1063 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001064 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001065 }
1066 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1067 } else {
1068 m.message.error.error_stream = nullptr;
1069 }
1070 switch (msg.msg.error.errorCode) {
1071 case ErrorCode::ERROR_DEVICE:
1072 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1073 break;
1074 case ErrorCode::ERROR_REQUEST:
1075 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1076 break;
1077 case ErrorCode::ERROR_RESULT:
1078 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1079 break;
1080 case ErrorCode::ERROR_BUFFER:
1081 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1082 break;
1083 }
1084 break;
1085 case MsgType::SHUTTER:
1086 m.type = CAMERA3_MSG_SHUTTER;
1087 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1088 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1089 break;
1090 }
1091 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001092}
1093
Jianing Weicb0652e2014-03-12 18:29:36 -07001094status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001096 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001097 ATRACE_CALL();
1098
Shuzhen Wang0129d522016-10-30 22:43:41 -07001099 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001100}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001101
Jianing Weicb0652e2014-03-12 18:29:36 -07001102status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1103 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001104 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001105
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001106 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001107 std::list<const SurfaceMap> surfaceMaps;
1108 convertToRequestList(requests, surfaceMaps, request);
1109
1110 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1111 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001112}
1113
Jianing Weicb0652e2014-03-12 18:29:36 -07001114status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001115 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001116 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001117 ATRACE_CALL();
1118
Shuzhen Wang0129d522016-10-30 22:43:41 -07001119 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001120}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001121
1122sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001123 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001124 status_t res;
1125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001126 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001127 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1128 // so unilaterally select normal operating mode.
1129 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001130 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001131 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001132 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001133 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001134 } else if (mStatus == STATUS_UNCONFIGURED) {
1135 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001136 CLOGE("No streams configured");
1137 return NULL;
1138 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001139 }
1140
Shuzhen Wang0129d522016-10-30 22:43:41 -07001141 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001142 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001143}
1144
Jianing Weicb0652e2014-03-12 18:29:36 -07001145status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001146 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001147 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001149
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001150 switch (mStatus) {
1151 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001152 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153 return INVALID_OPERATION;
1154 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001155 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001156 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001157 case STATUS_UNCONFIGURED:
1158 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001159 case STATUS_ACTIVE:
1160 // OK
1161 break;
1162 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001163 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001164 return INVALID_OPERATION;
1165 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001166 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001167
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001168 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169}
1170
1171status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1172 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001174
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001175 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176}
1177
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001178status_t Camera3Device::createInputStream(
1179 uint32_t width, uint32_t height, int format, int *id) {
1180 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001181 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001182 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001183 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1184 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001185
1186 status_t res;
1187 bool wasActive = false;
1188
1189 switch (mStatus) {
1190 case STATUS_ERROR:
1191 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1192 return INVALID_OPERATION;
1193 case STATUS_UNINITIALIZED:
1194 ALOGE("%s: Device not initialized", __FUNCTION__);
1195 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001196 case STATUS_UNCONFIGURED:
1197 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001198 // OK
1199 break;
1200 case STATUS_ACTIVE:
1201 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001203 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001205 return res;
1206 }
1207 wasActive = true;
1208 break;
1209 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001211 return INVALID_OPERATION;
1212 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001214
1215 if (mInputStream != 0) {
1216 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1217 return INVALID_OPERATION;
1218 }
1219
1220 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1221 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001222 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001223
1224 mInputStream = newStream;
1225
1226 *id = mNextStreamId++;
1227
1228 // Continue captures if active at start
1229 if (wasActive) {
1230 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001231 // Reuse current operating mode for new stream config
1232 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001233 if (res != OK) {
1234 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1235 __FUNCTION__, mNextStreamId, strerror(-res), res);
1236 return res;
1237 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001238 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001239 }
1240
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001241 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001242 return OK;
1243}
1244
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001245status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001246 uint32_t width, uint32_t height, int format,
1247 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001248 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001249 ATRACE_CALL();
1250
1251 if (consumer == nullptr) {
1252 ALOGE("%s: consumer must not be null", __FUNCTION__);
1253 return BAD_VALUE;
1254 }
1255
1256 std::vector<sp<Surface>> consumers;
1257 consumers.push_back(consumer);
1258
1259 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001260 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001261}
1262
1263status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1264 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1265 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001266 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001267 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001268 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001270 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001271 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1272 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001273
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 status_t res;
1275 bool wasActive = false;
1276
1277 switch (mStatus) {
1278 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001279 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 return INVALID_OPERATION;
1281 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001282 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 case STATUS_UNCONFIGURED:
1285 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 // OK
1287 break;
1288 case STATUS_ACTIVE:
1289 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 return res;
1294 }
1295 wasActive = true;
1296 break;
1297 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001298 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 return INVALID_OPERATION;
1300 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302
1303 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001304 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001305 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001306 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001307 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1308 }
Zhijun He5d677d12016-05-29 16:52:39 -07001309
Shuzhen Wang0129d522016-10-30 22:43:41 -07001310 if (consumers.size() == 0 && !hasDeferredConsumer) {
1311 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1312 return BAD_VALUE;
1313 }
Zhijun He5d677d12016-05-29 16:52:39 -07001314 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1315 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001316 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001317 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1318 return BAD_VALUE;
1319 }
1320
Shuzhen Wang0129d522016-10-30 22:43:41 -07001321 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001322 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1323 return BAD_VALUE;
1324 }
1325
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001326 // Use legacy dataspace values for older HALs
1327 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1328 dataSpace = mapToLegacyDataspace(dataSpace);
1329 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001330 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001331 ssize_t blobBufferSize;
1332 if (dataSpace != HAL_DATASPACE_DEPTH) {
1333 blobBufferSize = getJpegBufferSize(width, height);
1334 if (blobBufferSize <= 0) {
1335 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1336 return BAD_VALUE;
1337 }
1338 } else {
1339 blobBufferSize = getPointCloudBufferSize();
1340 if (blobBufferSize <= 0) {
1341 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1342 return BAD_VALUE;
1343 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001344 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001345 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001346 width, height, blobBufferSize, format, dataSpace, rotation,
1347 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001348 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1349 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1350 if (rawOpaqueBufferSize <= 0) {
1351 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1352 return BAD_VALUE;
1353 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001354 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001355 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1356 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001357 } else if (isShared) {
1358 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1359 width, height, format, consumerUsage, dataSpace, rotation,
1360 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001361 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001362 newStream = new Camera3OutputStream(mNextStreamId,
1363 width, height, format, consumerUsage, dataSpace, rotation,
1364 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001366 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001367 width, height, format, dataSpace, rotation,
1368 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001370 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371
Zhijun He125684a2015-12-26 15:07:30 -08001372 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001373 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1374 * requires buffers to be statically allocated for internal static buffer registration, while
1375 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1376 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001377 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001378 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001379 newStream->setBufferManager(mBufferManager);
1380 }
1381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 res = mOutputStreams.add(mNextStreamId, newStream);
1383 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001384 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 return res;
1386 }
1387
1388 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001389 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001390
1391 // Continue captures if active at start
1392 if (wasActive) {
1393 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001394 // Reuse current operating mode for new stream config
1395 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001397 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1398 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 return res;
1400 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001401 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001405}
1406
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001407status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001408 uint32_t *width, uint32_t *height,
1409 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001410 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001411 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001413
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414 switch (mStatus) {
1415 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001416 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001417 return INVALID_OPERATION;
1418 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001419 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001420 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001421 case STATUS_UNCONFIGURED:
1422 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 case STATUS_ACTIVE:
1424 // OK
1425 break;
1426 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001427 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 return INVALID_OPERATION;
1429 }
1430
1431 ssize_t idx = mOutputStreams.indexOfKey(id);
1432 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001433 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 return idx;
1435 }
1436
1437 if (width) *width = mOutputStreams[idx]->getWidth();
1438 if (height) *height = mOutputStreams[idx]->getHeight();
1439 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001440 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001442}
1443
1444status_t Camera3Device::setStreamTransform(int id,
1445 int transform) {
1446 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 switch (mStatus) {
1451 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001452 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 return INVALID_OPERATION;
1454 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001455 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 case STATUS_UNCONFIGURED:
1458 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 case STATUS_ACTIVE:
1460 // OK
1461 break;
1462 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001463 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 return INVALID_OPERATION;
1465 }
1466
1467 ssize_t idx = mOutputStreams.indexOfKey(id);
1468 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001469 CLOGE("Stream %d does not exist",
1470 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 return BAD_VALUE;
1472 }
1473
1474 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475}
1476
1477status_t Camera3Device::deleteStream(int id) {
1478 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001479 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 Mutex::Autolock l(mLock);
1481 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001482
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001483 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 // CameraDevice semantics require device to already be idle before
1486 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001487 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001488 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001489 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 }
1491
Igor Murashkin2fba5842013-04-22 14:03:54 -07001492 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001493 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 if (mInputStream != NULL && id == mInputStream->getId()) {
1495 deletedStream = mInputStream;
1496 mInputStream.clear();
1497 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001498 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001499 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 return BAD_VALUE;
1501 }
Zhijun He5f446352014-01-22 09:49:33 -08001502 }
1503
1504 // Delete output stream or the output part of a bi-directional stream.
1505 if (outputStreamIdx != NAME_NOT_FOUND) {
1506 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 mOutputStreams.removeItem(id);
1508 }
1509
1510 // Free up the stream endpoint so that it can be used by some other stream
1511 res = deletedStream->disconnect();
1512 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001513 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 // fall through since we want to still list the stream as deleted.
1515 }
1516 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001517 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518
1519 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001520}
1521
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001522status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001523 ATRACE_CALL();
1524 ALOGV("%s: E", __FUNCTION__);
1525
1526 Mutex::Autolock il(mInterfaceLock);
1527 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001528
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001529 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001530}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001531
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001532status_t Camera3Device::getInputBufferProducer(
1533 sp<IGraphicBufferProducer> *producer) {
1534 Mutex::Autolock il(mInterfaceLock);
1535 Mutex::Autolock l(mLock);
1536
1537 if (producer == NULL) {
1538 return BAD_VALUE;
1539 } else if (mInputStream == NULL) {
1540 return INVALID_OPERATION;
1541 }
1542
1543 return mInputStream->getInputBufferProducer(producer);
1544}
1545
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546status_t Camera3Device::createDefaultRequest(int templateId,
1547 CameraMetadata *request) {
1548 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001549 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001550
1551 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1552 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1553 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1554 return BAD_VALUE;
1555 }
1556
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001557 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 Mutex::Autolock l(mLock);
1559
1560 switch (mStatus) {
1561 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001562 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 return INVALID_OPERATION;
1564 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001565 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 case STATUS_UNCONFIGURED:
1568 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 case STATUS_ACTIVE:
1570 // OK
1571 break;
1572 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 return INVALID_OPERATION;
1575 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Zhijun Hea1530f12014-09-14 12:44:20 -07001577 if (!mRequestTemplateCache[templateId].isEmpty()) {
1578 *request = mRequestTemplateCache[templateId];
1579 return OK;
1580 }
1581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001582 camera_metadata_t *rawRequest;
1583 status_t res = mInterface->constructDefaultRequestSettings(
1584 (camera3_request_template_t) templateId, &rawRequest);
1585 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001586 ALOGI("%s: template %d is not supported on this camera device",
1587 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001588 return res;
1589 } else if (res != OK) {
1590 CLOGE("Unable to construct request template %d: %s (%d)",
1591 templateId, strerror(-res), res);
1592 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001593 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001594
Emilian Peev71c73a22017-03-21 16:35:51 +00001595 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001596 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001598 // Derive some new keys for backward compatibility
1599 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1600 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1601 int32_t defaultBoost[1] = {100};
1602 mRequestTemplateCache[templateId].update(
1603 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1604 defaultBoost, 1);
1605 }
1606
1607 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608 return OK;
1609}
1610
1611status_t Camera3Device::waitUntilDrained() {
1612 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615
Zhijun He69a37482014-03-23 18:44:49 -07001616 return waitUntilDrainedLocked();
1617}
1618
1619status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001620 switch (mStatus) {
1621 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001622 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 ALOGV("%s: Already idle", __FUNCTION__);
1624 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 case STATUS_CONFIGURED:
1626 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627 case STATUS_ERROR:
1628 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 break;
1631 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001632 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 return INVALID_OPERATION;
1634 }
1635
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001636 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001638 if (res != OK) {
1639 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1640 res);
1641 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642 return res;
1643}
1644
Ruben Brunk183f0562015-08-12 12:55:02 -07001645
1646void Camera3Device::internalUpdateStatusLocked(Status status) {
1647 mStatus = status;
1648 mRecentStatusUpdates.add(mStatus);
1649 mStatusChanged.broadcast();
1650}
1651
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001652// Pause to reconfigure
1653status_t Camera3Device::internalPauseAndWaitLocked() {
1654 mRequestThread->setPaused(true);
1655 mPauseStateNotify = true;
1656
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001657 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1659 if (res != OK) {
1660 SET_ERR_L("Can't idle device in %f seconds!",
1661 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001662 }
1663
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001664 return res;
1665}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667// Resume after internalPauseAndWaitLocked
1668status_t Camera3Device::internalResumeLocked() {
1669 status_t res;
1670
1671 mRequestThread->setPaused(false);
1672
1673 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1674 if (res != OK) {
1675 SET_ERR_L("Can't transition to active in %f seconds!",
1676 kActiveTimeout/1e9);
1677 }
1678 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001679 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680}
1681
Ruben Brunk183f0562015-08-12 12:55:02 -07001682status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001684
1685 size_t startIndex = 0;
1686 if (mStatusWaiters == 0) {
1687 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1688 // this status list
1689 mRecentStatusUpdates.clear();
1690 } else {
1691 // If other threads are waiting on updates to this status list, set the position of the
1692 // first element that this list will check rather than clearing the list.
1693 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001694 }
1695
Ruben Brunk183f0562015-08-12 12:55:02 -07001696 mStatusWaiters++;
1697
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001698 bool stateSeen = false;
1699 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001700 if (active == (mStatus == STATUS_ACTIVE)) {
1701 // Desired state is current
1702 break;
1703 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704
1705 res = mStatusChanged.waitRelative(mLock, timeout);
1706 if (res != OK) break;
1707
Ruben Brunk183f0562015-08-12 12:55:02 -07001708 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1709 // transitions.
1710 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1711 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1712 __FUNCTION__);
1713
1714 // Encountered desired state since we began waiting
1715 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001716 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1717 stateSeen = true;
1718 break;
1719 }
1720 }
1721 } while (!stateSeen);
1722
Ruben Brunk183f0562015-08-12 12:55:02 -07001723 mStatusWaiters--;
1724
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001725 return res;
1726}
1727
1728
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001729status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001730 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001731 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001733 if (listener != NULL && mListener != NULL) {
1734 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1735 }
1736 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001737 mRequestThread->setNotificationListener(listener);
1738 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001739
1740 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741}
1742
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001743bool Camera3Device::willNotify3A() {
1744 return false;
1745}
1746
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001747status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001748 status_t res;
1749 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001751 while (mResultQueue.empty()) {
1752 res = mResultSignal.waitRelative(mOutputLock, timeout);
1753 if (res == TIMED_OUT) {
1754 return res;
1755 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001756 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1757 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001758 return res;
1759 }
1760 }
1761 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762}
1763
Jianing Weicb0652e2014-03-12 18:29:36 -07001764status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001765 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001766 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001768 if (mResultQueue.empty()) {
1769 return NOT_ENOUGH_DATA;
1770 }
1771
Jianing Weicb0652e2014-03-12 18:29:36 -07001772 if (frame == NULL) {
1773 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1774 return BAD_VALUE;
1775 }
1776
1777 CaptureResult &result = *(mResultQueue.begin());
1778 frame->mResultExtras = result.mResultExtras;
1779 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001780 mResultQueue.erase(mResultQueue.begin());
1781
1782 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783}
1784
1785status_t Camera3Device::triggerAutofocus(uint32_t id) {
1786 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001788
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001789 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1790 // Mix-in this trigger into the next request and only the next request.
1791 RequestTrigger trigger[] = {
1792 {
1793 ANDROID_CONTROL_AF_TRIGGER,
1794 ANDROID_CONTROL_AF_TRIGGER_START
1795 },
1796 {
1797 ANDROID_CONTROL_AF_TRIGGER_ID,
1798 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001799 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001800 };
1801
1802 return mRequestThread->queueTrigger(trigger,
1803 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001804}
1805
1806status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1807 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001810 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1811 // Mix-in this trigger into the next request and only the next request.
1812 RequestTrigger trigger[] = {
1813 {
1814 ANDROID_CONTROL_AF_TRIGGER,
1815 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1816 },
1817 {
1818 ANDROID_CONTROL_AF_TRIGGER_ID,
1819 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001820 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001821 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001822
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001823 return mRequestThread->queueTrigger(trigger,
1824 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825}
1826
1827status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1828 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001830
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001831 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1832 // Mix-in this trigger into the next request and only the next request.
1833 RequestTrigger trigger[] = {
1834 {
1835 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1836 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1837 },
1838 {
1839 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1840 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001841 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001842 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001843
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001844 return mRequestThread->queueTrigger(trigger,
1845 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846}
1847
Jianing Weicb0652e2014-03-12 18:29:36 -07001848status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001849 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001850 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001851 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001852
Zhijun He7ef20392014-04-21 16:04:17 -07001853 {
1854 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001855 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001856 }
1857
Zhijun He491e3412013-12-27 10:57:44 -08001858 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001859 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001860 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001861 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001862 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001863 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001864 }
1865
1866 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001867}
1868
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001869status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001870 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1871}
1872
1873status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001874 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001875 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001876 Mutex::Autolock il(mInterfaceLock);
1877 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001878
1879 sp<Camera3StreamInterface> stream;
1880 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1881 if (outputStreamIdx == NAME_NOT_FOUND) {
1882 CLOGE("Stream %d does not exist", streamId);
1883 return BAD_VALUE;
1884 }
1885
1886 stream = mOutputStreams.editValueAt(outputStreamIdx);
1887
1888 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001889 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890 return BAD_VALUE;
1891 }
1892
1893 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001894 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001895 return BAD_VALUE;
1896 }
1897
Ruben Brunkc78ac262015-08-13 17:58:46 -07001898 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001899}
1900
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001901status_t Camera3Device::tearDown(int streamId) {
1902 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001903 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001904 Mutex::Autolock il(mInterfaceLock);
1905 Mutex::Autolock l(mLock);
1906
1907 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1908 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001909 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001910 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001911 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001912 return NO_INIT;
1913 }
1914
1915 sp<Camera3StreamInterface> stream;
1916 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1917 if (outputStreamIdx == NAME_NOT_FOUND) {
1918 CLOGE("Stream %d does not exist", streamId);
1919 return BAD_VALUE;
1920 }
1921
1922 stream = mOutputStreams.editValueAt(outputStreamIdx);
1923
1924 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1925 CLOGE("Stream %d is a target of a in-progress request", streamId);
1926 return BAD_VALUE;
1927 }
1928
1929 return stream->tearDown();
1930}
1931
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001932status_t Camera3Device::addBufferListenerForStream(int streamId,
1933 wp<Camera3StreamBufferListener> listener) {
1934 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001935 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001936 Mutex::Autolock il(mInterfaceLock);
1937 Mutex::Autolock l(mLock);
1938
1939 sp<Camera3StreamInterface> stream;
1940 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1941 if (outputStreamIdx == NAME_NOT_FOUND) {
1942 CLOGE("Stream %d does not exist", streamId);
1943 return BAD_VALUE;
1944 }
1945
1946 stream = mOutputStreams.editValueAt(outputStreamIdx);
1947 stream->addBufferListener(listener);
1948
1949 return OK;
1950}
1951
Zhijun He204e3292014-07-14 17:09:23 -07001952uint32_t Camera3Device::getDeviceVersion() {
1953 ATRACE_CALL();
1954 Mutex::Autolock il(mInterfaceLock);
1955 return mDeviceVersion;
1956}
1957
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001958/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 * Methods called by subclasses
1960 */
1961
1962void Camera3Device::notifyStatus(bool idle) {
1963 {
1964 // Need mLock to safely update state and synchronize to current
1965 // state of methods in flight.
1966 Mutex::Autolock l(mLock);
1967 // We can get various system-idle notices from the status tracker
1968 // while starting up. Only care about them if we've actually sent
1969 // in some requests recently.
1970 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1971 return;
1972 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001973 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001974 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001975 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001976
1977 // Skip notifying listener if we're doing some user-transparent
1978 // state changes
1979 if (mPauseStateNotify) return;
1980 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001981
1982 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001983 {
1984 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001985 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001986 }
1987 if (idle && listener != NULL) {
1988 listener->notifyIdle();
1989 }
1990}
1991
Shuzhen Wang758c2152017-01-10 18:26:18 -08001992status_t Camera3Device::setConsumerSurfaces(int streamId,
1993 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001994 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001995 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1996 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001997 Mutex::Autolock il(mInterfaceLock);
1998 Mutex::Autolock l(mLock);
1999
Shuzhen Wang758c2152017-01-10 18:26:18 -08002000 if (consumers.size() == 0) {
2001 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002002 return BAD_VALUE;
2003 }
2004
2005 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2006 if (idx == NAME_NOT_FOUND) {
2007 CLOGE("Stream %d is unknown", streamId);
2008 return idx;
2009 }
2010 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002011 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002012 if (res != OK) {
2013 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2014 return res;
2015 }
2016
Shuzhen Wang0129d522016-10-30 22:43:41 -07002017 if (stream->isConsumerConfigurationDeferred()) {
2018 if (!stream->isConfiguring()) {
2019 CLOGE("Stream %d was already fully configured.", streamId);
2020 return INVALID_OPERATION;
2021 }
Zhijun He5d677d12016-05-29 16:52:39 -07002022
Shuzhen Wang0129d522016-10-30 22:43:41 -07002023 res = stream->finishConfiguration();
2024 if (res != OK) {
2025 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2026 stream->getId(), strerror(-res), res);
2027 return res;
2028 }
Zhijun He5d677d12016-05-29 16:52:39 -07002029 }
2030
2031 return OK;
2032}
2033
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002034/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035 * Camera3Device private methods
2036 */
2037
2038sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002039 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040 ATRACE_CALL();
2041 status_t res;
2042
2043 sp<CaptureRequest> newRequest = new CaptureRequest;
2044 newRequest->mSettings = request;
2045
2046 camera_metadata_entry_t inputStreams =
2047 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2048 if (inputStreams.count > 0) {
2049 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002050 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002051 CLOGE("Request references unknown input stream %d",
2052 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053 return NULL;
2054 }
2055 // Lazy completion of stream configuration (allocation/registration)
2056 // on first use
2057 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002058 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002059 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002060 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002062 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063 return NULL;
2064 }
2065 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002066 // Check if stream is being prepared
2067 if (mInputStream->isPreparing()) {
2068 CLOGE("Request references an input stream that's being prepared!");
2069 return NULL;
2070 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071
2072 newRequest->mInputStream = mInputStream;
2073 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2074 }
2075
2076 camera_metadata_entry_t streams =
2077 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2078 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002079 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 return NULL;
2081 }
2082
2083 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002084 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002085 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002086 CLOGE("Request references unknown stream %d",
2087 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 return NULL;
2089 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002090 sp<Camera3OutputStreamInterface> stream =
2091 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092
Zhijun He5d677d12016-05-29 16:52:39 -07002093 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002094 auto iter = surfaceMap.find(streams.data.i32[i]);
2095 if (iter != surfaceMap.end()) {
2096 const std::vector<size_t>& surfaces = iter->second;
2097 for (const auto& surface : surfaces) {
2098 if (stream->isConsumerConfigurationDeferred(surface)) {
2099 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2100 "due to deferred consumer", stream->getId(), surface);
2101 return NULL;
2102 }
2103 }
2104 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002105 }
2106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 // Lazy completion of stream configuration (allocation/registration)
2108 // on first use
2109 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002110 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002111 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002112 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2113 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114 return NULL;
2115 }
2116 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002117 // Check if stream is being prepared
2118 if (stream->isPreparing()) {
2119 CLOGE("Request references an output stream that's being prepared!");
2120 return NULL;
2121 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122
2123 newRequest->mOutputStreams.push(stream);
2124 }
2125 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002126 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127
2128 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002129}
2130
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002131bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2132 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2133 Size size = mSupportedOpaqueInputSizes[i];
2134 if (size.width == width && size.height == height) {
2135 return true;
2136 }
2137 }
2138
2139 return false;
2140}
2141
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002142void Camera3Device::cancelStreamsConfigurationLocked() {
2143 int res = OK;
2144 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2145 res = mInputStream->cancelConfiguration();
2146 if (res != OK) {
2147 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2148 mInputStream->getId(), strerror(-res), res);
2149 }
2150 }
2151
2152 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2153 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2154 if (outputStream->isConfiguring()) {
2155 res = outputStream->cancelConfiguration();
2156 if (res != OK) {
2157 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2158 outputStream->getId(), strerror(-res), res);
2159 }
2160 }
2161 }
2162
2163 // Return state to that at start of call, so that future configures
2164 // properly clean things up
2165 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2166 mNeedConfig = true;
2167}
2168
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002169status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170 ATRACE_CALL();
2171 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002172
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002173 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002174 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175 return INVALID_OPERATION;
2176 }
2177
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002178 if (operatingMode < 0) {
2179 CLOGE("Invalid operating mode: %d", operatingMode);
2180 return BAD_VALUE;
2181 }
2182
2183 bool isConstrainedHighSpeed =
2184 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2185 operatingMode;
2186
2187 if (mOperatingMode != operatingMode) {
2188 mNeedConfig = true;
2189 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2190 mOperatingMode = operatingMode;
2191 }
2192
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002193 if (!mNeedConfig) {
2194 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2195 return OK;
2196 }
2197
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002198 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2199 // adding a dummy stream instead.
2200 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2201 if (mOutputStreams.size() == 0) {
2202 addDummyStreamLocked();
2203 } else {
2204 tryRemoveDummyStreamLocked();
2205 }
2206
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002207 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002208 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002209
2210 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002211 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002212 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2213
2214 Vector<camera3_stream_t*> streams;
2215 streams.setCapacity(config.num_streams);
2216
2217 if (mInputStream != NULL) {
2218 camera3_stream_t *inputStream;
2219 inputStream = mInputStream->startConfiguration();
2220 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002221 CLOGE("Can't start input stream configuration");
2222 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 return INVALID_OPERATION;
2224 }
2225 streams.add(inputStream);
2226 }
2227
2228 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002229
2230 // Don't configure bidi streams twice, nor add them twice to the list
2231 if (mOutputStreams[i].get() ==
2232 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2233
2234 config.num_streams--;
2235 continue;
2236 }
2237
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238 camera3_stream_t *outputStream;
2239 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2240 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002241 CLOGE("Can't start output stream configuration");
2242 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002243 return INVALID_OPERATION;
2244 }
2245 streams.add(outputStream);
2246 }
2247
2248 config.streams = streams.editArray();
2249
2250 // Do the HAL configuration; will potentially touch stream
2251 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002252
2253 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002255 if (res == BAD_VALUE) {
2256 // HAL rejected this set of streams as unsupported, clean up config
2257 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002258 CLOGE("Set of requested inputs/outputs not supported by HAL");
2259 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002260 return BAD_VALUE;
2261 } else if (res != OK) {
2262 // Some other kind of error from configure_streams - this is not
2263 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002264 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2265 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002266 return res;
2267 }
2268
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002269 // Finish all stream configuration immediately.
2270 // TODO: Try to relax this later back to lazy completion, which should be
2271 // faster
2272
Igor Murashkin073f8572013-05-02 14:59:28 -07002273 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002274 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002275 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002276 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002277 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002278 cancelStreamsConfigurationLocked();
2279 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002280 }
2281 }
2282
2283 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002284 sp<Camera3OutputStreamInterface> outputStream =
2285 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002286 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002287 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002288 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002289 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002290 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002291 cancelStreamsConfigurationLocked();
2292 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002293 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002294 }
2295 }
2296
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297 // Request thread needs to know to avoid using repeat-last-settings protocol
2298 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002299 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300
Zhijun He90f7c372016-08-16 16:19:43 -07002301 char value[PROPERTY_VALUE_MAX];
2302 property_get("camera.fifo.disable", value, "0");
2303 int32_t disableFifo = atoi(value);
2304 if (disableFifo != 1) {
2305 // Boost priority of request thread to SCHED_FIFO.
2306 pid_t requestThreadTid = mRequestThread->getTid();
2307 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002308 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002309 if (res != OK) {
2310 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2311 strerror(-res), res);
2312 } else {
2313 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2314 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002315 }
2316
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002317 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002319 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320
Ruben Brunk183f0562015-08-12 12:55:02 -07002321 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2322 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002323
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002324 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002325
Zhijun He0a210512014-07-24 13:45:15 -07002326 // tear down the deleted streams after configure streams.
2327 mDeletedStreams.clear();
2328
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002329 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002330}
2331
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002332status_t Camera3Device::addDummyStreamLocked() {
2333 ATRACE_CALL();
2334 status_t res;
2335
2336 if (mDummyStreamId != NO_STREAM) {
2337 // Should never be adding a second dummy stream when one is already
2338 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002339 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2340 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002341 return INVALID_OPERATION;
2342 }
2343
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002344 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002345
2346 sp<Camera3OutputStreamInterface> dummyStream =
2347 new Camera3DummyStream(mNextStreamId);
2348
2349 res = mOutputStreams.add(mNextStreamId, dummyStream);
2350 if (res < 0) {
2351 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2352 return res;
2353 }
2354
2355 mDummyStreamId = mNextStreamId;
2356 mNextStreamId++;
2357
2358 return OK;
2359}
2360
2361status_t Camera3Device::tryRemoveDummyStreamLocked() {
2362 ATRACE_CALL();
2363 status_t res;
2364
2365 if (mDummyStreamId == NO_STREAM) return OK;
2366 if (mOutputStreams.size() == 1) return OK;
2367
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002368 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002369
2370 // Ok, have a dummy stream and there's at least one other output stream,
2371 // so remove the dummy
2372
2373 sp<Camera3StreamInterface> deletedStream;
2374 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2375 if (outputStreamIdx == NAME_NOT_FOUND) {
2376 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2377 return INVALID_OPERATION;
2378 }
2379
2380 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2381 mOutputStreams.removeItemsAt(outputStreamIdx);
2382
2383 // Free up the stream endpoint so that it can be used by some other stream
2384 res = deletedStream->disconnect();
2385 if (res != OK) {
2386 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2387 // fall through since we want to still list the stream as deleted.
2388 }
2389 mDeletedStreams.add(deletedStream);
2390 mDummyStreamId = NO_STREAM;
2391
2392 return res;
2393}
2394
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002395void Camera3Device::setErrorState(const char *fmt, ...) {
2396 Mutex::Autolock l(mLock);
2397 va_list args;
2398 va_start(args, fmt);
2399
2400 setErrorStateLockedV(fmt, args);
2401
2402 va_end(args);
2403}
2404
2405void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2406 Mutex::Autolock l(mLock);
2407 setErrorStateLockedV(fmt, args);
2408}
2409
2410void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2411 va_list args;
2412 va_start(args, fmt);
2413
2414 setErrorStateLockedV(fmt, args);
2415
2416 va_end(args);
2417}
2418
2419void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002420 // Print out all error messages to log
2421 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002422 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002423
2424 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002425 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002426
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002427 mErrorCause = errorCause;
2428
2429 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002430 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002431
2432 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002433 sp<NotificationListener> listener = mListener.promote();
2434 if (listener != NULL) {
2435 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002436 CaptureResultExtras());
2437 }
2438
2439 // Save stack trace. View by dumping it later.
2440 CameraTraces::saveTrace();
2441 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002442}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002443
2444/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002445 * In-flight request management
2446 */
2447
Jianing Weicb0652e2014-03-12 18:29:36 -07002448status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002449 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002450 const AeTriggerCancelOverride_t &aeTriggerCancelOverride,
2451 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002452 ATRACE_CALL();
2453 Mutex::Autolock l(mInFlightLock);
2454
2455 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002456 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002457 aeTriggerCancelOverride, hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002458 if (res < 0) return res;
2459
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002460 if (mInFlightMap.size() == 1) {
2461 mStatusTracker->markComponentActive(mInFlightStatusId);
2462 }
2463
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002464 return OK;
2465}
2466
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002467void Camera3Device::returnOutputBuffers(
2468 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2469 nsecs_t timestamp) {
2470 for (size_t i = 0; i < numBuffers; i++)
2471 {
2472 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2473 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2474 // Note: stream may be deallocated at this point, if this buffer was
2475 // the last reference to it.
2476 if (res != OK) {
2477 ALOGE("Can't return buffer to its stream: %s (%d)",
2478 strerror(-res), res);
2479 }
2480 }
2481}
2482
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002483void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2484 mInFlightMap.removeItemsAt(idx, 1);
2485
2486 // Indicate idle inFlightMap to the status tracker
2487 if (mInFlightMap.size() == 0) {
2488 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2489 }
2490}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002491
2492void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2493
2494 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2495 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2496
2497 nsecs_t sensorTimestamp = request.sensorTimestamp;
2498 nsecs_t shutterTimestamp = request.shutterTimestamp;
2499
2500 // Check if it's okay to remove the request from InFlightMap:
2501 // In the case of a successful request:
2502 // all input and output buffers, all result metadata, shutter callback
2503 // arrived.
2504 // In the case of a unsuccessful request:
2505 // all input and output buffers arrived.
2506 if (request.numBuffersLeft == 0 &&
2507 (request.requestStatus != OK ||
2508 (request.haveResultMetadata && shutterTimestamp != 0))) {
2509 ATRACE_ASYNC_END("frame capture", frameNumber);
2510
Shuzhen Wang403044a2017-02-26 23:29:04 -08002511 // Sanity check - if sensor timestamp matches shutter timestamp in the
2512 // case of request having callback.
2513 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002514 sensorTimestamp != shutterTimestamp) {
2515 SET_ERR("sensor timestamp (%" PRId64
2516 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2517 sensorTimestamp, frameNumber, shutterTimestamp);
2518 }
2519
2520 // for an unsuccessful request, it may have pending output buffers to
2521 // return.
2522 assert(request.requestStatus != OK ||
2523 request.pendingOutputBuffers.size() == 0);
2524 returnOutputBuffers(request.pendingOutputBuffers.array(),
2525 request.pendingOutputBuffers.size(), 0);
2526
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002527 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002528 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2529 }
2530
2531 // Sanity check - if we have too many in-flight frames, something has
2532 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002533 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002534 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002535 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2536 kInFlightWarnLimitHighSpeed) {
2537 CLOGE("In-flight list too large for high speed configuration: %zu",
2538 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002539 }
2540}
2541
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002542void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2543 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2544 if (result == nullptr) return;
2545
Emilian Peev71c73a22017-03-21 16:35:51 +00002546 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2547 result->mMetadata.getAndLock());
2548 set_camera_metadata_vendor_id(meta, mVendorTagId);
2549 result->mMetadata.unlock(meta);
2550
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002551 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2552 (int32_t*)&frameNumber, 1) != OK) {
2553 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2554 return;
2555 }
2556
2557 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2558 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2559 return;
2560 }
2561
2562 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2563
2564 // Valid result, insert into queue
2565 List<CaptureResult>::iterator queuedResult =
2566 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2567 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2568 ", burstId = %" PRId32, __FUNCTION__,
2569 queuedResult->mResultExtras.requestId,
2570 queuedResult->mResultExtras.frameNumber,
2571 queuedResult->mResultExtras.burstId);
2572
2573 mResultSignal.signal();
2574}
2575
2576
2577void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2578 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2579 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2580 Mutex::Autolock l(mOutputLock);
2581
2582 CaptureResult captureResult;
2583 captureResult.mResultExtras = resultExtras;
2584 captureResult.mMetadata = partialResult;
2585
2586 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2587}
2588
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002589
2590void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2591 CaptureResultExtras &resultExtras,
2592 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002593 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002594 bool reprocess,
2595 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002596 if (pendingMetadata.isEmpty())
2597 return;
2598
2599 Mutex::Autolock l(mOutputLock);
2600
2601 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002602 if (reprocess) {
2603 if (frameNumber < mNextReprocessResultFrameNumber) {
2604 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002605 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002606 frameNumber, mNextReprocessResultFrameNumber);
2607 return;
2608 }
2609 mNextReprocessResultFrameNumber = frameNumber + 1;
2610 } else {
2611 if (frameNumber < mNextResultFrameNumber) {
2612 SET_ERR("Out-of-order capture result metadata submitted! "
2613 "(got frame number %d, expecting %d)",
2614 frameNumber, mNextResultFrameNumber);
2615 return;
2616 }
2617 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002618 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002619
2620 CaptureResult captureResult;
2621 captureResult.mResultExtras = resultExtras;
2622 captureResult.mMetadata = pendingMetadata;
2623
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002624 // Append any previous partials to form a complete result
2625 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2626 captureResult.mMetadata.append(collectedPartialResult);
2627 }
2628
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002629 // Derive some new keys for backward compaibility
2630 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2631 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2632 int32_t defaultBoost[1] = {100};
2633 captureResult.mMetadata.update(
2634 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2635 defaultBoost, 1);
2636 }
2637
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002638 captureResult.mMetadata.sort();
2639
2640 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002641 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2642 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002643 SET_ERR("No timestamp provided by HAL for frame %d!",
2644 frameNumber);
2645 return;
2646 }
2647
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002648 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2649 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2650
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002651 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002652}
2653
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002654/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655 * Camera HAL device callback methods
2656 */
2657
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002658void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002659 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002660
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002661 status_t res;
2662
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002663 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002664 if (result->result == NULL && result->num_output_buffers == 0 &&
2665 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002666 SET_ERR("No result data provided by HAL for frame %d",
2667 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002668 return;
2669 }
Zhijun He204e3292014-07-14 17:09:23 -07002670
2671 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2672 // partial_result to 1 when metadata is included in this result.
2673 if (!mUsePartialResult &&
2674 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2675 result->result != NULL &&
2676 result->partial_result != 1) {
2677 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2678 " if partial result is not supported",
2679 frameNumber, result->partial_result);
2680 return;
2681 }
2682
2683 bool isPartialResult = false;
2684 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002685 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002686 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002687
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002688 // Get shutter timestamp and resultExtras from list of in-flight requests,
2689 // where it was added by the shutter notification for this frame. If the
2690 // shutter timestamp isn't received yet, append the output buffers to the
2691 // in-flight request and they will be returned when the shutter timestamp
2692 // arrives. Update the in-flight status and remove the in-flight entry if
2693 // all result data and shutter timestamp have been received.
2694 nsecs_t shutterTimestamp = 0;
2695
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002696 {
2697 Mutex::Autolock l(mInFlightLock);
2698 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2699 if (idx == NAME_NOT_FOUND) {
2700 SET_ERR("Unknown frame number for capture result: %d",
2701 frameNumber);
2702 return;
2703 }
2704 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002705 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2706 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002707 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002708 __FUNCTION__, request.resultExtras.requestId,
2709 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002710 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002711 // Always update the partial count to the latest one if it's not 0
2712 // (buffers only). When framework aggregates adjacent partial results
2713 // into one, the latest partial count will be used.
2714 if (result->partial_result != 0)
2715 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002716
2717 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002718 if (mUsePartialResult && result->result != NULL) {
2719 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2720 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2721 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2722 " the range of [1, %d] when metadata is included in the result",
2723 frameNumber, result->partial_result, mNumPartialResults);
2724 return;
2725 }
2726 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002727 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002728 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002729 }
Zhijun He204e3292014-07-14 17:09:23 -07002730 } else {
2731 camera_metadata_ro_entry_t partialResultEntry;
2732 res = find_camera_metadata_ro_entry(result->result,
2733 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2734 if (res != NAME_NOT_FOUND &&
2735 partialResultEntry.count > 0 &&
2736 partialResultEntry.data.u8[0] ==
2737 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2738 // A partial result. Flag this as such, and collect this
2739 // set of metadata into the in-flight entry.
2740 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002741 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002742 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002743 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002744 ANDROID_QUIRKS_PARTIAL_RESULT);
2745 }
2746 }
2747
Shuzhen Wang4a472662017-02-26 23:29:04 -08002748 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002749 // Send partial capture result
2750 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2751 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002752 }
2753 }
2754
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002755 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002756 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002757
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002758 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002759 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 if (request.haveResultMetadata) {
2761 SET_ERR("Called multiple times with metadata for frame %d",
2762 frameNumber);
2763 return;
2764 }
Zhijun He204e3292014-07-14 17:09:23 -07002765 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002766 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002767 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002768 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002769 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002770 request.haveResultMetadata = true;
2771 }
2772
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002773 uint32_t numBuffersReturned = result->num_output_buffers;
2774 if (result->input_buffer != NULL) {
2775 if (hasInputBufferInRequest) {
2776 numBuffersReturned += 1;
2777 } else {
2778 ALOGW("%s: Input buffer should be NULL if there is no input"
2779 " buffer sent in the request",
2780 __FUNCTION__);
2781 }
2782 }
2783 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002784 if (request.numBuffersLeft < 0) {
2785 SET_ERR("Too many buffers returned for frame %d",
2786 frameNumber);
2787 return;
2788 }
2789
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002790 camera_metadata_ro_entry_t entry;
2791 res = find_camera_metadata_ro_entry(result->result,
2792 ANDROID_SENSOR_TIMESTAMP, &entry);
2793 if (res == OK && entry.count == 1) {
2794 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002795 }
2796
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002797 // If shutter event isn't received yet, append the output buffers to
2798 // the in-flight request. Otherwise, return the output buffers to
2799 // streams.
2800 if (shutterTimestamp == 0) {
2801 request.pendingOutputBuffers.appendArray(result->output_buffers,
2802 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002803 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002804 returnOutputBuffers(result->output_buffers,
2805 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002806 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002807
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002808 if (result->result != NULL && !isPartialResult) {
2809 if (shutterTimestamp == 0) {
2810 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002811 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002812 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002813 CameraMetadata metadata;
2814 metadata = result->result;
2815 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002816 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2817 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002818 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002819 }
2820
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002821 removeInFlightRequestIfReadyLocked(idx);
2822 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002823
Zhijun Hef0d962a2014-06-30 10:24:11 -07002824 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002825 if (hasInputBufferInRequest) {
2826 Camera3Stream *stream =
2827 Camera3Stream::cast(result->input_buffer->stream);
2828 res = stream->returnInputBuffer(*(result->input_buffer));
2829 // Note: stream may be deallocated at this point, if this buffer was the
2830 // last reference to it.
2831 if (res != OK) {
2832 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2833 " its stream:%s (%d)", __FUNCTION__,
2834 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002835 }
2836 } else {
2837 ALOGW("%s: Input buffer should be NULL if there is no input"
2838 " buffer sent in the request, skipping input buffer return.",
2839 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002840 }
2841 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002842}
2843
2844void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002845 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002846 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002847 {
2848 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002849 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002850 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002851
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002852 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002853 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002854 return;
2855 }
2856
2857 switch (msg->type) {
2858 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002860 break;
2861 }
2862 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002863 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002864 break;
2865 }
2866 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002867 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002868 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002869 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002870}
2871
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002872void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002873 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002874
2875 // Map camera HAL error codes to ICameraDeviceCallback error codes
2876 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002877 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002878 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002879 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002881 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002882 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002883 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002884 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002885 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002886 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002887 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002888 };
2889
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002890 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002891 ((msg.error_code >= 0) &&
2892 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2893 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002894 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002895
2896 int streamId = 0;
2897 if (msg.error_stream != NULL) {
2898 Camera3Stream *stream =
2899 Camera3Stream::cast(msg.error_stream);
2900 streamId = stream->getId();
2901 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002902 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2903 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002904 streamId, msg.error_code);
2905
2906 CaptureResultExtras resultExtras;
2907 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002908 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002909 // SET_ERR calls notifyError
2910 SET_ERR("Camera HAL reported serious device error");
2911 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002912 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2913 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2914 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002915 {
2916 Mutex::Autolock l(mInFlightLock);
2917 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2918 if (idx >= 0) {
2919 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2920 r.requestStatus = msg.error_code;
2921 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002922 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2923 errorCode) {
2924 // In case of missing result check whether the buffers
2925 // returned. If they returned, then remove inflight
2926 // request.
2927 removeInFlightRequestIfReadyLocked(idx);
2928 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002929 } else {
2930 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002931 ALOGE("Camera %s: %s: cannot find in-flight request on "
2932 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002933 resultExtras.frameNumber);
2934 }
2935 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002936 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002937 if (listener != NULL) {
2938 listener->notifyError(errorCode, resultExtras);
2939 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002940 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002941 }
2942 break;
2943 default:
2944 // SET_ERR calls notifyError
2945 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2946 break;
2947 }
2948}
2949
2950void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002951 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002952 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002953
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002954 // Set timestamp for the request in the in-flight tracking
2955 // and get the request ID to send upstream
2956 {
2957 Mutex::Autolock l(mInFlightLock);
2958 idx = mInFlightMap.indexOfKey(msg.frame_number);
2959 if (idx >= 0) {
2960 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002961
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002962 // Verify ordering of shutter notifications
2963 {
2964 Mutex::Autolock l(mOutputLock);
2965 // TODO: need to track errors for tighter bounds on expected frame number.
2966 if (r.hasInputBuffer) {
2967 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2968 SET_ERR("Shutter notification out-of-order. Expected "
2969 "notification for frame %d, got frame %d",
2970 mNextReprocessShutterFrameNumber, msg.frame_number);
2971 return;
2972 }
2973 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2974 } else {
2975 if (msg.frame_number < mNextShutterFrameNumber) {
2976 SET_ERR("Shutter notification out-of-order. Expected "
2977 "notification for frame %d, got frame %d",
2978 mNextShutterFrameNumber, msg.frame_number);
2979 return;
2980 }
2981 mNextShutterFrameNumber = msg.frame_number + 1;
2982 }
2983 }
2984
Shuzhen Wang4a472662017-02-26 23:29:04 -08002985 r.shutterTimestamp = msg.timestamp;
2986 if (r.hasCallback) {
2987 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002988 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002989 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002990 // Call listener, if any
2991 if (listener != NULL) {
2992 listener->notifyShutter(r.resultExtras, msg.timestamp);
2993 }
2994 // send pending result and buffers
2995 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2996 r.collectedPartialResult, msg.frame_number,
2997 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002998 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002999 returnOutputBuffers(r.pendingOutputBuffers.array(),
3000 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3001 r.pendingOutputBuffers.clear();
3002
3003 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003004 }
3005 }
3006 if (idx < 0) {
3007 SET_ERR("Shutter notification for non-existent frame number %d",
3008 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003009 }
3010}
3011
3012
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003013CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003014 ALOGV("%s", __FUNCTION__);
3015
Igor Murashkin1e479c02013-09-06 16:55:14 -07003016 CameraMetadata retVal;
3017
3018 if (mRequestThread != NULL) {
3019 retVal = mRequestThread->getLatestRequest();
3020 }
3021
Igor Murashkin1e479c02013-09-06 16:55:14 -07003022 return retVal;
3023}
3024
Jianing Weicb0652e2014-03-12 18:29:36 -07003025
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003026void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3027 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3028 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3029}
3030
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003031/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003032 * HalInterface inner class methods
3033 */
3034
3035Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3036 mHal3Device(device) {}
3037
3038Camera3Device::HalInterface::HalInterface(sp<ICameraDeviceSession> &session) :
3039 mHal3Device(nullptr),
3040 mHidlSession(session) {}
3041
3042Camera3Device::HalInterface::HalInterface() :
3043 mHal3Device(nullptr) {}
3044
3045Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003046 mHal3Device(other.mHal3Device),
3047 mHidlSession(other.mHidlSession) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003048
3049bool Camera3Device::HalInterface::valid() {
3050 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3051}
3052
3053void Camera3Device::HalInterface::clear() {
3054 mHal3Device = nullptr;
3055 mHidlSession.clear();
3056}
3057
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003058bool Camera3Device::HalInterface::supportBatchRequest() {
3059 return mHidlSession != nullptr;
3060}
3061
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003062status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3063 camera3_request_template_t templateId,
3064 /*out*/ camera_metadata_t **requestTemplate) {
3065 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3066 if (!valid()) return INVALID_OPERATION;
3067 status_t res = OK;
3068
3069 if (mHal3Device != nullptr) {
3070 const camera_metadata *r;
3071 r = mHal3Device->ops->construct_default_request_settings(
3072 mHal3Device, templateId);
3073 if (r == nullptr) return BAD_VALUE;
3074 *requestTemplate = clone_camera_metadata(r);
3075 if (requestTemplate == nullptr) {
3076 ALOGE("%s: Unable to clone camera metadata received from HAL",
3077 __FUNCTION__);
3078 return INVALID_OPERATION;
3079 }
3080 } else {
3081 common::V1_0::Status status;
3082 RequestTemplate id;
3083 switch (templateId) {
3084 case CAMERA3_TEMPLATE_PREVIEW:
3085 id = RequestTemplate::PREVIEW;
3086 break;
3087 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3088 id = RequestTemplate::STILL_CAPTURE;
3089 break;
3090 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3091 id = RequestTemplate::VIDEO_RECORD;
3092 break;
3093 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3094 id = RequestTemplate::VIDEO_SNAPSHOT;
3095 break;
3096 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3097 id = RequestTemplate::ZERO_SHUTTER_LAG;
3098 break;
3099 case CAMERA3_TEMPLATE_MANUAL:
3100 id = RequestTemplate::MANUAL;
3101 break;
3102 default:
3103 // Unknown template ID
3104 return BAD_VALUE;
3105 }
3106 mHidlSession->constructDefaultRequestSettings(id,
3107 [&status, &requestTemplate]
3108 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3109 status = s;
3110 if (status == common::V1_0::Status::OK) {
3111 const camera_metadata *r =
3112 reinterpret_cast<const camera_metadata_t*>(request.data());
3113 size_t expectedSize = request.size();
3114 int ret = validate_camera_metadata_structure(r, &expectedSize);
3115 if (ret == OK) {
3116 *requestTemplate = clone_camera_metadata(r);
3117 if (*requestTemplate == nullptr) {
3118 ALOGE("%s: Unable to clone camera metadata received from HAL",
3119 __FUNCTION__);
3120 status = common::V1_0::Status::INTERNAL_ERROR;
3121 }
3122 } else {
3123 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3124 status = common::V1_0::Status::INTERNAL_ERROR;
3125 }
3126 }
3127 });
3128 res = CameraProviderManager::mapToStatusT(status);
3129 }
3130 return res;
3131}
3132
3133status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3134 ATRACE_NAME("CameraHal::configureStreams");
3135 if (!valid()) return INVALID_OPERATION;
3136 status_t res = OK;
3137
3138 if (mHal3Device != nullptr) {
3139 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3140 } else {
3141 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003142 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003143 StreamConfiguration requestedConfiguration;
3144 requestedConfiguration.streams.resize(config->num_streams);
3145 for (size_t i = 0; i < config->num_streams; i++) {
3146 Stream &dst = requestedConfiguration.streams[i];
3147 camera3_stream_t *src = config->streams[i];
3148
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003149 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3150 cam3stream->setBufferFreedListener(this);
3151 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003152 StreamType streamType;
3153 switch (src->stream_type) {
3154 case CAMERA3_STREAM_OUTPUT:
3155 streamType = StreamType::OUTPUT;
3156 break;
3157 case CAMERA3_STREAM_INPUT:
3158 streamType = StreamType::INPUT;
3159 break;
3160 default:
3161 ALOGE("%s: Stream %d: Unsupported stream type %d",
3162 __FUNCTION__, streamId, config->streams[i]->stream_type);
3163 return BAD_VALUE;
3164 }
3165 dst.id = streamId;
3166 dst.streamType = streamType;
3167 dst.width = src->width;
3168 dst.height = src->height;
3169 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003170 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003171 dst.dataSpace = mapToHidlDataspace(src->data_space);
3172 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003173
3174 activeStreams.insert(streamId);
3175 // Create Buffer ID map if necessary
3176 if (mBufferIdMaps.count(streamId) == 0) {
3177 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3178 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003179 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003180 // remove BufferIdMap for deleted streams
3181 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3182 int streamId = it->first;
3183 bool active = activeStreams.count(streamId) > 0;
3184 if (!active) {
3185 it = mBufferIdMaps.erase(it);
3186 } else {
3187 ++it;
3188 }
3189 }
3190
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003191 res = mapToStreamConfigurationMode(
3192 (camera3_stream_configuration_mode_t) config->operation_mode,
3193 /*out*/ &requestedConfiguration.operationMode);
3194 if (res != OK) {
3195 return res;
3196 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003197
3198 // Invoke configureStreams
3199
3200 HalStreamConfiguration finalConfiguration;
3201 common::V1_0::Status status;
3202 mHidlSession->configureStreams(requestedConfiguration,
3203 [&status, &finalConfiguration]
3204 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3205 finalConfiguration = halConfiguration;
3206 status = s;
3207 });
3208 if (status != common::V1_0::Status::OK ) {
3209 return CameraProviderManager::mapToStatusT(status);
3210 }
3211
3212 // And convert output stream configuration from HIDL
3213
3214 for (size_t i = 0; i < config->num_streams; i++) {
3215 camera3_stream_t *dst = config->streams[i];
3216 int streamId = Camera3Stream::cast(dst)->getId();
3217
3218 // Start scan at i, with the assumption that the stream order matches
3219 size_t realIdx = i;
3220 bool found = false;
3221 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3222 if (finalConfiguration.streams[realIdx].id == streamId) {
3223 found = true;
3224 break;
3225 }
3226 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3227 }
3228 if (!found) {
3229 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3230 __FUNCTION__, streamId);
3231 return INVALID_OPERATION;
3232 }
3233 HalStream &src = finalConfiguration.streams[realIdx];
3234
3235 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3236 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3237 if (dst->format != overrideFormat) {
3238 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3239 streamId, dst->format);
3240 }
3241 } else {
3242 // Override allowed with IMPLEMENTATION_DEFINED
3243 dst->format = overrideFormat;
3244 }
3245
3246 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3247 if (src.producerUsage != 0) {
3248 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3249 __FUNCTION__, streamId);
3250 return INVALID_OPERATION;
3251 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003252 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003253 } else {
3254 // OUTPUT
3255 if (src.consumerUsage != 0) {
3256 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3257 __FUNCTION__, streamId);
3258 return INVALID_OPERATION;
3259 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003260 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003261 }
3262 dst->max_buffers = src.maxBuffers;
3263 }
3264 }
3265 return res;
3266}
3267
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003268void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3269 /*out*/device::V3_2::CaptureRequest* captureRequest,
3270 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3271
3272 if (captureRequest == nullptr || handlesCreated == nullptr) {
3273 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3274 __FUNCTION__, captureRequest, handlesCreated);
3275 return;
3276 }
3277
3278 captureRequest->frameNumber = request->frame_number;
3279 // A null request settings maps to a size-0 CameraMetadata
3280 if (request->settings != nullptr) {
3281 captureRequest->settings.setToExternal(
3282 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3283 get_camera_metadata_size(request->settings));
3284 }
3285
3286 {
3287 std::lock_guard<std::mutex> lock(mInflightLock);
3288 if (request->input_buffer != nullptr) {
3289 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3290 buffer_handle_t buf = *(request->input_buffer->buffer);
3291 auto pair = getBufferId(buf, streamId);
3292 bool isNewBuffer = pair.first;
3293 uint64_t bufferId = pair.second;
3294 captureRequest->inputBuffer.streamId = streamId;
3295 captureRequest->inputBuffer.bufferId = bufferId;
3296 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3297 captureRequest->inputBuffer.status = BufferStatus::OK;
3298 native_handle_t *acquireFence = nullptr;
3299 if (request->input_buffer->acquire_fence != -1) {
3300 acquireFence = native_handle_create(1,0);
3301 acquireFence->data[0] = request->input_buffer->acquire_fence;
3302 handlesCreated->push_back(acquireFence);
3303 }
3304 captureRequest->inputBuffer.acquireFence = acquireFence;
3305 captureRequest->inputBuffer.releaseFence = nullptr;
3306
3307 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3308 request->input_buffer->buffer,
3309 request->input_buffer->acquire_fence);
3310 } else {
3311 captureRequest->inputBuffer.streamId = -1;
3312 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3313 }
3314
3315 captureRequest->outputBuffers.resize(request->num_output_buffers);
3316 for (size_t i = 0; i < request->num_output_buffers; i++) {
3317 const camera3_stream_buffer_t *src = request->output_buffers + i;
3318 StreamBuffer &dst = captureRequest->outputBuffers[i];
3319 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3320 buffer_handle_t buf = *(src->buffer);
3321 auto pair = getBufferId(buf, streamId);
3322 bool isNewBuffer = pair.first;
3323 dst.streamId = streamId;
3324 dst.bufferId = pair.second;
3325 dst.buffer = isNewBuffer ? buf : nullptr;
3326 dst.status = BufferStatus::OK;
3327 native_handle_t *acquireFence = nullptr;
3328 if (src->acquire_fence != -1) {
3329 acquireFence = native_handle_create(1,0);
3330 acquireFence->data[0] = src->acquire_fence;
3331 handlesCreated->push_back(acquireFence);
3332 }
3333 dst.acquireFence = acquireFence;
3334 dst.releaseFence = nullptr;
3335
3336 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3337 src->buffer, src->acquire_fence);
3338 }
3339 }
3340}
3341
3342status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3343 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3344 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3345 if (!valid()) return INVALID_OPERATION;
3346
3347 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3348 size_t batchSize = requests.size();
3349 captureRequests.resize(batchSize);
3350 std::vector<native_handle_t*> handlesCreated;
3351
3352 for (size_t i = 0; i < batchSize; i++) {
3353 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3354 }
3355
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003356 std::vector<device::V3_2::BufferCache> cachesToRemove;
3357 {
3358 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3359 for (auto& pair : mFreedBuffers) {
3360 // The stream might have been removed since onBufferFreed
3361 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3362 cachesToRemove.push_back({pair.first, pair.second});
3363 }
3364 }
3365 mFreedBuffers.clear();
3366 }
3367
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003368 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3369 *numRequestProcessed = 0;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003370 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003371 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3372 status = s;
3373 *numRequestProcessed = n;
3374 });
3375
3376 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3377 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3378 __FUNCTION__, *numRequestProcessed, batchSize);
3379 status = common::V1_0::Status::INTERNAL_ERROR;
3380 }
3381
3382 for (auto& handle : handlesCreated) {
3383 native_handle_delete(handle);
3384 }
3385 return CameraProviderManager::mapToStatusT(status);
3386}
3387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003388status_t Camera3Device::HalInterface::processCaptureRequest(
3389 camera3_capture_request_t *request) {
3390 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003391 if (!valid()) return INVALID_OPERATION;
3392 status_t res = OK;
3393
3394 if (mHal3Device != nullptr) {
3395 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3396 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003397 uint32_t numRequestProcessed = 0;
3398 std::vector<camera3_capture_request_t*> requests(1);
3399 requests[0] = request;
3400 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003401 }
3402 return res;
3403}
3404
3405status_t Camera3Device::HalInterface::flush() {
3406 ATRACE_NAME("CameraHal::flush");
3407 if (!valid()) return INVALID_OPERATION;
3408 status_t res = OK;
3409
3410 if (mHal3Device != nullptr) {
3411 res = mHal3Device->ops->flush(mHal3Device);
3412 } else {
3413 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3414 }
3415 return res;
3416}
3417
3418status_t Camera3Device::HalInterface::dump(int fd) {
3419 ATRACE_NAME("CameraHal::dump");
3420 if (!valid()) return INVALID_OPERATION;
3421 status_t res = OK;
3422
3423 if (mHal3Device != nullptr) {
3424 mHal3Device->ops->dump(mHal3Device, fd);
3425 } else {
3426 // Handled by CameraProviderManager::dump
3427 }
3428 return res;
3429}
3430
3431status_t Camera3Device::HalInterface::close() {
3432 ATRACE_NAME("CameraHal::close()");
3433 if (!valid()) return INVALID_OPERATION;
3434 status_t res = OK;
3435
3436 if (mHal3Device != nullptr) {
3437 mHal3Device->common.close(&mHal3Device->common);
3438 } else {
3439 mHidlSession->close();
3440 }
3441 return res;
3442}
3443
3444status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003445 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003446 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003447 auto pair = std::make_pair(buffer, acquireFence);
3448 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003449 return OK;
3450}
3451
3452status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003453 int32_t frameNumber, int32_t streamId,
3454 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003455 std::lock_guard<std::mutex> lock(mInflightLock);
3456
3457 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3458 auto it = mInflightBufferMap.find(key);
3459 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003460 auto pair = it->second;
3461 *buffer = pair.first;
3462 int acquireFence = pair.second;
3463 if (acquireFence > 0) {
3464 ::close(acquireFence);
3465 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003466 mInflightBufferMap.erase(it);
3467 return OK;
3468}
3469
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003470std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3471 const buffer_handle_t& buf, int streamId) {
3472 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3473
3474 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3475 auto it = bIdMap.find(buf);
3476 if (it == bIdMap.end()) {
3477 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003478 ALOGV("stream %d now have %zu buffer caches, buf %p",
3479 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003480 return std::make_pair(true, mNextBufferId - 1);
3481 } else {
3482 return std::make_pair(false, it->second);
3483 }
3484}
3485
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003486void Camera3Device::HalInterface::onBufferFreed(
3487 int streamId, const native_handle_t* handle) {
3488 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3489 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3490 auto mapIt = mBufferIdMaps.find(streamId);
3491 if (mapIt == mBufferIdMaps.end()) {
3492 // streamId might be from a deleted stream here
3493 ALOGI("%s: stream %d has been removed",
3494 __FUNCTION__, streamId);
3495 return;
3496 }
3497 BufferIdMap& bIdMap = mapIt->second;
3498 auto it = bIdMap.find(handle);
3499 if (it == bIdMap.end()) {
3500 ALOGW("%s: cannot find buffer %p in stream %d",
3501 __FUNCTION__, handle, streamId);
3502 return;
3503 } else {
3504 bufferId = it->second;
3505 bIdMap.erase(it);
3506 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3507 __FUNCTION__, streamId, bIdMap.size(), handle);
3508 }
3509 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3510}
3511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003512/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003513 * RequestThread inner class methods
3514 */
3515
3516Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003517 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003518 HalInterface* interface,
3519 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003520 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003521 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003522 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003523 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003524 mInterface(interface),
3525 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003526 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003527 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003528 mReconfigured(false),
3529 mDoPause(false),
3530 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003531 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003532 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003533 mCurrentAfTriggerId(0),
3534 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003535 mRepeatingLastFrameNumber(
3536 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003537 mAeLockAvailable(aeLockAvailable),
3538 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003539 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003540}
3541
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003542Camera3Device::RequestThread::~RequestThread() {}
3543
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003544void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003545 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003546 Mutex::Autolock l(mRequestLock);
3547 mListener = listener;
3548}
3549
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003550void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003551 Mutex::Autolock l(mRequestLock);
3552 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003553 // Prepare video stream for high speed recording.
3554 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003555}
3556
Jianing Wei90e59c92014-03-12 18:29:36 -07003557status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003558 List<sp<CaptureRequest> > &requests,
3559 /*out*/
3560 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003561 Mutex::Autolock l(mRequestLock);
3562 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3563 ++it) {
3564 mRequestQueue.push_back(*it);
3565 }
3566
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003567 if (lastFrameNumber != NULL) {
3568 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3569 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3570 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3571 *lastFrameNumber);
3572 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003573
Jianing Wei90e59c92014-03-12 18:29:36 -07003574 unpauseForNewRequests();
3575
3576 return OK;
3577}
3578
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003579
3580status_t Camera3Device::RequestThread::queueTrigger(
3581 RequestTrigger trigger[],
3582 size_t count) {
3583
3584 Mutex::Autolock l(mTriggerMutex);
3585 status_t ret;
3586
3587 for (size_t i = 0; i < count; ++i) {
3588 ret = queueTriggerLocked(trigger[i]);
3589
3590 if (ret != OK) {
3591 return ret;
3592 }
3593 }
3594
3595 return OK;
3596}
3597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003598const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3599 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003600 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003601 if (d != nullptr) return d->mId;
3602 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003603}
3604
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003605status_t Camera3Device::RequestThread::queueTriggerLocked(
3606 RequestTrigger trigger) {
3607
3608 uint32_t tag = trigger.metadataTag;
3609 ssize_t index = mTriggerMap.indexOfKey(tag);
3610
3611 switch (trigger.getTagType()) {
3612 case TYPE_BYTE:
3613 // fall-through
3614 case TYPE_INT32:
3615 break;
3616 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003617 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3618 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003619 return INVALID_OPERATION;
3620 }
3621
3622 /**
3623 * Collect only the latest trigger, since we only have 1 field
3624 * in the request settings per trigger tag, and can't send more than 1
3625 * trigger per request.
3626 */
3627 if (index != NAME_NOT_FOUND) {
3628 mTriggerMap.editValueAt(index) = trigger;
3629 } else {
3630 mTriggerMap.add(tag, trigger);
3631 }
3632
3633 return OK;
3634}
3635
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003636status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003637 const RequestList &requests,
3638 /*out*/
3639 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003640 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003641 if (lastFrameNumber != NULL) {
3642 *lastFrameNumber = mRepeatingLastFrameNumber;
3643 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003644 mRepeatingRequests.clear();
3645 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3646 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003647
3648 unpauseForNewRequests();
3649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003650 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003651 return OK;
3652}
3653
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003654bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003655 if (mRepeatingRequests.empty()) {
3656 return false;
3657 }
3658 int32_t requestId = requestIn->mResultExtras.requestId;
3659 const RequestList &repeatRequests = mRepeatingRequests;
3660 // All repeating requests are guaranteed to have same id so only check first quest
3661 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3662 return (firstRequest->mResultExtras.requestId == requestId);
3663}
3664
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003665status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003666 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003667 return clearRepeatingRequestsLocked(lastFrameNumber);
3668
3669}
3670
3671status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003672 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003673 if (lastFrameNumber != NULL) {
3674 *lastFrameNumber = mRepeatingLastFrameNumber;
3675 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003676 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003677 return OK;
3678}
3679
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003680status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003681 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003682 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003683 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003684
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003685 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003686
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003687 // Send errors for all requests pending in the request queue, including
3688 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003689 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003690 if (listener != NULL) {
3691 for (RequestList::iterator it = mRequestQueue.begin();
3692 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003693 // Abort the input buffers for reprocess requests.
3694 if ((*it)->mInputStream != NULL) {
3695 camera3_stream_buffer_t inputBuffer;
3696 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3697 if (res != OK) {
3698 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3699 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3700 } else {
3701 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3702 if (res != OK) {
3703 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3704 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3705 }
3706 }
3707 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003708 // Set the frame number this request would have had, if it
3709 // had been submitted; this frame number will not be reused.
3710 // The requestId and burstId fields were set when the request was
3711 // submitted originally (in convertMetadataListToRequestListLocked)
3712 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003715 }
3716 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003717 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003718
3719 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003720 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003721 if (lastFrameNumber != NULL) {
3722 *lastFrameNumber = mRepeatingLastFrameNumber;
3723 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003724 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003725 return OK;
3726}
3727
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003728status_t Camera3Device::RequestThread::flush() {
3729 ATRACE_CALL();
3730 Mutex::Autolock l(mFlushLock);
3731
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003732 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3733 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003734 }
3735
3736 return -ENOTSUP;
3737}
3738
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003739void Camera3Device::RequestThread::setPaused(bool paused) {
3740 Mutex::Autolock l(mPauseLock);
3741 mDoPause = paused;
3742 mDoPauseSignal.signal();
3743}
3744
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003745status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3746 int32_t requestId, nsecs_t timeout) {
3747 Mutex::Autolock l(mLatestRequestMutex);
3748 status_t res;
3749 while (mLatestRequestId != requestId) {
3750 nsecs_t startTime = systemTime();
3751
3752 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3753 if (res != OK) return res;
3754
3755 timeout -= (systemTime() - startTime);
3756 }
3757
3758 return OK;
3759}
3760
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003761void Camera3Device::RequestThread::requestExit() {
3762 // Call parent to set up shutdown
3763 Thread::requestExit();
3764 // The exit from any possible waits
3765 mDoPauseSignal.signal();
3766 mRequestSignal.signal();
3767}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003768
Chien-Yu Chend196d612015-06-22 19:49:01 -07003769
3770/**
3771 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3772 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3773 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3774 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3775 * request.
3776 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003777void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003778 request->mAeTriggerCancelOverride.applyAeLock = false;
3779 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3780
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003781 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003782 return;
3783 }
3784
3785 camera_metadata_entry_t aePrecaptureTrigger =
3786 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3787 if (aePrecaptureTrigger.count > 0 &&
3788 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3789 // Always override CANCEL to IDLE
3790 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3791 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3792 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3793 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3794 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3795
3796 if (mAeLockAvailable == true) {
3797 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3798 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3799 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3800 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3801 request->mAeTriggerCancelOverride.applyAeLock = true;
3802 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3803 }
3804 }
3805 }
3806}
3807
3808/**
3809 * Override result metadata for cancelling AE precapture trigger applied in
3810 * handleAePrecaptureCancelRequest().
3811 */
3812void Camera3Device::overrideResultForPrecaptureCancel(
3813 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3814 if (aeTriggerCancelOverride.applyAeLock) {
3815 // Only devices <= v3.2 should have this override
3816 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3817 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3818 }
3819
3820 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3821 // Only devices <= v3.2 should have this override
3822 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3823 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3824 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3825 }
3826}
3827
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003828void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003829 bool surfaceAbandoned = false;
3830 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003831 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003832 {
3833 Mutex::Autolock l(mRequestLock);
3834 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3835 // repeating requests.
3836 for (const auto& request : mRepeatingRequests) {
3837 for (const auto& s : request->mOutputStreams) {
3838 if (s->isAbandoned()) {
3839 surfaceAbandoned = true;
3840 clearRepeatingRequestsLocked(&lastFrameNumber);
3841 break;
3842 }
3843 }
3844 if (surfaceAbandoned) {
3845 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003846 }
3847 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003848 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003849 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003850
3851 if (listener != NULL && surfaceAbandoned) {
3852 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003853 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003854}
3855
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003856bool Camera3Device::RequestThread::sendRequestsBatch() {
3857 status_t res;
3858 size_t batchSize = mNextRequests.size();
3859 std::vector<camera3_capture_request_t*> requests(batchSize);
3860 uint32_t numRequestProcessed = 0;
3861 for (size_t i = 0; i < batchSize; i++) {
3862 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3863 }
3864
3865 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3866 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3867
3868 bool triggerRemoveFailed = false;
3869 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3870 for (size_t i = 0; i < numRequestProcessed; i++) {
3871 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3872 nextRequest.submitted = true;
3873
3874
3875 // Update the latest request sent to HAL
3876 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3877 Mutex::Autolock al(mLatestRequestMutex);
3878
3879 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3880 mLatestRequest.acquire(cloned);
3881
3882 sp<Camera3Device> parent = mParent.promote();
3883 if (parent != NULL) {
3884 parent->monitorMetadata(TagMonitor::REQUEST,
3885 nextRequest.halRequest.frame_number,
3886 0, mLatestRequest);
3887 }
3888 }
3889
3890 if (nextRequest.halRequest.settings != NULL) {
3891 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3892 }
3893
3894 if (!triggerRemoveFailed) {
3895 // Remove any previously queued triggers (after unlock)
3896 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3897 if (removeTriggerRes != OK) {
3898 triggerRemoveFailed = true;
3899 triggerFailedRequest = nextRequest;
3900 }
3901 }
3902 }
3903
3904 if (triggerRemoveFailed) {
3905 SET_ERR("RequestThread: Unable to remove triggers "
3906 "(capture request %d, HAL device: %s (%d)",
3907 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3908 cleanUpFailedRequests(/*sendRequestError*/ false);
3909 return false;
3910 }
3911
3912 if (res != OK) {
3913 // Should only get a failure here for malformed requests or device-level
3914 // errors, so consider all errors fatal. Bad metadata failures should
3915 // come through notify.
3916 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3917 mNextRequests[numRequestProcessed].halRequest.frame_number,
3918 strerror(-res), res);
3919 cleanUpFailedRequests(/*sendRequestError*/ false);
3920 return false;
3921 }
3922 return true;
3923}
3924
3925bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3926 status_t res;
3927
3928 for (auto& nextRequest : mNextRequests) {
3929 // Submit request and block until ready for next one
3930 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3931 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3932
3933 if (res != OK) {
3934 // Should only get a failure here for malformed requests or device-level
3935 // errors, so consider all errors fatal. Bad metadata failures should
3936 // come through notify.
3937 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3938 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3939 res);
3940 cleanUpFailedRequests(/*sendRequestError*/ false);
3941 return false;
3942 }
3943
3944 // Mark that the request has be submitted successfully.
3945 nextRequest.submitted = true;
3946
3947 // Update the latest request sent to HAL
3948 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3949 Mutex::Autolock al(mLatestRequestMutex);
3950
3951 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3952 mLatestRequest.acquire(cloned);
3953
3954 sp<Camera3Device> parent = mParent.promote();
3955 if (parent != NULL) {
3956 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3957 0, mLatestRequest);
3958 }
3959 }
3960
3961 if (nextRequest.halRequest.settings != NULL) {
3962 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3963 }
3964
3965 // Remove any previously queued triggers (after unlock)
3966 res = removeTriggers(mPrevRequest);
3967 if (res != OK) {
3968 SET_ERR("RequestThread: Unable to remove triggers "
3969 "(capture request %d, HAL device: %s (%d)",
3970 nextRequest.halRequest.frame_number, strerror(-res), res);
3971 cleanUpFailedRequests(/*sendRequestError*/ false);
3972 return false;
3973 }
3974 }
3975 return true;
3976}
3977
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003978bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003979 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003980 status_t res;
3981
3982 // Handle paused state.
3983 if (waitIfPaused()) {
3984 return true;
3985 }
3986
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003987 // Wait for the next batch of requests.
3988 waitForNextRequestBatch();
3989 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003990 return true;
3991 }
3992
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003993 // Get the latest request ID, if any
3994 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003995 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003996 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003997 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003998 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003999 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004000 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4001 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004002 }
4003
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004004 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004005 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004006 if (res == TIMED_OUT) {
4007 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004008 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004009 // Check if any stream is abandoned.
4010 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004011 return true;
4012 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004013 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004014 return false;
4015 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004016
Zhijun Hecc27e112013-10-03 16:12:43 -07004017 // Inform waitUntilRequestProcessed thread of a new request ID
4018 {
4019 Mutex::Autolock al(mLatestRequestMutex);
4020
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004021 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004022 mLatestRequestSignal.signal();
4023 }
4024
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004025 // Submit a batch of requests to HAL.
4026 // Use flush lock only when submitting multilple requests in a batch.
4027 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4028 // which may take a long time to finish so synchronizing flush() and
4029 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4030 // For now, only synchronize for high speed recording and we should figure something out for
4031 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004032 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004033
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004034 if (useFlushLock) {
4035 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004036 }
4037
Zhijun Hef0645c12016-08-02 00:58:11 -07004038 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004039 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004040
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004041 bool submitRequestSuccess = false;
4042 if (mInterface->supportBatchRequest()) {
4043 submitRequestSuccess = sendRequestsBatch();
4044 } else {
4045 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004046 }
4047
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004048 if (useFlushLock) {
4049 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004050 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004051
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004052 // Unset as current request
4053 {
4054 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004055 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004056 }
4057
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004058 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004059}
4060
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004061status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004062 ATRACE_CALL();
4063
Shuzhen Wang4a472662017-02-26 23:29:04 -08004064 for (size_t i = 0; i < mNextRequests.size(); i++) {
4065 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004066 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4067 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4068 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4069
4070 // Prepare a request to HAL
4071 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4072
4073 // Insert any queued triggers (before metadata is locked)
4074 status_t res = insertTriggers(captureRequest);
4075
4076 if (res < 0) {
4077 SET_ERR("RequestThread: Unable to insert triggers "
4078 "(capture request %d, HAL device: %s (%d)",
4079 halRequest->frame_number, strerror(-res), res);
4080 return INVALID_OPERATION;
4081 }
4082 int triggerCount = res;
4083 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4084 mPrevTriggers = triggerCount;
4085
4086 // If the request is the same as last, or we had triggers last time
4087 if (mPrevRequest != captureRequest || triggersMixedIn) {
4088 /**
4089 * HAL workaround:
4090 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4091 */
4092 res = addDummyTriggerIds(captureRequest);
4093 if (res != OK) {
4094 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4095 "(capture request %d, HAL device: %s (%d)",
4096 halRequest->frame_number, strerror(-res), res);
4097 return INVALID_OPERATION;
4098 }
4099
4100 /**
4101 * The request should be presorted so accesses in HAL
4102 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4103 */
4104 captureRequest->mSettings.sort();
4105 halRequest->settings = captureRequest->mSettings.getAndLock();
4106 mPrevRequest = captureRequest;
4107 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4108
4109 IF_ALOGV() {
4110 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4111 find_camera_metadata_ro_entry(
4112 halRequest->settings,
4113 ANDROID_CONTROL_AF_TRIGGER,
4114 &e
4115 );
4116 if (e.count > 0) {
4117 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4118 __FUNCTION__,
4119 halRequest->frame_number,
4120 e.data.u8[0]);
4121 }
4122 }
4123 } else {
4124 // leave request.settings NULL to indicate 'reuse latest given'
4125 ALOGVV("%s: Request settings are REUSED",
4126 __FUNCTION__);
4127 }
4128
4129 uint32_t totalNumBuffers = 0;
4130
4131 // Fill in buffers
4132 if (captureRequest->mInputStream != NULL) {
4133 halRequest->input_buffer = &captureRequest->mInputBuffer;
4134 totalNumBuffers += 1;
4135 } else {
4136 halRequest->input_buffer = NULL;
4137 }
4138
4139 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4140 captureRequest->mOutputStreams.size());
4141 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004142 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4143 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004144
4145 // Prepare video buffers for high speed recording on the first video request.
4146 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4147 // Only try to prepare video stream on the first video request.
4148 mPrepareVideoStream = false;
4149
4150 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4151 while (res == NOT_ENOUGH_DATA) {
4152 res = outputStream->prepareNextBuffer();
4153 }
4154 if (res != OK) {
4155 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4156 __FUNCTION__, strerror(-res), res);
4157 outputStream->cancelPrepare();
4158 }
4159 }
4160
Shuzhen Wang4a472662017-02-26 23:29:04 -08004161 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4162 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004163 if (res != OK) {
4164 // Can't get output buffer from gralloc queue - this could be due to
4165 // abandoned queue or other consumer misbehavior, so not a fatal
4166 // error
4167 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4168 " %s (%d)", strerror(-res), res);
4169
4170 return TIMED_OUT;
4171 }
4172 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004173
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004174 }
4175 totalNumBuffers += halRequest->num_output_buffers;
4176
4177 // Log request in the in-flight queue
4178 sp<Camera3Device> parent = mParent.promote();
4179 if (parent == NULL) {
4180 // Should not happen, and nowhere to send errors to, so just log it
4181 CLOGE("RequestThread: Parent is gone");
4182 return INVALID_OPERATION;
4183 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004184
4185 // If this request list is for constrained high speed recording (not
4186 // preview), and the current request is not the last one in the batch,
4187 // do not send callback to the app.
4188 bool hasCallback = true;
4189 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4190 hasCallback = false;
4191 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004192 res = parent->registerInFlight(halRequest->frame_number,
4193 totalNumBuffers, captureRequest->mResultExtras,
4194 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004195 captureRequest->mAeTriggerCancelOverride,
4196 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004197 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4198 ", burstId = %" PRId32 ".",
4199 __FUNCTION__,
4200 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4201 captureRequest->mResultExtras.burstId);
4202 if (res != OK) {
4203 SET_ERR("RequestThread: Unable to register new in-flight request:"
4204 " %s (%d)", strerror(-res), res);
4205 return INVALID_OPERATION;
4206 }
4207 }
4208
4209 return OK;
4210}
4211
Igor Murashkin1e479c02013-09-06 16:55:14 -07004212CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4213 Mutex::Autolock al(mLatestRequestMutex);
4214
4215 ALOGV("RequestThread::%s", __FUNCTION__);
4216
4217 return mLatestRequest;
4218}
4219
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004220bool Camera3Device::RequestThread::isStreamPending(
4221 sp<Camera3StreamInterface>& stream) {
4222 Mutex::Autolock l(mRequestLock);
4223
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004224 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004225 if (!nextRequest.submitted) {
4226 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4227 if (stream == s) return true;
4228 }
4229 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004230 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004231 }
4232
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004233 for (const auto& request : mRequestQueue) {
4234 for (const auto& s : request->mOutputStreams) {
4235 if (stream == s) return true;
4236 }
4237 if (stream == request->mInputStream) return true;
4238 }
4239
4240 for (const auto& request : mRepeatingRequests) {
4241 for (const auto& s : request->mOutputStreams) {
4242 if (stream == s) return true;
4243 }
4244 if (stream == request->mInputStream) return true;
4245 }
4246
4247 return false;
4248}
Jianing Weicb0652e2014-03-12 18:29:36 -07004249
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004250void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4251 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004252 return;
4253 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004254
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004255 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004256 // Skip the ones that have been submitted successfully.
4257 if (nextRequest.submitted) {
4258 continue;
4259 }
4260
4261 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4262 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4263 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4264
4265 if (halRequest->settings != NULL) {
4266 captureRequest->mSettings.unlock(halRequest->settings);
4267 }
4268
4269 if (captureRequest->mInputStream != NULL) {
4270 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4271 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4272 }
4273
4274 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4275 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4276 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4277 }
4278
4279 if (sendRequestError) {
4280 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004281 sp<NotificationListener> listener = mListener.promote();
4282 if (listener != NULL) {
4283 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004284 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004285 captureRequest->mResultExtras);
4286 }
4287 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004288
4289 // Remove yet-to-be submitted inflight request from inflightMap
4290 {
4291 sp<Camera3Device> parent = mParent.promote();
4292 if (parent != NULL) {
4293 Mutex::Autolock l(parent->mInFlightLock);
4294 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4295 if (idx >= 0) {
4296 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4297 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4298 parent->removeInFlightMapEntryLocked(idx);
4299 }
4300 }
4301 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004302 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004303
4304 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004305 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306}
4307
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004308void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 // Optimized a bit for the simple steady-state case (single repeating
4310 // request), to avoid putting that request in the queue temporarily.
4311 Mutex::Autolock l(mRequestLock);
4312
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004313 assert(mNextRequests.empty());
4314
4315 NextRequest nextRequest;
4316 nextRequest.captureRequest = waitForNextRequestLocked();
4317 if (nextRequest.captureRequest == nullptr) {
4318 return;
4319 }
4320
4321 nextRequest.halRequest = camera3_capture_request_t();
4322 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004323 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004324
4325 // Wait for additional requests
4326 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4327
4328 for (size_t i = 1; i < batchSize; i++) {
4329 NextRequest additionalRequest;
4330 additionalRequest.captureRequest = waitForNextRequestLocked();
4331 if (additionalRequest.captureRequest == nullptr) {
4332 break;
4333 }
4334
4335 additionalRequest.halRequest = camera3_capture_request_t();
4336 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004337 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004338 }
4339
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004340 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004341 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004342 mNextRequests.size(), batchSize);
4343 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004344 }
4345
4346 return;
4347}
4348
4349sp<Camera3Device::CaptureRequest>
4350 Camera3Device::RequestThread::waitForNextRequestLocked() {
4351 status_t res;
4352 sp<CaptureRequest> nextRequest;
4353
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004354 while (mRequestQueue.empty()) {
4355 if (!mRepeatingRequests.empty()) {
4356 // Always atomically enqueue all requests in a repeating request
4357 // list. Guarantees a complete in-sequence set of captures to
4358 // application.
4359 const RequestList &requests = mRepeatingRequests;
4360 RequestList::const_iterator firstRequest =
4361 requests.begin();
4362 nextRequest = *firstRequest;
4363 mRequestQueue.insert(mRequestQueue.end(),
4364 ++firstRequest,
4365 requests.end());
4366 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004367
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004368 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004369
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004370 break;
4371 }
4372
4373 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4374
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004375 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4376 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004377 Mutex::Autolock pl(mPauseLock);
4378 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004379 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004381 // Let the tracker know
4382 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4383 if (statusTracker != 0) {
4384 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4385 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004386 }
4387 // Stop waiting for now and let thread management happen
4388 return NULL;
4389 }
4390 }
4391
4392 if (nextRequest == NULL) {
4393 // Don't have a repeating request already in hand, so queue
4394 // must have an entry now.
4395 RequestList::iterator firstRequest =
4396 mRequestQueue.begin();
4397 nextRequest = *firstRequest;
4398 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004399 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4400 sp<NotificationListener> listener = mListener.promote();
4401 if (listener != NULL) {
4402 listener->notifyRequestQueueEmpty();
4403 }
4404 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004405 }
4406
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004407 // In case we've been unpaused by setPaused clearing mDoPause, need to
4408 // update internal pause state (capture/setRepeatingRequest unpause
4409 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004410 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004411 if (mPaused) {
4412 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4413 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4414 if (statusTracker != 0) {
4415 statusTracker->markComponentActive(mStatusId);
4416 }
4417 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 mPaused = false;
4419
4420 // Check if we've reconfigured since last time, and reset the preview
4421 // request if so. Can't use 'NULL request == repeat' across configure calls.
4422 if (mReconfigured) {
4423 mPrevRequest.clear();
4424 mReconfigured = false;
4425 }
4426
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004427 if (nextRequest != NULL) {
4428 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004429 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4430 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004431
4432 // Since RequestThread::clear() removes buffers from the input stream,
4433 // get the right buffer here before unlocking mRequestLock
4434 if (nextRequest->mInputStream != NULL) {
4435 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4436 if (res != OK) {
4437 // Can't get input buffer from gralloc queue - this could be due to
4438 // disconnected queue or other producer misbehavior, so not a fatal
4439 // error
4440 ALOGE("%s: Can't get input buffer, skipping request:"
4441 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004442
4443 sp<NotificationListener> listener = mListener.promote();
4444 if (listener != NULL) {
4445 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004446 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004447 nextRequest->mResultExtras);
4448 }
4449 return NULL;
4450 }
4451 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004452 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004453
4454 handleAePrecaptureCancelRequest(nextRequest);
4455
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004456 return nextRequest;
4457}
4458
4459bool Camera3Device::RequestThread::waitIfPaused() {
4460 status_t res;
4461 Mutex::Autolock l(mPauseLock);
4462 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004463 if (mPaused == false) {
4464 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004465 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4466 // Let the tracker know
4467 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4468 if (statusTracker != 0) {
4469 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4470 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004471 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004472
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004473 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004474 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004475 return true;
4476 }
4477 }
4478 // We don't set mPaused to false here, because waitForNextRequest needs
4479 // to further manage the paused state in case of starvation.
4480 return false;
4481}
4482
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004483void Camera3Device::RequestThread::unpauseForNewRequests() {
4484 // With work to do, mark thread as unpaused.
4485 // If paused by request (setPaused), don't resume, to avoid
4486 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004487 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004488 Mutex::Autolock p(mPauseLock);
4489 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004490 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4491 if (mPaused) {
4492 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4493 if (statusTracker != 0) {
4494 statusTracker->markComponentActive(mStatusId);
4495 }
4496 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004497 mPaused = false;
4498 }
4499}
4500
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004501void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4502 sp<Camera3Device> parent = mParent.promote();
4503 if (parent != NULL) {
4504 va_list args;
4505 va_start(args, fmt);
4506
4507 parent->setErrorStateV(fmt, args);
4508
4509 va_end(args);
4510 }
4511}
4512
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004513status_t Camera3Device::RequestThread::insertTriggers(
4514 const sp<CaptureRequest> &request) {
4515
4516 Mutex::Autolock al(mTriggerMutex);
4517
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004518 sp<Camera3Device> parent = mParent.promote();
4519 if (parent == NULL) {
4520 CLOGE("RequestThread: Parent is gone");
4521 return DEAD_OBJECT;
4522 }
4523
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004524 CameraMetadata &metadata = request->mSettings;
4525 size_t count = mTriggerMap.size();
4526
4527 for (size_t i = 0; i < count; ++i) {
4528 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004529 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004530
4531 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4532 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4533 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004534 if (isAeTrigger) {
4535 request->mResultExtras.precaptureTriggerId = triggerId;
4536 mCurrentPreCaptureTriggerId = triggerId;
4537 } else {
4538 request->mResultExtras.afTriggerId = triggerId;
4539 mCurrentAfTriggerId = triggerId;
4540 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004541 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4542 continue; // Trigger ID tag is deprecated since device HAL 3.2
4543 }
4544 }
4545
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004546 camera_metadata_entry entry = metadata.find(tag);
4547
4548 if (entry.count > 0) {
4549 /**
4550 * Already has an entry for this trigger in the request.
4551 * Rewrite it with our requested trigger value.
4552 */
4553 RequestTrigger oldTrigger = trigger;
4554
4555 oldTrigger.entryValue = entry.data.u8[0];
4556
4557 mTriggerReplacedMap.add(tag, oldTrigger);
4558 } else {
4559 /**
4560 * More typical, no trigger entry, so we just add it
4561 */
4562 mTriggerRemovedMap.add(tag, trigger);
4563 }
4564
4565 status_t res;
4566
4567 switch (trigger.getTagType()) {
4568 case TYPE_BYTE: {
4569 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4570 res = metadata.update(tag,
4571 &entryValue,
4572 /*count*/1);
4573 break;
4574 }
4575 case TYPE_INT32:
4576 res = metadata.update(tag,
4577 &trigger.entryValue,
4578 /*count*/1);
4579 break;
4580 default:
4581 ALOGE("%s: Type not supported: 0x%x",
4582 __FUNCTION__,
4583 trigger.getTagType());
4584 return INVALID_OPERATION;
4585 }
4586
4587 if (res != OK) {
4588 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4589 ", value %d", __FUNCTION__, trigger.getTagName(),
4590 trigger.entryValue);
4591 return res;
4592 }
4593
4594 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4595 trigger.getTagName(),
4596 trigger.entryValue);
4597 }
4598
4599 mTriggerMap.clear();
4600
4601 return count;
4602}
4603
4604status_t Camera3Device::RequestThread::removeTriggers(
4605 const sp<CaptureRequest> &request) {
4606 Mutex::Autolock al(mTriggerMutex);
4607
4608 CameraMetadata &metadata = request->mSettings;
4609
4610 /**
4611 * Replace all old entries with their old values.
4612 */
4613 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4614 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4615
4616 status_t res;
4617
4618 uint32_t tag = trigger.metadataTag;
4619 switch (trigger.getTagType()) {
4620 case TYPE_BYTE: {
4621 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4622 res = metadata.update(tag,
4623 &entryValue,
4624 /*count*/1);
4625 break;
4626 }
4627 case TYPE_INT32:
4628 res = metadata.update(tag,
4629 &trigger.entryValue,
4630 /*count*/1);
4631 break;
4632 default:
4633 ALOGE("%s: Type not supported: 0x%x",
4634 __FUNCTION__,
4635 trigger.getTagType());
4636 return INVALID_OPERATION;
4637 }
4638
4639 if (res != OK) {
4640 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4641 ", trigger value %d", __FUNCTION__,
4642 trigger.getTagName(), trigger.entryValue);
4643 return res;
4644 }
4645 }
4646 mTriggerReplacedMap.clear();
4647
4648 /**
4649 * Remove all new entries.
4650 */
4651 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4652 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4653 status_t res = metadata.erase(trigger.metadataTag);
4654
4655 if (res != OK) {
4656 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4657 ", trigger value %d", __FUNCTION__,
4658 trigger.getTagName(), trigger.entryValue);
4659 return res;
4660 }
4661 }
4662 mTriggerRemovedMap.clear();
4663
4664 return OK;
4665}
4666
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004667status_t Camera3Device::RequestThread::addDummyTriggerIds(
4668 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004669 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004670 static const int32_t dummyTriggerId = 1;
4671 status_t res;
4672
4673 CameraMetadata &metadata = request->mSettings;
4674
4675 // If AF trigger is active, insert a dummy AF trigger ID if none already
4676 // exists
4677 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4678 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4679 if (afTrigger.count > 0 &&
4680 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4681 afId.count == 0) {
4682 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4683 if (res != OK) return res;
4684 }
4685
4686 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4687 // if none already exists
4688 camera_metadata_entry pcTrigger =
4689 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4690 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4691 if (pcTrigger.count > 0 &&
4692 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4693 pcId.count == 0) {
4694 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4695 &dummyTriggerId, 1);
4696 if (res != OK) return res;
4697 }
4698
4699 return OK;
4700}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004701
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004702/**
4703 * PreparerThread inner class methods
4704 */
4705
4706Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004707 Thread(/*canCallJava*/false), mListener(nullptr),
4708 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004709}
4710
4711Camera3Device::PreparerThread::~PreparerThread() {
4712 Thread::requestExitAndWait();
4713 if (mCurrentStream != nullptr) {
4714 mCurrentStream->cancelPrepare();
4715 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4716 mCurrentStream.clear();
4717 }
4718 clear();
4719}
4720
Ruben Brunkc78ac262015-08-13 17:58:46 -07004721status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004722 status_t res;
4723
4724 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004725 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004726
Ruben Brunkc78ac262015-08-13 17:58:46 -07004727 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004728 if (res == OK) {
4729 // No preparation needed, fire listener right off
4730 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004731 if (listener != NULL) {
4732 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004733 }
4734 return OK;
4735 } else if (res != NOT_ENOUGH_DATA) {
4736 return res;
4737 }
4738
4739 // Need to prepare, start up thread if necessary
4740 if (!mActive) {
4741 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4742 // isn't running
4743 Thread::requestExitAndWait();
4744 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4745 if (res != OK) {
4746 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004747 if (listener != NULL) {
4748 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004749 }
4750 return res;
4751 }
4752 mCancelNow = false;
4753 mActive = true;
4754 ALOGV("%s: Preparer stream started", __FUNCTION__);
4755 }
4756
4757 // queue up the work
4758 mPendingStreams.push_back(stream);
4759 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4760
4761 return OK;
4762}
4763
4764status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004765 Mutex::Autolock l(mLock);
4766
4767 for (const auto& stream : mPendingStreams) {
4768 stream->cancelPrepare();
4769 }
4770 mPendingStreams.clear();
4771 mCancelNow = true;
4772
4773 return OK;
4774}
4775
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004776void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004777 Mutex::Autolock l(mLock);
4778 mListener = listener;
4779}
4780
4781bool Camera3Device::PreparerThread::threadLoop() {
4782 status_t res;
4783 {
4784 Mutex::Autolock l(mLock);
4785 if (mCurrentStream == nullptr) {
4786 // End thread if done with work
4787 if (mPendingStreams.empty()) {
4788 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4789 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4790 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4791 mActive = false;
4792 return false;
4793 }
4794
4795 // Get next stream to prepare
4796 auto it = mPendingStreams.begin();
4797 mCurrentStream = *it;
4798 mPendingStreams.erase(it);
4799 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4800 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4801 } else if (mCancelNow) {
4802 mCurrentStream->cancelPrepare();
4803 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4804 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4805 mCurrentStream.clear();
4806 mCancelNow = false;
4807 return true;
4808 }
4809 }
4810
4811 res = mCurrentStream->prepareNextBuffer();
4812 if (res == NOT_ENOUGH_DATA) return true;
4813 if (res != OK) {
4814 // Something bad happened; try to recover by cancelling prepare and
4815 // signalling listener anyway
4816 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4817 mCurrentStream->getId(), res, strerror(-res));
4818 mCurrentStream->cancelPrepare();
4819 }
4820
4821 // This stream has finished, notify listener
4822 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004823 sp<NotificationListener> listener = mListener.promote();
4824 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004825 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4826 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004827 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004828 }
4829
4830 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4831 mCurrentStream.clear();
4832
4833 return true;
4834}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004835
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004836/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004837 * Static callback forwarding methods from HAL to instance
4838 */
4839
4840void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4841 const camera3_capture_result *result) {
4842 Camera3Device *d =
4843 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004844
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004845 d->processCaptureResult(result);
4846}
4847
4848void Camera3Device::sNotify(const camera3_callback_ops *cb,
4849 const camera3_notify_msg *msg) {
4850 Camera3Device *d =
4851 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4852 d->notify(msg);
4853}
4854
4855}; // namespace android