blob: b64488ce25265fdd823909c7bc2e969d2c2741c2 [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
Yifan Hongf79b5542017-04-11 14:44:25 -0700202 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700203 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
204 [&queue](const auto& descriptor) {
205 queue = std::make_shared<RequestMetadataQueue>(descriptor);
206 if (!queue->isValid() || queue->availableToWrite() <= 0) {
207 ALOGE("HAL returns empty request metadata fmq, not use it");
208 queue = nullptr;
209 // don't use the queue onwards.
210 }
211 });
212 if (!requestQueueRet.isOk()) {
213 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
214 requestQueueRet.description().c_str());
Yifan Hongf79b5542017-04-11 14:44:25 -0700215 queue = nullptr;
216 // Don't use the queue onwards.
217 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700218 auto resultQueueRet = session->getCaptureResultMetadataQueue(
219 [&queue = mResultMetadataQueue](const auto& descriptor) {
220 queue = std::make_unique<ResultMetadataQueue>(descriptor);
221 if (!queue->isValid() || queue->availableToWrite() <= 0) {
222 ALOGE("HAL returns empty result metadata fmq, not use it");
223 queue = nullptr;
224 // Don't use the queue onwards.
225 }
226 });
227 if (!resultQueueRet.isOk()) {
228 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
229 resultQueueRet.description().c_str());
230 mResultMetadataQueue = nullptr;
231 // Don't use the queue onwards.
232 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700233
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800234 // TODO: camera service will absorb 3_2/3_3/3_4 differences in the future
235 // for now use 3_4 to keep legacy devices working
236 mDeviceVersion = CAMERA_DEVICE_API_VERSION_3_4;
Yifan Hongf79b5542017-04-11 14:44:25 -0700237 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000238 std::string providerType;
239 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800240
241 return initializeCommonLocked();
242}
243
244status_t Camera3Device::initializeCommonLocked() {
245
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700246 /** Start up status tracker thread */
247 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800248 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700249 if (res != OK) {
250 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
251 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800252 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 mStatusTracker.clear();
254 return res;
255 }
256
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700257 /** Register in-flight map to the status tracker */
258 mInFlightStatusId = mStatusTracker->addComponent();
259
Zhijun He125684a2015-12-26 15:07:30 -0800260 /** Create buffer manager */
261 mBufferManager = new Camera3BufferManager();
262
Emilian Peev71c73a22017-03-21 16:35:51 +0000263 mTagMonitor.initialize(mVendorTagId);
264
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700265 bool aeLockAvailable = false;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 camera_metadata_entry aeLockAvailableEntry = mDeviceInfo.find(
267 ANDROID_CONTROL_AE_LOCK_AVAILABLE);
268 if (aeLockAvailableEntry.count > 0) {
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700269 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] ==
270 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE);
271 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800272
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700273 /** Start up request queue thread */
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800274 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get(), mDeviceVersion,
275 aeLockAvailable);
276 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800277 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700278 SET_ERR_L("Unable to start request queue thread: %s (%d)",
279 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800280 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800281 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800282 return res;
283 }
284
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700285 mPreparerThread = new PreparerThread();
286
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700287 // Determine whether we need to derive sensitivity boost values for older devices.
288 // If post-RAW sensitivity boost range is listed, so should post-raw sensitivity control
289 // be listed (as the default value 100)
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800290 if (mDeviceInfo.exists(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE)) {
Yin-Chia Yeh4c060992016-04-11 17:40:12 -0700291 mDerivePostRawSensKey = true;
292 }
293
Ruben Brunk183f0562015-08-12 12:55:02 -0700294 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800295 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700296 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700297 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800299
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800300 // Measure the clock domain offset between camera and video/hw_composer
301 camera_metadata_entry timestampSource =
302 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
303 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
304 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
305 mTimestampOffset = getMonoToBoottimeOffset();
306 }
307
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700308 // Will the HAL be sending in early partial result metadata?
Zhijun He204e3292014-07-14 17:09:23 -0700309 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
310 camera_metadata_entry partialResultsCount =
311 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
312 if (partialResultsCount.count > 0) {
313 mNumPartialResults = partialResultsCount.data.i32[0];
314 mUsePartialResult = (mNumPartialResults > 1);
315 }
316 } else {
317 camera_metadata_entry partialResultsQuirk =
318 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
319 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
320 mUsePartialResult = true;
321 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700322 }
323
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700324 camera_metadata_entry configs =
325 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
326 for (uint32_t i = 0; i < configs.count; i += 4) {
327 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
328 configs.data.i32[i + 3] ==
329 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
330 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
331 configs.data.i32[i + 2]));
332 }
333 }
334
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800335 return OK;
336}
337
338status_t Camera3Device::disconnect() {
339 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700340 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700342 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700344 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800345
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 {
347 Mutex::Autolock l(mLock);
348 if (mStatus == STATUS_UNINITIALIZED) return res;
349
350 if (mStatus == STATUS_ACTIVE ||
351 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
352 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700353 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700355 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 } else {
357 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
358 if (res != OK) {
359 SET_ERR_L("Timeout waiting for HAL to drain");
360 // Continue to close device even in case of error
361 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800363 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700365 if (mStatus == STATUS_ERROR) {
366 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700367 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700368
369 if (mStatusTracker != NULL) {
370 mStatusTracker->requestExit();
371 }
372
373 if (mRequestThread != NULL) {
374 mRequestThread->requestExit();
375 }
376
377 mOutputStreams.clear();
378 mInputStream.clear();
379 }
380
381 // Joining done without holding mLock, otherwise deadlocks may ensue
382 // as the threads try to access parent state
383 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
384 // HAL may be in a bad state, so waiting for request thread
385 // (which may be stuck in the HAL processCaptureRequest call)
386 // could be dangerous.
387 mRequestThread->join();
388 }
389
390 if (mStatusTracker != NULL) {
391 mStatusTracker->join();
392 }
393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800394 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700395 {
396 Mutex::Autolock l(mLock);
397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800398 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800400 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800401
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800402 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700403 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800404
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700405 // Call close without internal mutex held, as the HAL close may need to
406 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800407 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700408
409 {
410 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800411 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700412 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700413 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800414
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700415 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700416 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800417}
418
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419// For dumping/debugging only -
420// try to acquire a lock a few times, eventually give up to proceed with
421// debug/dump operations
422bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
423 bool gotLock = false;
424 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
425 if (lock.tryLock() == NO_ERROR) {
426 gotLock = true;
427 break;
428 } else {
429 usleep(kDumpSleepDuration);
430 }
431 }
432 return gotLock;
433}
434
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700435Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
436 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
437 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
438 const int STREAM_CONFIGURATION_SIZE = 4;
439 const int STREAM_FORMAT_OFFSET = 0;
440 const int STREAM_WIDTH_OFFSET = 1;
441 const int STREAM_HEIGHT_OFFSET = 2;
442 const int STREAM_IS_INPUT_OFFSET = 3;
443 camera_metadata_ro_entry_t availableStreamConfigs =
444 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
445 if (availableStreamConfigs.count == 0 ||
446 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
447 return Size(0, 0);
448 }
449
450 // Get max jpeg size (area-wise).
451 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
452 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
453 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
454 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
455 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
456 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
457 && format == HAL_PIXEL_FORMAT_BLOB &&
458 (width * height > maxJpegWidth * maxJpegHeight)) {
459 maxJpegWidth = width;
460 maxJpegHeight = height;
461 }
462 }
463 } else {
464 camera_metadata_ro_entry availableJpegSizes =
465 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
466 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
467 return Size(0, 0);
468 }
469
470 // Get max jpeg size (area-wise).
471 for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
472 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
473 > (maxJpegWidth * maxJpegHeight)) {
474 maxJpegWidth = availableJpegSizes.data.i32[i];
475 maxJpegHeight = availableJpegSizes.data.i32[i + 1];
476 }
477 }
478 }
479 return Size(maxJpegWidth, maxJpegHeight);
480}
481
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800482nsecs_t Camera3Device::getMonoToBoottimeOffset() {
483 // try three times to get the clock offset, choose the one
484 // with the minimum gap in measurements.
485 const int tries = 3;
486 nsecs_t bestGap, measured;
487 for (int i = 0; i < tries; ++i) {
488 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
489 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
490 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
491 const nsecs_t gap = tmono2 - tmono;
492 if (i == 0 || gap < bestGap) {
493 bestGap = gap;
494 measured = tbase - ((tmono + tmono2) >> 1);
495 }
496 }
497 return measured;
498}
499
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -0700500/**
501 * Map Android N dataspace definitions back to Android M definitions, for
502 * use with HALv3.3 or older.
503 *
504 * Only map where correspondences exist, and otherwise preserve the value.
505 */
506android_dataspace Camera3Device::mapToLegacyDataspace(android_dataspace dataSpace) {
507 switch (dataSpace) {
508 case HAL_DATASPACE_V0_SRGB_LINEAR:
509 return HAL_DATASPACE_SRGB_LINEAR;
510 case HAL_DATASPACE_V0_SRGB:
511 return HAL_DATASPACE_SRGB;
512 case HAL_DATASPACE_V0_JFIF:
513 return HAL_DATASPACE_JFIF;
514 case HAL_DATASPACE_V0_BT601_625:
515 return HAL_DATASPACE_BT601_625;
516 case HAL_DATASPACE_V0_BT601_525:
517 return HAL_DATASPACE_BT601_525;
518 case HAL_DATASPACE_V0_BT709:
519 return HAL_DATASPACE_BT709;
520 default:
521 return dataSpace;
522 }
523}
524
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800525hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
526 int frameworkFormat) {
527 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
528}
529
530DataspaceFlags Camera3Device::mapToHidlDataspace(
531 android_dataspace dataSpace) {
532 return dataSpace;
533}
534
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700535BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700536 uint32_t usage) {
537 return usage;
538}
539
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800540StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
541 switch (rotation) {
542 case CAMERA3_STREAM_ROTATION_0:
543 return StreamRotation::ROTATION_0;
544 case CAMERA3_STREAM_ROTATION_90:
545 return StreamRotation::ROTATION_90;
546 case CAMERA3_STREAM_ROTATION_180:
547 return StreamRotation::ROTATION_180;
548 case CAMERA3_STREAM_ROTATION_270:
549 return StreamRotation::ROTATION_270;
550 }
551 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
552 return StreamRotation::ROTATION_0;
553}
554
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800555status_t Camera3Device::mapToStreamConfigurationMode(
556 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
557 if (mode == nullptr) return BAD_VALUE;
558 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
559 switch(operationMode) {
560 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
561 *mode = StreamConfigurationMode::NORMAL_MODE;
562 break;
563 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
564 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
565 break;
566 default:
567 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
568 return BAD_VALUE;
569 }
570 } else {
571 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800574}
575
576camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
577 switch (status) {
578 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
579 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
580 }
581 return CAMERA3_BUFFER_STATUS_ERROR;
582}
583
584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700589uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700590 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700591 return usage;
592}
593
594uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Zhijun Hef7da0962014-04-24 13:27:56 -0700599ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700600 // Get max jpeg size (area-wise).
601 Size maxJpegResolution = getMaxJpegResolution();
602 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
604 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700605 return BAD_VALUE;
606 }
607
Zhijun Hef7da0962014-04-24 13:27:56 -0700608 // Get max jpeg buffer size
609 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700610 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
611 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800612 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
613 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 return BAD_VALUE;
615 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800617 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700618
619 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700620 float scaleFactor = ((float) (width * height)) /
621 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800622 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
623 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700624 if (jpegBufferSize > maxJpegBufferSize) {
625 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700626 }
627
628 return jpegBufferSize;
629}
630
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700631ssize_t Camera3Device::getPointCloudBufferSize() const {
632 const int FLOATS_PER_POINT=4;
633 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
634 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
636 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637 return BAD_VALUE;
638 }
639 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
640 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
641 return maxBytesForPointCloud;
642}
643
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800644ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800645 const int PER_CONFIGURATION_SIZE = 3;
646 const int WIDTH_OFFSET = 0;
647 const int HEIGHT_OFFSET = 1;
648 const int SIZE_OFFSET = 2;
649 camera_metadata_ro_entry rawOpaqueSizes =
650 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800651 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800652 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800653 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
654 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800655 return BAD_VALUE;
656 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700657
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800658 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
659 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
660 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
661 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
662 }
663 }
664
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
666 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800667 return BAD_VALUE;
668}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700669
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800670status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
671 ATRACE_CALL();
672 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700673
674 // Try to lock, but continue in case of failure (to avoid blocking in
675 // deadlocks)
676 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
677 bool gotLock = tryLockSpinRightRound(mLock);
678
679 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800680 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
681 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700682 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800683 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
684 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700685
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800686 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700687
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800688 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700689 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800690 int n = args.size();
691 for (int i = 0; i < n; i++) {
692 if (args[i] == templatesOption) {
693 dumpTemplates = true;
694 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700695 if (args[i] == monitorOption) {
696 if (i + 1 < n) {
697 String8 monitorTags = String8(args[i + 1]);
698 if (monitorTags == "off") {
699 mTagMonitor.disableMonitoring();
700 } else {
701 mTagMonitor.parseTagsToMonitor(monitorTags);
702 }
703 } else {
704 mTagMonitor.disableMonitoring();
705 }
706 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800707 }
708
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800709 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800710
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800711 const char *status =
712 mStatus == STATUS_ERROR ? "ERROR" :
713 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700714 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
715 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 mStatus == STATUS_ACTIVE ? "ACTIVE" :
717 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800719 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700720 if (mStatus == STATUS_ERROR) {
721 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
722 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800723 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800724 const char *mode =
725 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
726 mOperatingMode == static_cast<int>(
727 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
728 "CUSTOM";
729 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800730
731 if (mInputStream != NULL) {
732 write(fd, lines.string(), lines.size());
733 mInputStream->dump(fd, args);
734 } else {
735 lines.appendFormat(" No input stream.\n");
736 write(fd, lines.string(), lines.size());
737 }
738 for (size_t i = 0; i < mOutputStreams.size(); i++) {
739 mOutputStreams[i]->dump(fd,args);
740 }
741
Zhijun He431503c2016-03-07 17:30:16 -0800742 if (mBufferManager != NULL) {
743 lines = String8(" Camera3 Buffer Manager:\n");
744 write(fd, lines.string(), lines.size());
745 mBufferManager->dump(fd, args);
746 }
Zhijun He125684a2015-12-26 15:07:30 -0800747
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700748 lines = String8(" In-flight requests:\n");
749 if (mInFlightMap.size() == 0) {
750 lines.append(" None\n");
751 } else {
752 for (size_t i = 0; i < mInFlightMap.size(); i++) {
753 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700754 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700755 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800756 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700757 r.numBuffersLeft);
758 }
759 }
760 write(fd, lines.string(), lines.size());
761
Igor Murashkin1e479c02013-09-06 16:55:14 -0700762 {
763 lines = String8(" Last request sent:\n");
764 write(fd, lines.string(), lines.size());
765
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700766 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700767 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
768 }
769
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800770 if (dumpTemplates) {
771 const char *templateNames[] = {
772 "TEMPLATE_PREVIEW",
773 "TEMPLATE_STILL_CAPTURE",
774 "TEMPLATE_VIDEO_RECORD",
775 "TEMPLATE_VIDEO_SNAPSHOT",
776 "TEMPLATE_ZERO_SHUTTER_LAG",
777 "TEMPLATE_MANUAL"
778 };
779
780 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800781 camera_metadata_t *templateRequest = nullptr;
782 mInterface->constructDefaultRequestSettings(
783 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800784 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800785 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800786 lines.append(" Not supported\n");
787 write(fd, lines.string(), lines.size());
788 } else {
789 write(fd, lines.string(), lines.size());
790 dump_indented_camera_metadata(templateRequest,
791 fd, /*verbosity*/2, /*indentation*/8);
792 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800793 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 }
795 }
796
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700797 mTagMonitor.dumpMonitoredMetadata(fd);
798
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800799 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800800 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800801 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800802 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800803 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800804
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700805 if (gotLock) mLock.unlock();
806 if (gotInterfaceLock) mInterfaceLock.unlock();
807
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800808 return OK;
809}
810
811const CameraMetadata& Camera3Device::info() const {
812 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
814 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700815 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800816 mStatus == STATUS_ERROR ?
817 "when in error state" : "before init");
818 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800819 return mDeviceInfo;
820}
821
Jianing Wei90e59c92014-03-12 18:29:36 -0700822status_t Camera3Device::checkStatusOkToCaptureLocked() {
823 switch (mStatus) {
824 case STATUS_ERROR:
825 CLOGE("Device has encountered a serious error");
826 return INVALID_OPERATION;
827 case STATUS_UNINITIALIZED:
828 CLOGE("Device not initialized");
829 return INVALID_OPERATION;
830 case STATUS_UNCONFIGURED:
831 case STATUS_CONFIGURED:
832 case STATUS_ACTIVE:
833 // OK
834 break;
835 default:
836 SET_ERR_L("Unexpected status: %d", mStatus);
837 return INVALID_OPERATION;
838 }
839 return OK;
840}
841
842status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700843 const List<const CameraMetadata> &metadataList,
844 const std::list<const SurfaceMap> &surfaceMaps,
845 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700846 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700847 if (requestList == NULL) {
848 CLOGE("requestList cannot be NULL.");
849 return BAD_VALUE;
850 }
851
Jianing Weicb0652e2014-03-12 18:29:36 -0700852 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700853 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
854 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
855 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
856 ++metadataIt, ++surfaceMapIt) {
857 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700858 if (newRequest == 0) {
859 CLOGE("Can't create capture request");
860 return BAD_VALUE;
861 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700862
Shuzhen Wang9d066012016-09-30 11:30:20 -0700863 newRequest->mRepeating = repeating;
864
Jianing Weicb0652e2014-03-12 18:29:36 -0700865 // Setup burst Id and request Id
866 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700867 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
868 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700869 CLOGE("RequestID entry exists; but must not be empty in metadata");
870 return BAD_VALUE;
871 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700872 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700873 } else {
874 CLOGE("RequestID does not exist in metadata");
875 return BAD_VALUE;
876 }
877
Jianing Wei90e59c92014-03-12 18:29:36 -0700878 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700879
880 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700881 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700882 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
883 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
884 return BAD_VALUE;
885 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700886
887 // Setup batch size if this is a high speed video recording request.
888 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
889 auto firstRequest = requestList->begin();
890 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
891 if (outputStream->isVideoStream()) {
892 (*firstRequest)->mBatchSize = requestList->size();
893 break;
894 }
895 }
896 }
897
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 return OK;
899}
900
Jianing Weicb0652e2014-03-12 18:29:36 -0700901status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800903
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700904 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700905 std::list<const SurfaceMap> surfaceMaps;
906 convertToRequestList(requests, surfaceMaps, request);
907
908 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
909}
910
911void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
912 std::list<const SurfaceMap>& surfaceMaps,
913 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700914 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700915
916 SurfaceMap surfaceMap;
917 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
918 // With no surface list passed in, stream and surface will have 1-to-1
919 // mapping. So the surface index is 0 for each stream in the surfaceMap.
920 for (size_t i = 0; i < streams.count; i++) {
921 surfaceMap[streams.data.i32[i]].push_back(0);
922 }
923 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800924}
925
Jianing Wei90e59c92014-03-12 18:29:36 -0700926status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700927 const List<const CameraMetadata> &requests,
928 const std::list<const SurfaceMap> &surfaceMaps,
929 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700930 /*out*/
931 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700932 ATRACE_CALL();
933 Mutex::Autolock il(mInterfaceLock);
934 Mutex::Autolock l(mLock);
935
936 status_t res = checkStatusOkToCaptureLocked();
937 if (res != OK) {
938 // error logged by previous call
939 return res;
940 }
941
942 RequestList requestList;
943
Shuzhen Wang0129d522016-10-30 22:43:41 -0700944 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
945 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700946 if (res != OK) {
947 // error logged by previous call
948 return res;
949 }
950
951 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700952 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700953 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700954 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700955 }
956
957 if (res == OK) {
958 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
959 if (res != OK) {
960 SET_ERR_L("Can't transition to active in %f seconds!",
961 kActiveTimeout/1e9);
962 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800963 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700964 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700965 } else {
966 CLOGE("Cannot queue request. Impossible.");
967 return BAD_VALUE;
968 }
969
970 return res;
971}
972
Yifan Honga640c5a2017-04-12 16:30:31 -0700973// Only one processCaptureResult should be called at a time, so
974// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800975hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800976 const hardware::hidl_vec<
977 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700978
979 if (mProcessCaptureResultLock.tryLock() != OK) {
980 // This should never happen; it indicates a wrong client implementation
981 // that doesn't follow the contract. But, we can be tolerant here.
982 ALOGE("%s: callback overlapped! waiting 1s...",
983 __FUNCTION__);
984 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
985 ALOGE("%s: cannot acquire lock in 1s, dropping results",
986 __FUNCTION__);
987 // really don't know what to do, so bail out.
988 return hardware::Void();
989 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800990 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700991 for (const auto& result : results) {
992 processOneCaptureResultLocked(result);
993 }
994 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800995 return hardware::Void();
996}
997
Yifan Honga640c5a2017-04-12 16:30:31 -0700998void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800999 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001000 camera3_capture_result r;
1001 status_t res;
1002 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001003
1004 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
1005 if (result.fmqResultSize > 0) {
1006 resultMetadata.resize(result.fmqResultSize);
1007 if (mResultMetadataQueue == nullptr) {
1008 return; // logged in initialize()
1009 }
1010 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
1011 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
1012 __FUNCTION__, result.frameNumber, result.fmqResultSize);
1013 return;
1014 }
1015 } else {
1016 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
1017 result.result.size());
1018 }
1019
1020 if (resultMetadata.size() != 0) {
1021 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1022 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001023 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
1024 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
1025 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001026 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001027 }
1028 } else {
1029 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001030 }
1031
1032 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1033 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1034 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1035 auto& bDst = outputBuffers[i];
1036 const StreamBuffer &bSrc = result.outputBuffers[i];
1037
1038 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001039 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001040 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1041 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001042 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001043 }
1044 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1045
1046 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001047 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001048 if (res != OK) {
1049 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1050 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001051 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001052 }
1053 bDst.buffer = buffer;
1054 bDst.status = mapHidlBufferStatus(bSrc.status);
1055 bDst.acquire_fence = -1;
1056 if (bSrc.releaseFence == nullptr) {
1057 bDst.release_fence = -1;
1058 } else if (bSrc.releaseFence->numFds == 1) {
1059 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1060 } else {
1061 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1062 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001063 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001064 }
1065 }
1066 r.num_output_buffers = outputBuffers.size();
1067 r.output_buffers = outputBuffers.data();
1068
1069 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001070 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001071 r.input_buffer = nullptr;
1072 } else {
1073 if (mInputStream->getId() != result.inputBuffer.streamId) {
1074 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1075 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001076 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001077 }
1078 inputBuffer.stream = mInputStream->asHalStream();
1079 buffer_handle_t *buffer;
1080 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1081 &buffer);
1082 if (res != OK) {
1083 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1084 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001085 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001086 }
1087 inputBuffer.buffer = buffer;
1088 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1089 inputBuffer.acquire_fence = -1;
1090 if (result.inputBuffer.releaseFence == nullptr) {
1091 inputBuffer.release_fence = -1;
1092 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1093 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1094 } else {
1095 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1096 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001097 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001098 }
1099 r.input_buffer = &inputBuffer;
1100 }
1101
1102 r.partial_result = result.partialResult;
1103
1104 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001105}
1106
1107hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001108 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
1109 for (const auto& msg : msgs) {
1110 notify(msg);
1111 }
1112 return hardware::Void();
1113}
1114
1115void Camera3Device::notify(
1116 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001118 camera3_notify_msg m;
1119 switch (msg.type) {
1120 case MsgType::ERROR:
1121 m.type = CAMERA3_MSG_ERROR;
1122 m.message.error.frame_number = msg.msg.error.frameNumber;
1123 if (msg.msg.error.errorStreamId >= 0) {
1124 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001125 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001126 ALOGE("%s: Frame %d: Invalid error stream id %d",
1127 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001128 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001129 }
1130 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1131 } else {
1132 m.message.error.error_stream = nullptr;
1133 }
1134 switch (msg.msg.error.errorCode) {
1135 case ErrorCode::ERROR_DEVICE:
1136 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1137 break;
1138 case ErrorCode::ERROR_REQUEST:
1139 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1140 break;
1141 case ErrorCode::ERROR_RESULT:
1142 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1143 break;
1144 case ErrorCode::ERROR_BUFFER:
1145 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1146 break;
1147 }
1148 break;
1149 case MsgType::SHUTTER:
1150 m.type = CAMERA3_MSG_SHUTTER;
1151 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1152 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1153 break;
1154 }
1155 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001156}
1157
Jianing Weicb0652e2014-03-12 18:29:36 -07001158status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001159 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001160 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001161 ATRACE_CALL();
1162
Shuzhen Wang0129d522016-10-30 22:43:41 -07001163 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001164}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001165
Jianing Weicb0652e2014-03-12 18:29:36 -07001166status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1167 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001168 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001170 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171 std::list<const SurfaceMap> surfaceMaps;
1172 convertToRequestList(requests, surfaceMaps, request);
1173
1174 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1175 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176}
1177
Jianing Weicb0652e2014-03-12 18:29:36 -07001178status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001179 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001180 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001181 ATRACE_CALL();
1182
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001184}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185
1186sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001187 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188 status_t res;
1189
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001190 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001191 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1192 // so unilaterally select normal operating mode.
1193 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001194 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001196 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001198 } else if (mStatus == STATUS_UNCONFIGURED) {
1199 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 CLOGE("No streams configured");
1201 return NULL;
1202 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 }
1204
Shuzhen Wang0129d522016-10-30 22:43:41 -07001205 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207}
1208
Jianing Weicb0652e2014-03-12 18:29:36 -07001209status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 switch (mStatus) {
1215 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001219 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 case STATUS_UNCONFIGURED:
1222 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 case STATUS_ACTIVE:
1224 // OK
1225 break;
1226 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001227 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 return INVALID_OPERATION;
1229 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001230 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001231
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001232 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233}
1234
1235status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001239 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240}
1241
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001242status_t Camera3Device::createInputStream(
1243 uint32_t width, uint32_t height, int format, int *id) {
1244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001246 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001247 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1248 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001249
1250 status_t res;
1251 bool wasActive = false;
1252
1253 switch (mStatus) {
1254 case STATUS_ERROR:
1255 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1256 return INVALID_OPERATION;
1257 case STATUS_UNINITIALIZED:
1258 ALOGE("%s: Device not initialized", __FUNCTION__);
1259 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001260 case STATUS_UNCONFIGURED:
1261 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001262 // OK
1263 break;
1264 case STATUS_ACTIVE:
1265 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001267 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001268 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001269 return res;
1270 }
1271 wasActive = true;
1272 break;
1273 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275 return INVALID_OPERATION;
1276 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001278
1279 if (mInputStream != 0) {
1280 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1281 return INVALID_OPERATION;
1282 }
1283
1284 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1285 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287
1288 mInputStream = newStream;
1289
1290 *id = mNextStreamId++;
1291
1292 // Continue captures if active at start
1293 if (wasActive) {
1294 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001295 // Reuse current operating mode for new stream config
1296 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001297 if (res != OK) {
1298 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1299 __FUNCTION__, mNextStreamId, strerror(-res), res);
1300 return res;
1301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001302 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303 }
1304
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001305 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 return OK;
1307}
1308
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001309status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001310 uint32_t width, uint32_t height, int format,
1311 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001312 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001313 ATRACE_CALL();
1314
1315 if (consumer == nullptr) {
1316 ALOGE("%s: consumer must not be null", __FUNCTION__);
1317 return BAD_VALUE;
1318 }
1319
1320 std::vector<sp<Surface>> consumers;
1321 consumers.push_back(consumer);
1322
1323 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001324 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325}
1326
1327status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1328 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1329 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001330 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001331 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001332 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001334 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001335 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1336 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001337
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 status_t res;
1339 bool wasActive = false;
1340
1341 switch (mStatus) {
1342 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001343 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001344 return INVALID_OPERATION;
1345 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001346 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001348 case STATUS_UNCONFIGURED:
1349 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350 // OK
1351 break;
1352 case STATUS_ACTIVE:
1353 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001354 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001355 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001356 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 return res;
1358 }
1359 wasActive = true;
1360 break;
1361 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001362 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 return INVALID_OPERATION;
1364 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001365 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366
1367 sp<Camera3OutputStream> newStream;
Zhijun Heedd41ae2016-02-03 14:45:53 -08001368 // Overwrite stream set id to invalid for HAL3.2 or lower, as buffer manager does support
Zhijun He125684a2015-12-26 15:07:30 -08001369 // such devices.
Zhijun Heedd41ae2016-02-03 14:45:53 -08001370 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001371 streamSetId = CAMERA3_STREAM_SET_ID_INVALID;
1372 }
Zhijun He5d677d12016-05-29 16:52:39 -07001373
Shuzhen Wang0129d522016-10-30 22:43:41 -07001374 if (consumers.size() == 0 && !hasDeferredConsumer) {
1375 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1376 return BAD_VALUE;
1377 }
Zhijun He5d677d12016-05-29 16:52:39 -07001378 // HAL3.1 doesn't support deferred consumer stream creation as it requires buffer registration
1379 // which requires a consumer surface to be available.
Shuzhen Wang0129d522016-10-30 22:43:41 -07001380 if (hasDeferredConsumer && mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He5d677d12016-05-29 16:52:39 -07001381 ALOGE("HAL3.1 doesn't support deferred consumer stream creation");
1382 return BAD_VALUE;
1383 }
1384
Shuzhen Wang0129d522016-10-30 22:43:41 -07001385 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001386 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1387 return BAD_VALUE;
1388 }
1389
Eino-Ville Talvala2cbf6ce2016-03-14 13:03:25 -07001390 // Use legacy dataspace values for older HALs
1391 if (mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_3) {
1392 dataSpace = mapToLegacyDataspace(dataSpace);
1393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001395 ssize_t blobBufferSize;
1396 if (dataSpace != HAL_DATASPACE_DEPTH) {
1397 blobBufferSize = getJpegBufferSize(width, height);
1398 if (blobBufferSize <= 0) {
1399 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1400 return BAD_VALUE;
1401 }
1402 } else {
1403 blobBufferSize = getPointCloudBufferSize();
1404 if (blobBufferSize <= 0) {
1405 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1406 return BAD_VALUE;
1407 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001408 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001409 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001410 width, height, blobBufferSize, format, dataSpace, rotation,
1411 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001412 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1413 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1414 if (rawOpaqueBufferSize <= 0) {
1415 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1416 return BAD_VALUE;
1417 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001419 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1420 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001421 } else if (isShared) {
1422 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1423 width, height, format, consumerUsage, dataSpace, rotation,
1424 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001426 newStream = new Camera3OutputStream(mNextStreamId,
1427 width, height, format, consumerUsage, dataSpace, rotation,
1428 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001430 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001431 width, height, format, dataSpace, rotation,
1432 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001434 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001435
Zhijun He125684a2015-12-26 15:07:30 -08001436 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -08001437 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs ( < HAL3.2)
1438 * requires buffers to be statically allocated for internal static buffer registration, while
1439 * the buffers provided by buffer manager are really dynamically allocated. For HAL3.2, because
1440 * not all HAL implementation supports dynamic buffer registeration, exlude it as well.
Zhijun He125684a2015-12-26 15:07:30 -08001441 */
Zhijun Heedd41ae2016-02-03 14:45:53 -08001442 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Zhijun He125684a2015-12-26 15:07:30 -08001443 newStream->setBufferManager(mBufferManager);
1444 }
1445
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 res = mOutputStreams.add(mNextStreamId, newStream);
1447 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001448 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 return res;
1450 }
1451
1452 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001453 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454
1455 // Continue captures if active at start
1456 if (wasActive) {
1457 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001458 // Reuse current operating mode for new stream config
1459 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001461 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1462 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 return res;
1464 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001465 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001467 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001469}
1470
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001472 uint32_t *width, uint32_t *height,
1473 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001475 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 switch (mStatus) {
1479 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001480 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 return INVALID_OPERATION;
1482 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001485 case STATUS_UNCONFIGURED:
1486 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 case STATUS_ACTIVE:
1488 // OK
1489 break;
1490 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001491 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 return INVALID_OPERATION;
1493 }
1494
1495 ssize_t idx = mOutputStreams.indexOfKey(id);
1496 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001497 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return idx;
1499 }
1500
1501 if (width) *width = mOutputStreams[idx]->getWidth();
1502 if (height) *height = mOutputStreams[idx]->getHeight();
1503 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001504 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001506}
1507
1508status_t Camera3Device::setStreamTransform(int id,
1509 int transform) {
1510 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 switch (mStatus) {
1515 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001516 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 return INVALID_OPERATION;
1518 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001519 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 case STATUS_UNCONFIGURED:
1522 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 case STATUS_ACTIVE:
1524 // OK
1525 break;
1526 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 }
1530
1531 ssize_t idx = mOutputStreams.indexOfKey(id);
1532 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001533 CLOGE("Stream %d does not exist",
1534 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 return BAD_VALUE;
1536 }
1537
1538 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001539}
1540
1541status_t Camera3Device::deleteStream(int id) {
1542 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 Mutex::Autolock l(mLock);
1545 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001547 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001548
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 // CameraDevice semantics require device to already be idle before
1550 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001553 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 }
1555
Igor Murashkin2fba5842013-04-22 14:03:54 -07001556 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001557 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 if (mInputStream != NULL && id == mInputStream->getId()) {
1559 deletedStream = mInputStream;
1560 mInputStream.clear();
1561 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001562 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 return BAD_VALUE;
1565 }
Zhijun He5f446352014-01-22 09:49:33 -08001566 }
1567
1568 // Delete output stream or the output part of a bi-directional stream.
1569 if (outputStreamIdx != NAME_NOT_FOUND) {
1570 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001571 mOutputStreams.removeItem(id);
1572 }
1573
1574 // Free up the stream endpoint so that it can be used by some other stream
1575 res = deletedStream->disconnect();
1576 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 // fall through since we want to still list the stream as deleted.
1579 }
1580 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001581 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001582
1583 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001584}
1585
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001586status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001587 ATRACE_CALL();
1588 ALOGV("%s: E", __FUNCTION__);
1589
1590 Mutex::Autolock il(mInterfaceLock);
1591 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001592
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001593 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001594}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001596status_t Camera3Device::getInputBufferProducer(
1597 sp<IGraphicBufferProducer> *producer) {
1598 Mutex::Autolock il(mInterfaceLock);
1599 Mutex::Autolock l(mLock);
1600
1601 if (producer == NULL) {
1602 return BAD_VALUE;
1603 } else if (mInputStream == NULL) {
1604 return INVALID_OPERATION;
1605 }
1606
1607 return mInputStream->getInputBufferProducer(producer);
1608}
1609
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610status_t Camera3Device::createDefaultRequest(int templateId,
1611 CameraMetadata *request) {
1612 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001613 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001614
1615 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1616 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1617 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1618 return BAD_VALUE;
1619 }
1620
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001622 Mutex::Autolock l(mLock);
1623
1624 switch (mStatus) {
1625 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001626 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627 return INVALID_OPERATION;
1628 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001629 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 case STATUS_UNCONFIGURED:
1632 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001633 case STATUS_ACTIVE:
1634 // OK
1635 break;
1636 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001637 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001638 return INVALID_OPERATION;
1639 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001640
Zhijun Hea1530f12014-09-14 12:44:20 -07001641 if (!mRequestTemplateCache[templateId].isEmpty()) {
1642 *request = mRequestTemplateCache[templateId];
1643 return OK;
1644 }
1645
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001646 camera_metadata_t *rawRequest;
1647 status_t res = mInterface->constructDefaultRequestSettings(
1648 (camera3_request_template_t) templateId, &rawRequest);
1649 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001650 ALOGI("%s: template %d is not supported on this camera device",
1651 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001652 return res;
1653 } else if (res != OK) {
1654 CLOGE("Unable to construct request template %d: %s (%d)",
1655 templateId, strerror(-res), res);
1656 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001657 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001658
Emilian Peev71c73a22017-03-21 16:35:51 +00001659 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001660 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001662 // Derive some new keys for backward compatibility
1663 if (mDerivePostRawSensKey && !mRequestTemplateCache[templateId].exists(
1664 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
1665 int32_t defaultBoost[1] = {100};
1666 mRequestTemplateCache[templateId].update(
1667 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1668 defaultBoost, 1);
1669 }
1670
1671 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672 return OK;
1673}
1674
1675status_t Camera3Device::waitUntilDrained() {
1676 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001677 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001678 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001679
Zhijun He69a37482014-03-23 18:44:49 -07001680 return waitUntilDrainedLocked();
1681}
1682
1683status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001684 switch (mStatus) {
1685 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001687 ALOGV("%s: Already idle", __FUNCTION__);
1688 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001689 case STATUS_CONFIGURED:
1690 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001691 case STATUS_ERROR:
1692 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001693 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001694 break;
1695 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001696 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001697 return INVALID_OPERATION;
1698 }
1699
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001700 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001701 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001702 if (res != OK) {
1703 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1704 res);
1705 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 return res;
1707}
1708
Ruben Brunk183f0562015-08-12 12:55:02 -07001709
1710void Camera3Device::internalUpdateStatusLocked(Status status) {
1711 mStatus = status;
1712 mRecentStatusUpdates.add(mStatus);
1713 mStatusChanged.broadcast();
1714}
1715
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001716// Pause to reconfigure
1717status_t Camera3Device::internalPauseAndWaitLocked() {
1718 mRequestThread->setPaused(true);
1719 mPauseStateNotify = true;
1720
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001721 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1723 if (res != OK) {
1724 SET_ERR_L("Can't idle device in %f seconds!",
1725 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726 }
1727
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001728 return res;
1729}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001730
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001731// Resume after internalPauseAndWaitLocked
1732status_t Camera3Device::internalResumeLocked() {
1733 status_t res;
1734
1735 mRequestThread->setPaused(false);
1736
1737 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1738 if (res != OK) {
1739 SET_ERR_L("Can't transition to active in %f seconds!",
1740 kActiveTimeout/1e9);
1741 }
1742 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001743 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744}
1745
Ruben Brunk183f0562015-08-12 12:55:02 -07001746status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001747 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001748
1749 size_t startIndex = 0;
1750 if (mStatusWaiters == 0) {
1751 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1752 // this status list
1753 mRecentStatusUpdates.clear();
1754 } else {
1755 // If other threads are waiting on updates to this status list, set the position of the
1756 // first element that this list will check rather than clearing the list.
1757 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001758 }
1759
Ruben Brunk183f0562015-08-12 12:55:02 -07001760 mStatusWaiters++;
1761
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001762 bool stateSeen = false;
1763 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001764 if (active == (mStatus == STATUS_ACTIVE)) {
1765 // Desired state is current
1766 break;
1767 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768
1769 res = mStatusChanged.waitRelative(mLock, timeout);
1770 if (res != OK) break;
1771
Ruben Brunk183f0562015-08-12 12:55:02 -07001772 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1773 // transitions.
1774 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1775 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1776 __FUNCTION__);
1777
1778 // Encountered desired state since we began waiting
1779 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1781 stateSeen = true;
1782 break;
1783 }
1784 }
1785 } while (!stateSeen);
1786
Ruben Brunk183f0562015-08-12 12:55:02 -07001787 mStatusWaiters--;
1788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 return res;
1790}
1791
1792
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001793status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001794 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001795 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001796
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001797 if (listener != NULL && mListener != NULL) {
1798 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1799 }
1800 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001801 mRequestThread->setNotificationListener(listener);
1802 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001803
1804 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001805}
1806
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001807bool Camera3Device::willNotify3A() {
1808 return false;
1809}
1810
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001811status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001812 status_t res;
1813 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001814
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001815 while (mResultQueue.empty()) {
1816 res = mResultSignal.waitRelative(mOutputLock, timeout);
1817 if (res == TIMED_OUT) {
1818 return res;
1819 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001820 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1821 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001822 return res;
1823 }
1824 }
1825 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001826}
1827
Jianing Weicb0652e2014-03-12 18:29:36 -07001828status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001830 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001831
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001832 if (mResultQueue.empty()) {
1833 return NOT_ENOUGH_DATA;
1834 }
1835
Jianing Weicb0652e2014-03-12 18:29:36 -07001836 if (frame == NULL) {
1837 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1838 return BAD_VALUE;
1839 }
1840
1841 CaptureResult &result = *(mResultQueue.begin());
1842 frame->mResultExtras = result.mResultExtras;
1843 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001844 mResultQueue.erase(mResultQueue.begin());
1845
1846 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001847}
1848
1849status_t Camera3Device::triggerAutofocus(uint32_t id) {
1850 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001851 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001852
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001853 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1854 // Mix-in this trigger into the next request and only the next request.
1855 RequestTrigger trigger[] = {
1856 {
1857 ANDROID_CONTROL_AF_TRIGGER,
1858 ANDROID_CONTROL_AF_TRIGGER_START
1859 },
1860 {
1861 ANDROID_CONTROL_AF_TRIGGER_ID,
1862 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001863 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001864 };
1865
1866 return mRequestThread->queueTrigger(trigger,
1867 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001868}
1869
1870status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1871 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001873
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001874 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1875 // Mix-in this trigger into the next request and only the next request.
1876 RequestTrigger trigger[] = {
1877 {
1878 ANDROID_CONTROL_AF_TRIGGER,
1879 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1880 },
1881 {
1882 ANDROID_CONTROL_AF_TRIGGER_ID,
1883 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001884 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001885 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001887 return mRequestThread->queueTrigger(trigger,
1888 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889}
1890
1891status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1892 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001893 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001895 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1896 // Mix-in this trigger into the next request and only the next request.
1897 RequestTrigger trigger[] = {
1898 {
1899 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1900 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1901 },
1902 {
1903 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1904 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001905 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001906 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001908 return mRequestThread->queueTrigger(trigger,
1909 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001910}
1911
Jianing Weicb0652e2014-03-12 18:29:36 -07001912status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001913 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001914 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001916
Zhijun He7ef20392014-04-21 16:04:17 -07001917 {
1918 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001919 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001920 }
1921
Zhijun He491e3412013-12-27 10:57:44 -08001922 status_t res;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001923 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001924 res = mRequestThread->flush();
Zhijun He491e3412013-12-27 10:57:44 -08001925 } else {
Zhijun He7ef20392014-04-21 16:04:17 -07001926 Mutex::Autolock l(mLock);
Zhijun He69a37482014-03-23 18:44:49 -07001927 res = waitUntilDrainedLocked();
Zhijun He491e3412013-12-27 10:57:44 -08001928 }
1929
1930 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001931}
1932
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001933status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001934 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1935}
1936
1937status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001938 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001939 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001940 Mutex::Autolock il(mInterfaceLock);
1941 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001942
1943 sp<Camera3StreamInterface> stream;
1944 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1945 if (outputStreamIdx == NAME_NOT_FOUND) {
1946 CLOGE("Stream %d does not exist", streamId);
1947 return BAD_VALUE;
1948 }
1949
1950 stream = mOutputStreams.editValueAt(outputStreamIdx);
1951
1952 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001953 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001954 return BAD_VALUE;
1955 }
1956
1957 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001958 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001959 return BAD_VALUE;
1960 }
1961
Ruben Brunkc78ac262015-08-13 17:58:46 -07001962 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001963}
1964
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001965status_t Camera3Device::tearDown(int streamId) {
1966 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001967 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001968 Mutex::Autolock il(mInterfaceLock);
1969 Mutex::Autolock l(mLock);
1970
1971 // Teardown can only be accomplished on devices that don't require register_stream_buffers,
1972 // since we cannot call register_stream_buffers except right after configure_streams.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001973 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001974 ALOGE("%s: Unable to tear down streams on device HAL v%x",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001975 __FUNCTION__, mDeviceVersion);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001976 return NO_INIT;
1977 }
1978
1979 sp<Camera3StreamInterface> stream;
1980 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1981 if (outputStreamIdx == NAME_NOT_FOUND) {
1982 CLOGE("Stream %d does not exist", streamId);
1983 return BAD_VALUE;
1984 }
1985
1986 stream = mOutputStreams.editValueAt(outputStreamIdx);
1987
1988 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1989 CLOGE("Stream %d is a target of a in-progress request", streamId);
1990 return BAD_VALUE;
1991 }
1992
1993 return stream->tearDown();
1994}
1995
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001996status_t Camera3Device::addBufferListenerForStream(int streamId,
1997 wp<Camera3StreamBufferListener> listener) {
1998 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001999 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002000 Mutex::Autolock il(mInterfaceLock);
2001 Mutex::Autolock l(mLock);
2002
2003 sp<Camera3StreamInterface> stream;
2004 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2005 if (outputStreamIdx == NAME_NOT_FOUND) {
2006 CLOGE("Stream %d does not exist", streamId);
2007 return BAD_VALUE;
2008 }
2009
2010 stream = mOutputStreams.editValueAt(outputStreamIdx);
2011 stream->addBufferListener(listener);
2012
2013 return OK;
2014}
2015
Zhijun He204e3292014-07-14 17:09:23 -07002016uint32_t Camera3Device::getDeviceVersion() {
2017 ATRACE_CALL();
2018 Mutex::Autolock il(mInterfaceLock);
2019 return mDeviceVersion;
2020}
2021
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002023 * Methods called by subclasses
2024 */
2025
2026void Camera3Device::notifyStatus(bool idle) {
2027 {
2028 // Need mLock to safely update state and synchronize to current
2029 // state of methods in flight.
2030 Mutex::Autolock l(mLock);
2031 // We can get various system-idle notices from the status tracker
2032 // while starting up. Only care about them if we've actually sent
2033 // in some requests recently.
2034 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2035 return;
2036 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002037 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002038 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07002039 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002040
2041 // Skip notifying listener if we're doing some user-transparent
2042 // state changes
2043 if (mPauseStateNotify) return;
2044 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002045
2046 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002047 {
2048 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002049 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 }
2051 if (idle && listener != NULL) {
2052 listener->notifyIdle();
2053 }
2054}
2055
Shuzhen Wang758c2152017-01-10 18:26:18 -08002056status_t Camera3Device::setConsumerSurfaces(int streamId,
2057 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07002058 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002059 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2060 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07002061 Mutex::Autolock il(mInterfaceLock);
2062 Mutex::Autolock l(mLock);
2063
Shuzhen Wang758c2152017-01-10 18:26:18 -08002064 if (consumers.size() == 0) {
2065 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002066 return BAD_VALUE;
2067 }
2068
2069 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2070 if (idx == NAME_NOT_FOUND) {
2071 CLOGE("Stream %d is unknown", streamId);
2072 return idx;
2073 }
2074 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002075 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002076 if (res != OK) {
2077 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2078 return res;
2079 }
2080
Shuzhen Wang0129d522016-10-30 22:43:41 -07002081 if (stream->isConsumerConfigurationDeferred()) {
2082 if (!stream->isConfiguring()) {
2083 CLOGE("Stream %d was already fully configured.", streamId);
2084 return INVALID_OPERATION;
2085 }
Zhijun He5d677d12016-05-29 16:52:39 -07002086
Shuzhen Wang0129d522016-10-30 22:43:41 -07002087 res = stream->finishConfiguration();
2088 if (res != OK) {
2089 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2090 stream->getId(), strerror(-res), res);
2091 return res;
2092 }
Zhijun He5d677d12016-05-29 16:52:39 -07002093 }
2094
2095 return OK;
2096}
2097
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002098/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002099 * Camera3Device private methods
2100 */
2101
2102sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07002103 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 ATRACE_CALL();
2105 status_t res;
2106
2107 sp<CaptureRequest> newRequest = new CaptureRequest;
2108 newRequest->mSettings = request;
2109
2110 camera_metadata_entry_t inputStreams =
2111 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
2112 if (inputStreams.count > 0) {
2113 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002114 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002115 CLOGE("Request references unknown input stream %d",
2116 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 return NULL;
2118 }
2119 // Lazy completion of stream configuration (allocation/registration)
2120 // on first use
2121 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002122 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002124 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002126 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127 return NULL;
2128 }
2129 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002130 // Check if stream is being prepared
2131 if (mInputStream->isPreparing()) {
2132 CLOGE("Request references an input stream that's being prepared!");
2133 return NULL;
2134 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135
2136 newRequest->mInputStream = mInputStream;
2137 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
2138 }
2139
2140 camera_metadata_entry_t streams =
2141 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2142 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002143 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144 return NULL;
2145 }
2146
2147 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002148 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002150 CLOGE("Request references unknown stream %d",
2151 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002152 return NULL;
2153 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002154 sp<Camera3OutputStreamInterface> stream =
2155 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156
Zhijun He5d677d12016-05-29 16:52:39 -07002157 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002158 auto iter = surfaceMap.find(streams.data.i32[i]);
2159 if (iter != surfaceMap.end()) {
2160 const std::vector<size_t>& surfaces = iter->second;
2161 for (const auto& surface : surfaces) {
2162 if (stream->isConsumerConfigurationDeferred(surface)) {
2163 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2164 "due to deferred consumer", stream->getId(), surface);
2165 return NULL;
2166 }
2167 }
2168 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002169 }
2170
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002171 // Lazy completion of stream configuration (allocation/registration)
2172 // on first use
2173 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002174 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002176 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2177 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002178 return NULL;
2179 }
2180 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002181 // Check if stream is being prepared
2182 if (stream->isPreparing()) {
2183 CLOGE("Request references an output stream that's being prepared!");
2184 return NULL;
2185 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002186
2187 newRequest->mOutputStreams.push(stream);
2188 }
2189 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002190 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191
2192 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002193}
2194
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002195bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2196 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2197 Size size = mSupportedOpaqueInputSizes[i];
2198 if (size.width == width && size.height == height) {
2199 return true;
2200 }
2201 }
2202
2203 return false;
2204}
2205
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002206void Camera3Device::cancelStreamsConfigurationLocked() {
2207 int res = OK;
2208 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2209 res = mInputStream->cancelConfiguration();
2210 if (res != OK) {
2211 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2212 mInputStream->getId(), strerror(-res), res);
2213 }
2214 }
2215
2216 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2217 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2218 if (outputStream->isConfiguring()) {
2219 res = outputStream->cancelConfiguration();
2220 if (res != OK) {
2221 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2222 outputStream->getId(), strerror(-res), res);
2223 }
2224 }
2225 }
2226
2227 // Return state to that at start of call, so that future configures
2228 // properly clean things up
2229 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2230 mNeedConfig = true;
2231}
2232
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002233status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 ATRACE_CALL();
2235 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002236
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002237 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002238 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 return INVALID_OPERATION;
2240 }
2241
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002242 if (operatingMode < 0) {
2243 CLOGE("Invalid operating mode: %d", operatingMode);
2244 return BAD_VALUE;
2245 }
2246
2247 bool isConstrainedHighSpeed =
2248 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2249 operatingMode;
2250
2251 if (mOperatingMode != operatingMode) {
2252 mNeedConfig = true;
2253 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2254 mOperatingMode = operatingMode;
2255 }
2256
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002257 if (!mNeedConfig) {
2258 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2259 return OK;
2260 }
2261
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002262 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2263 // adding a dummy stream instead.
2264 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2265 if (mOutputStreams.size() == 0) {
2266 addDummyStreamLocked();
2267 } else {
2268 tryRemoveDummyStreamLocked();
2269 }
2270
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002271 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002272 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002273
2274 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002275 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2277
2278 Vector<camera3_stream_t*> streams;
2279 streams.setCapacity(config.num_streams);
2280
2281 if (mInputStream != NULL) {
2282 camera3_stream_t *inputStream;
2283 inputStream = mInputStream->startConfiguration();
2284 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002285 CLOGE("Can't start input stream configuration");
2286 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287 return INVALID_OPERATION;
2288 }
2289 streams.add(inputStream);
2290 }
2291
2292 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002293
2294 // Don't configure bidi streams twice, nor add them twice to the list
2295 if (mOutputStreams[i].get() ==
2296 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2297
2298 config.num_streams--;
2299 continue;
2300 }
2301
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302 camera3_stream_t *outputStream;
2303 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2304 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002305 CLOGE("Can't start output stream configuration");
2306 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 return INVALID_OPERATION;
2308 }
2309 streams.add(outputStream);
2310 }
2311
2312 config.streams = streams.editArray();
2313
2314 // Do the HAL configuration; will potentially touch stream
2315 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002316
2317 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002319 if (res == BAD_VALUE) {
2320 // HAL rejected this set of streams as unsupported, clean up config
2321 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002322 CLOGE("Set of requested inputs/outputs not supported by HAL");
2323 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002324 return BAD_VALUE;
2325 } else if (res != OK) {
2326 // Some other kind of error from configure_streams - this is not
2327 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002328 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2329 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002330 return res;
2331 }
2332
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002333 // Finish all stream configuration immediately.
2334 // TODO: Try to relax this later back to lazy completion, which should be
2335 // faster
2336
Igor Murashkin073f8572013-05-02 14:59:28 -07002337 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002338 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002339 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002340 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002341 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002342 cancelStreamsConfigurationLocked();
2343 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002344 }
2345 }
2346
2347 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002348 sp<Camera3OutputStreamInterface> outputStream =
2349 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002350 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002351 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002352 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002353 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002354 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002355 cancelStreamsConfigurationLocked();
2356 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002357 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002358 }
2359 }
2360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 // Request thread needs to know to avoid using repeat-last-settings protocol
2362 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002363 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364
Zhijun He90f7c372016-08-16 16:19:43 -07002365 char value[PROPERTY_VALUE_MAX];
2366 property_get("camera.fifo.disable", value, "0");
2367 int32_t disableFifo = atoi(value);
2368 if (disableFifo != 1) {
2369 // Boost priority of request thread to SCHED_FIFO.
2370 pid_t requestThreadTid = mRequestThread->getTid();
2371 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002372 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002373 if (res != OK) {
2374 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2375 strerror(-res), res);
2376 } else {
2377 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2378 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002379 }
2380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002381 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002383 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384
Ruben Brunk183f0562015-08-12 12:55:02 -07002385 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2386 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002388 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002389
Zhijun He0a210512014-07-24 13:45:15 -07002390 // tear down the deleted streams after configure streams.
2391 mDeletedStreams.clear();
2392
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002394}
2395
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002396status_t Camera3Device::addDummyStreamLocked() {
2397 ATRACE_CALL();
2398 status_t res;
2399
2400 if (mDummyStreamId != NO_STREAM) {
2401 // Should never be adding a second dummy stream when one is already
2402 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002403 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2404 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002405 return INVALID_OPERATION;
2406 }
2407
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002408 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002409
2410 sp<Camera3OutputStreamInterface> dummyStream =
2411 new Camera3DummyStream(mNextStreamId);
2412
2413 res = mOutputStreams.add(mNextStreamId, dummyStream);
2414 if (res < 0) {
2415 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2416 return res;
2417 }
2418
2419 mDummyStreamId = mNextStreamId;
2420 mNextStreamId++;
2421
2422 return OK;
2423}
2424
2425status_t Camera3Device::tryRemoveDummyStreamLocked() {
2426 ATRACE_CALL();
2427 status_t res;
2428
2429 if (mDummyStreamId == NO_STREAM) return OK;
2430 if (mOutputStreams.size() == 1) return OK;
2431
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002432 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002433
2434 // Ok, have a dummy stream and there's at least one other output stream,
2435 // so remove the dummy
2436
2437 sp<Camera3StreamInterface> deletedStream;
2438 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2439 if (outputStreamIdx == NAME_NOT_FOUND) {
2440 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2441 return INVALID_OPERATION;
2442 }
2443
2444 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2445 mOutputStreams.removeItemsAt(outputStreamIdx);
2446
2447 // Free up the stream endpoint so that it can be used by some other stream
2448 res = deletedStream->disconnect();
2449 if (res != OK) {
2450 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2451 // fall through since we want to still list the stream as deleted.
2452 }
2453 mDeletedStreams.add(deletedStream);
2454 mDummyStreamId = NO_STREAM;
2455
2456 return res;
2457}
2458
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002459void Camera3Device::setErrorState(const char *fmt, ...) {
2460 Mutex::Autolock l(mLock);
2461 va_list args;
2462 va_start(args, fmt);
2463
2464 setErrorStateLockedV(fmt, args);
2465
2466 va_end(args);
2467}
2468
2469void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2470 Mutex::Autolock l(mLock);
2471 setErrorStateLockedV(fmt, args);
2472}
2473
2474void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2475 va_list args;
2476 va_start(args, fmt);
2477
2478 setErrorStateLockedV(fmt, args);
2479
2480 va_end(args);
2481}
2482
2483void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002484 // Print out all error messages to log
2485 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002486 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002487
2488 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002489 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002490
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002491 mErrorCause = errorCause;
2492
2493 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002494 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002495
2496 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002497 sp<NotificationListener> listener = mListener.promote();
2498 if (listener != NULL) {
2499 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002500 CaptureResultExtras());
2501 }
2502
2503 // Save stack trace. View by dumping it later.
2504 CameraTraces::saveTrace();
2505 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002506}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002507
2508/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002509 * In-flight request management
2510 */
2511
Jianing Weicb0652e2014-03-12 18:29:36 -07002512status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002513 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002514 const AeTriggerCancelOverride_t &aeTriggerCancelOverride,
2515 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002516 ATRACE_CALL();
2517 Mutex::Autolock l(mInFlightLock);
2518
2519 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002520 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002521 aeTriggerCancelOverride, hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002522 if (res < 0) return res;
2523
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002524 if (mInFlightMap.size() == 1) {
2525 mStatusTracker->markComponentActive(mInFlightStatusId);
2526 }
2527
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002528 return OK;
2529}
2530
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002531void Camera3Device::returnOutputBuffers(
2532 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2533 nsecs_t timestamp) {
2534 for (size_t i = 0; i < numBuffers; i++)
2535 {
2536 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2537 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2538 // Note: stream may be deallocated at this point, if this buffer was
2539 // the last reference to it.
2540 if (res != OK) {
2541 ALOGE("Can't return buffer to its stream: %s (%d)",
2542 strerror(-res), res);
2543 }
2544 }
2545}
2546
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002547void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2548 mInFlightMap.removeItemsAt(idx, 1);
2549
2550 // Indicate idle inFlightMap to the status tracker
2551 if (mInFlightMap.size() == 0) {
2552 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2553 }
2554}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002555
2556void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2557
2558 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2559 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2560
2561 nsecs_t sensorTimestamp = request.sensorTimestamp;
2562 nsecs_t shutterTimestamp = request.shutterTimestamp;
2563
2564 // Check if it's okay to remove the request from InFlightMap:
2565 // In the case of a successful request:
2566 // all input and output buffers, all result metadata, shutter callback
2567 // arrived.
2568 // In the case of a unsuccessful request:
2569 // all input and output buffers arrived.
2570 if (request.numBuffersLeft == 0 &&
2571 (request.requestStatus != OK ||
2572 (request.haveResultMetadata && shutterTimestamp != 0))) {
2573 ATRACE_ASYNC_END("frame capture", frameNumber);
2574
Shuzhen Wang403044a2017-02-26 23:29:04 -08002575 // Sanity check - if sensor timestamp matches shutter timestamp in the
2576 // case of request having callback.
2577 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002578 sensorTimestamp != shutterTimestamp) {
2579 SET_ERR("sensor timestamp (%" PRId64
2580 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2581 sensorTimestamp, frameNumber, shutterTimestamp);
2582 }
2583
2584 // for an unsuccessful request, it may have pending output buffers to
2585 // return.
2586 assert(request.requestStatus != OK ||
2587 request.pendingOutputBuffers.size() == 0);
2588 returnOutputBuffers(request.pendingOutputBuffers.array(),
2589 request.pendingOutputBuffers.size(), 0);
2590
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002591 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002592 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2593 }
2594
2595 // Sanity check - if we have too many in-flight frames, something has
2596 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002597 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002598 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002599 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2600 kInFlightWarnLimitHighSpeed) {
2601 CLOGE("In-flight list too large for high speed configuration: %zu",
2602 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002603 }
2604}
2605
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002606void Camera3Device::insertResultLocked(CaptureResult *result, uint32_t frameNumber,
2607 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2608 if (result == nullptr) return;
2609
Emilian Peev71c73a22017-03-21 16:35:51 +00002610 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2611 result->mMetadata.getAndLock());
2612 set_camera_metadata_vendor_id(meta, mVendorTagId);
2613 result->mMetadata.unlock(meta);
2614
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002615 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2616 (int32_t*)&frameNumber, 1) != OK) {
2617 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2618 return;
2619 }
2620
2621 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2622 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2623 return;
2624 }
2625
2626 overrideResultForPrecaptureCancel(&result->mMetadata, aeTriggerCancelOverride);
2627
2628 // Valid result, insert into queue
2629 List<CaptureResult>::iterator queuedResult =
2630 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2631 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2632 ", burstId = %" PRId32, __FUNCTION__,
2633 queuedResult->mResultExtras.requestId,
2634 queuedResult->mResultExtras.frameNumber,
2635 queuedResult->mResultExtras.burstId);
2636
2637 mResultSignal.signal();
2638}
2639
2640
2641void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
2642 const CaptureResultExtras &resultExtras, uint32_t frameNumber,
2643 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
2644 Mutex::Autolock l(mOutputLock);
2645
2646 CaptureResult captureResult;
2647 captureResult.mResultExtras = resultExtras;
2648 captureResult.mMetadata = partialResult;
2649
2650 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
2651}
2652
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002653
2654void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2655 CaptureResultExtras &resultExtras,
2656 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002657 uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002658 bool reprocess,
2659 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002660 if (pendingMetadata.isEmpty())
2661 return;
2662
2663 Mutex::Autolock l(mOutputLock);
2664
2665 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002666 if (reprocess) {
2667 if (frameNumber < mNextReprocessResultFrameNumber) {
2668 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002669 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002670 frameNumber, mNextReprocessResultFrameNumber);
2671 return;
2672 }
2673 mNextReprocessResultFrameNumber = frameNumber + 1;
2674 } else {
2675 if (frameNumber < mNextResultFrameNumber) {
2676 SET_ERR("Out-of-order capture result metadata submitted! "
2677 "(got frame number %d, expecting %d)",
2678 frameNumber, mNextResultFrameNumber);
2679 return;
2680 }
2681 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002682 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002683
2684 CaptureResult captureResult;
2685 captureResult.mResultExtras = resultExtras;
2686 captureResult.mMetadata = pendingMetadata;
2687
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002688 // Append any previous partials to form a complete result
2689 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2690 captureResult.mMetadata.append(collectedPartialResult);
2691 }
2692
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07002693 // Derive some new keys for backward compaibility
2694 if (mDerivePostRawSensKey && !captureResult.mMetadata.exists(
2695 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST)) {
2696 int32_t defaultBoost[1] = {100};
2697 captureResult.mMetadata.update(
2698 ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2699 defaultBoost, 1);
2700 }
2701
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002702 captureResult.mMetadata.sort();
2703
2704 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002705 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2706 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002707 SET_ERR("No timestamp provided by HAL for frame %d!",
2708 frameNumber);
2709 return;
2710 }
2711
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002712 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2713 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2714
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002715 insertResultLocked(&captureResult, frameNumber, aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002716}
2717
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002718/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002719 * Camera HAL device callback methods
2720 */
2721
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002722void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002723 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002724
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002725 status_t res;
2726
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002727 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002728 if (result->result == NULL && result->num_output_buffers == 0 &&
2729 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002730 SET_ERR("No result data provided by HAL for frame %d",
2731 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002732 return;
2733 }
Zhijun He204e3292014-07-14 17:09:23 -07002734
2735 // For HAL3.2 or above, If HAL doesn't support partial, it must always set
2736 // partial_result to 1 when metadata is included in this result.
2737 if (!mUsePartialResult &&
2738 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
2739 result->result != NULL &&
2740 result->partial_result != 1) {
2741 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2742 " if partial result is not supported",
2743 frameNumber, result->partial_result);
2744 return;
2745 }
2746
2747 bool isPartialResult = false;
2748 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002749 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002750 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002752 // Get shutter timestamp and resultExtras from list of in-flight requests,
2753 // where it was added by the shutter notification for this frame. If the
2754 // shutter timestamp isn't received yet, append the output buffers to the
2755 // in-flight request and they will be returned when the shutter timestamp
2756 // arrives. Update the in-flight status and remove the in-flight entry if
2757 // all result data and shutter timestamp have been received.
2758 nsecs_t shutterTimestamp = 0;
2759
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 {
2761 Mutex::Autolock l(mInFlightLock);
2762 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2763 if (idx == NAME_NOT_FOUND) {
2764 SET_ERR("Unknown frame number for capture result: %d",
2765 frameNumber);
2766 return;
2767 }
2768 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002769 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2770 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002771 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002772 __FUNCTION__, request.resultExtras.requestId,
2773 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002774 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002775 // Always update the partial count to the latest one if it's not 0
2776 // (buffers only). When framework aggregates adjacent partial results
2777 // into one, the latest partial count will be used.
2778 if (result->partial_result != 0)
2779 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002780
2781 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002782 if (mUsePartialResult && result->result != NULL) {
2783 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2784 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2785 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2786 " the range of [1, %d] when metadata is included in the result",
2787 frameNumber, result->partial_result, mNumPartialResults);
2788 return;
2789 }
2790 isPartialResult = (result->partial_result < mNumPartialResults);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002791 if (isPartialResult) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002792 request.collectedPartialResult.append(result->result);
Zhijun He5d76e1a2014-07-22 16:08:13 -07002793 }
Zhijun He204e3292014-07-14 17:09:23 -07002794 } else {
2795 camera_metadata_ro_entry_t partialResultEntry;
2796 res = find_camera_metadata_ro_entry(result->result,
2797 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
2798 if (res != NAME_NOT_FOUND &&
2799 partialResultEntry.count > 0 &&
2800 partialResultEntry.data.u8[0] ==
2801 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
2802 // A partial result. Flag this as such, and collect this
2803 // set of metadata into the in-flight entry.
2804 isPartialResult = true;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002805 request.collectedPartialResult.append(
Zhijun He204e3292014-07-14 17:09:23 -07002806 result->result);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002807 request.collectedPartialResult.erase(
Zhijun He204e3292014-07-14 17:09:23 -07002808 ANDROID_QUIRKS_PARTIAL_RESULT);
2809 }
2810 }
2811
Shuzhen Wang4a472662017-02-26 23:29:04 -08002812 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002813 // Send partial capture result
2814 sendPartialCaptureResult(result->result, request.resultExtras, frameNumber,
2815 request.aeTriggerCancelOverride);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002816 }
2817 }
2818
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002819 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002820 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002821
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002822 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002823 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002824 if (request.haveResultMetadata) {
2825 SET_ERR("Called multiple times with metadata for frame %d",
2826 frameNumber);
2827 return;
2828 }
Zhijun He204e3292014-07-14 17:09:23 -07002829 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002830 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002831 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002832 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002833 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002834 request.haveResultMetadata = true;
2835 }
2836
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002837 uint32_t numBuffersReturned = result->num_output_buffers;
2838 if (result->input_buffer != NULL) {
2839 if (hasInputBufferInRequest) {
2840 numBuffersReturned += 1;
2841 } else {
2842 ALOGW("%s: Input buffer should be NULL if there is no input"
2843 " buffer sent in the request",
2844 __FUNCTION__);
2845 }
2846 }
2847 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002848 if (request.numBuffersLeft < 0) {
2849 SET_ERR("Too many buffers returned for frame %d",
2850 frameNumber);
2851 return;
2852 }
2853
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002854 camera_metadata_ro_entry_t entry;
2855 res = find_camera_metadata_ro_entry(result->result,
2856 ANDROID_SENSOR_TIMESTAMP, &entry);
2857 if (res == OK && entry.count == 1) {
2858 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002859 }
2860
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002861 // If shutter event isn't received yet, append the output buffers to
2862 // the in-flight request. Otherwise, return the output buffers to
2863 // streams.
2864 if (shutterTimestamp == 0) {
2865 request.pendingOutputBuffers.appendArray(result->output_buffers,
2866 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002867 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002868 returnOutputBuffers(result->output_buffers,
2869 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002870 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002871
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002872 if (result->result != NULL && !isPartialResult) {
2873 if (shutterTimestamp == 0) {
2874 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002875 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002876 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002877 CameraMetadata metadata;
2878 metadata = result->result;
2879 sendCaptureResult(metadata, request.resultExtras,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002880 collectedPartialResult, frameNumber, hasInputBufferInRequest,
2881 request.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002882 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002883 }
2884
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002885 removeInFlightRequestIfReadyLocked(idx);
2886 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002887
Zhijun Hef0d962a2014-06-30 10:24:11 -07002888 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002889 if (hasInputBufferInRequest) {
2890 Camera3Stream *stream =
2891 Camera3Stream::cast(result->input_buffer->stream);
2892 res = stream->returnInputBuffer(*(result->input_buffer));
2893 // Note: stream may be deallocated at this point, if this buffer was the
2894 // last reference to it.
2895 if (res != OK) {
2896 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2897 " its stream:%s (%d)", __FUNCTION__,
2898 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002899 }
2900 } else {
2901 ALOGW("%s: Input buffer should be NULL if there is no input"
2902 " buffer sent in the request, skipping input buffer return.",
2903 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002904 }
2905 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002906}
2907
2908void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002909 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002910 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002911 {
2912 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002913 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002914 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002915
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002916 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002917 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002918 return;
2919 }
2920
2921 switch (msg->type) {
2922 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002923 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002924 break;
2925 }
2926 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002927 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002928 break;
2929 }
2930 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002931 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002932 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002933 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002934}
2935
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002936void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002937 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002938
2939 // Map camera HAL error codes to ICameraDeviceCallback error codes
2940 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002941 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002942 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002943 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002944 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002945 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002946 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002948 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002949 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002950 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002951 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002952 };
2953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002954 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002955 ((msg.error_code >= 0) &&
2956 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2957 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002958 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959
2960 int streamId = 0;
2961 if (msg.error_stream != NULL) {
2962 Camera3Stream *stream =
2963 Camera3Stream::cast(msg.error_stream);
2964 streamId = stream->getId();
2965 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002966 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2967 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002968 streamId, msg.error_code);
2969
2970 CaptureResultExtras resultExtras;
2971 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002973 // SET_ERR calls notifyError
2974 SET_ERR("Camera HAL reported serious device error");
2975 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2977 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2978 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002979 {
2980 Mutex::Autolock l(mInFlightLock);
2981 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2982 if (idx >= 0) {
2983 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2984 r.requestStatus = msg.error_code;
2985 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002986 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2987 errorCode) {
2988 // In case of missing result check whether the buffers
2989 // returned. If they returned, then remove inflight
2990 // request.
2991 removeInFlightRequestIfReadyLocked(idx);
2992 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002993 } else {
2994 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002995 ALOGE("Camera %s: %s: cannot find in-flight request on "
2996 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002997 resultExtras.frameNumber);
2998 }
2999 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003000 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003001 if (listener != NULL) {
3002 listener->notifyError(errorCode, resultExtras);
3003 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003004 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003005 }
3006 break;
3007 default:
3008 // SET_ERR calls notifyError
3009 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3010 break;
3011 }
3012}
3013
3014void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003015 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003016 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003017
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003018 // Set timestamp for the request in the in-flight tracking
3019 // and get the request ID to send upstream
3020 {
3021 Mutex::Autolock l(mInFlightLock);
3022 idx = mInFlightMap.indexOfKey(msg.frame_number);
3023 if (idx >= 0) {
3024 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003026 // Verify ordering of shutter notifications
3027 {
3028 Mutex::Autolock l(mOutputLock);
3029 // TODO: need to track errors for tighter bounds on expected frame number.
3030 if (r.hasInputBuffer) {
3031 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3032 SET_ERR("Shutter notification out-of-order. Expected "
3033 "notification for frame %d, got frame %d",
3034 mNextReprocessShutterFrameNumber, msg.frame_number);
3035 return;
3036 }
3037 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3038 } else {
3039 if (msg.frame_number < mNextShutterFrameNumber) {
3040 SET_ERR("Shutter notification out-of-order. Expected "
3041 "notification for frame %d, got frame %d",
3042 mNextShutterFrameNumber, msg.frame_number);
3043 return;
3044 }
3045 mNextShutterFrameNumber = msg.frame_number + 1;
3046 }
3047 }
3048
Shuzhen Wang4a472662017-02-26 23:29:04 -08003049 r.shutterTimestamp = msg.timestamp;
3050 if (r.hasCallback) {
3051 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003052 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003053 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003054 // Call listener, if any
3055 if (listener != NULL) {
3056 listener->notifyShutter(r.resultExtras, msg.timestamp);
3057 }
3058 // send pending result and buffers
3059 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3060 r.collectedPartialResult, msg.frame_number,
3061 r.hasInputBuffer, r.aeTriggerCancelOverride);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003062 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003063 returnOutputBuffers(r.pendingOutputBuffers.array(),
3064 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3065 r.pendingOutputBuffers.clear();
3066
3067 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003068 }
3069 }
3070 if (idx < 0) {
3071 SET_ERR("Shutter notification for non-existent frame number %d",
3072 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003073 }
3074}
3075
3076
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003077CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003078 ALOGV("%s", __FUNCTION__);
3079
Igor Murashkin1e479c02013-09-06 16:55:14 -07003080 CameraMetadata retVal;
3081
3082 if (mRequestThread != NULL) {
3083 retVal = mRequestThread->getLatestRequest();
3084 }
3085
Igor Murashkin1e479c02013-09-06 16:55:14 -07003086 return retVal;
3087}
3088
Jianing Weicb0652e2014-03-12 18:29:36 -07003089
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003090void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3091 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3092 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3093}
3094
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003095/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003096 * HalInterface inner class methods
3097 */
3098
3099Camera3Device::HalInterface::HalInterface(camera3_device_t *device) :
3100 mHal3Device(device) {}
3101
Yifan Hongf79b5542017-04-11 14:44:25 -07003102Camera3Device::HalInterface::HalInterface(
3103 sp<ICameraDeviceSession> &session,
3104 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003105 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07003106 mHidlSession(session),
3107 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003108
3109Camera3Device::HalInterface::HalInterface() :
3110 mHal3Device(nullptr) {}
3111
3112Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003113 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07003114 mHidlSession(other.mHidlSession),
3115 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003116
3117bool Camera3Device::HalInterface::valid() {
3118 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
3119}
3120
3121void Camera3Device::HalInterface::clear() {
3122 mHal3Device = nullptr;
3123 mHidlSession.clear();
3124}
3125
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003126bool Camera3Device::HalInterface::supportBatchRequest() {
3127 return mHidlSession != nullptr;
3128}
3129
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3131 camera3_request_template_t templateId,
3132 /*out*/ camera_metadata_t **requestTemplate) {
3133 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3134 if (!valid()) return INVALID_OPERATION;
3135 status_t res = OK;
3136
3137 if (mHal3Device != nullptr) {
3138 const camera_metadata *r;
3139 r = mHal3Device->ops->construct_default_request_settings(
3140 mHal3Device, templateId);
3141 if (r == nullptr) return BAD_VALUE;
3142 *requestTemplate = clone_camera_metadata(r);
3143 if (requestTemplate == nullptr) {
3144 ALOGE("%s: Unable to clone camera metadata received from HAL",
3145 __FUNCTION__);
3146 return INVALID_OPERATION;
3147 }
3148 } else {
3149 common::V1_0::Status status;
3150 RequestTemplate id;
3151 switch (templateId) {
3152 case CAMERA3_TEMPLATE_PREVIEW:
3153 id = RequestTemplate::PREVIEW;
3154 break;
3155 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3156 id = RequestTemplate::STILL_CAPTURE;
3157 break;
3158 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3159 id = RequestTemplate::VIDEO_RECORD;
3160 break;
3161 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3162 id = RequestTemplate::VIDEO_SNAPSHOT;
3163 break;
3164 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3165 id = RequestTemplate::ZERO_SHUTTER_LAG;
3166 break;
3167 case CAMERA3_TEMPLATE_MANUAL:
3168 id = RequestTemplate::MANUAL;
3169 break;
3170 default:
3171 // Unknown template ID
3172 return BAD_VALUE;
3173 }
3174 mHidlSession->constructDefaultRequestSettings(id,
3175 [&status, &requestTemplate]
3176 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
3177 status = s;
3178 if (status == common::V1_0::Status::OK) {
3179 const camera_metadata *r =
3180 reinterpret_cast<const camera_metadata_t*>(request.data());
3181 size_t expectedSize = request.size();
3182 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07003183 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003184 *requestTemplate = clone_camera_metadata(r);
3185 if (*requestTemplate == nullptr) {
3186 ALOGE("%s: Unable to clone camera metadata received from HAL",
3187 __FUNCTION__);
3188 status = common::V1_0::Status::INTERNAL_ERROR;
3189 }
3190 } else {
3191 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3192 status = common::V1_0::Status::INTERNAL_ERROR;
3193 }
3194 }
3195 });
3196 res = CameraProviderManager::mapToStatusT(status);
3197 }
3198 return res;
3199}
3200
3201status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
3202 ATRACE_NAME("CameraHal::configureStreams");
3203 if (!valid()) return INVALID_OPERATION;
3204 status_t res = OK;
3205
3206 if (mHal3Device != nullptr) {
3207 res = mHal3Device->ops->configure_streams(mHal3Device, config);
3208 } else {
3209 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003210 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003211 StreamConfiguration requestedConfiguration;
3212 requestedConfiguration.streams.resize(config->num_streams);
3213 for (size_t i = 0; i < config->num_streams; i++) {
3214 Stream &dst = requestedConfiguration.streams[i];
3215 camera3_stream_t *src = config->streams[i];
3216
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003217 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3218 cam3stream->setBufferFreedListener(this);
3219 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003220 StreamType streamType;
3221 switch (src->stream_type) {
3222 case CAMERA3_STREAM_OUTPUT:
3223 streamType = StreamType::OUTPUT;
3224 break;
3225 case CAMERA3_STREAM_INPUT:
3226 streamType = StreamType::INPUT;
3227 break;
3228 default:
3229 ALOGE("%s: Stream %d: Unsupported stream type %d",
3230 __FUNCTION__, streamId, config->streams[i]->stream_type);
3231 return BAD_VALUE;
3232 }
3233 dst.id = streamId;
3234 dst.streamType = streamType;
3235 dst.width = src->width;
3236 dst.height = src->height;
3237 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003238 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003239 dst.dataSpace = mapToHidlDataspace(src->data_space);
3240 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003241
3242 activeStreams.insert(streamId);
3243 // Create Buffer ID map if necessary
3244 if (mBufferIdMaps.count(streamId) == 0) {
3245 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3246 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003247 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003248 // remove BufferIdMap for deleted streams
3249 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3250 int streamId = it->first;
3251 bool active = activeStreams.count(streamId) > 0;
3252 if (!active) {
3253 it = mBufferIdMaps.erase(it);
3254 } else {
3255 ++it;
3256 }
3257 }
3258
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003259 res = mapToStreamConfigurationMode(
3260 (camera3_stream_configuration_mode_t) config->operation_mode,
3261 /*out*/ &requestedConfiguration.operationMode);
3262 if (res != OK) {
3263 return res;
3264 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003265
3266 // Invoke configureStreams
3267
3268 HalStreamConfiguration finalConfiguration;
3269 common::V1_0::Status status;
3270 mHidlSession->configureStreams(requestedConfiguration,
3271 [&status, &finalConfiguration]
3272 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3273 finalConfiguration = halConfiguration;
3274 status = s;
3275 });
3276 if (status != common::V1_0::Status::OK ) {
3277 return CameraProviderManager::mapToStatusT(status);
3278 }
3279
3280 // And convert output stream configuration from HIDL
3281
3282 for (size_t i = 0; i < config->num_streams; i++) {
3283 camera3_stream_t *dst = config->streams[i];
3284 int streamId = Camera3Stream::cast(dst)->getId();
3285
3286 // Start scan at i, with the assumption that the stream order matches
3287 size_t realIdx = i;
3288 bool found = false;
3289 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3290 if (finalConfiguration.streams[realIdx].id == streamId) {
3291 found = true;
3292 break;
3293 }
3294 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3295 }
3296 if (!found) {
3297 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3298 __FUNCTION__, streamId);
3299 return INVALID_OPERATION;
3300 }
3301 HalStream &src = finalConfiguration.streams[realIdx];
3302
3303 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3304 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3305 if (dst->format != overrideFormat) {
3306 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3307 streamId, dst->format);
3308 }
3309 } else {
3310 // Override allowed with IMPLEMENTATION_DEFINED
3311 dst->format = overrideFormat;
3312 }
3313
3314 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3315 if (src.producerUsage != 0) {
3316 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3317 __FUNCTION__, streamId);
3318 return INVALID_OPERATION;
3319 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003320 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003321 } else {
3322 // OUTPUT
3323 if (src.consumerUsage != 0) {
3324 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3325 __FUNCTION__, streamId);
3326 return INVALID_OPERATION;
3327 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003328 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003329 }
3330 dst->max_buffers = src.maxBuffers;
3331 }
3332 }
3333 return res;
3334}
3335
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003336void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3337 /*out*/device::V3_2::CaptureRequest* captureRequest,
3338 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3339
3340 if (captureRequest == nullptr || handlesCreated == nullptr) {
3341 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3342 __FUNCTION__, captureRequest, handlesCreated);
3343 return;
3344 }
3345
3346 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003347
3348 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003349
3350 {
3351 std::lock_guard<std::mutex> lock(mInflightLock);
3352 if (request->input_buffer != nullptr) {
3353 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3354 buffer_handle_t buf = *(request->input_buffer->buffer);
3355 auto pair = getBufferId(buf, streamId);
3356 bool isNewBuffer = pair.first;
3357 uint64_t bufferId = pair.second;
3358 captureRequest->inputBuffer.streamId = streamId;
3359 captureRequest->inputBuffer.bufferId = bufferId;
3360 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3361 captureRequest->inputBuffer.status = BufferStatus::OK;
3362 native_handle_t *acquireFence = nullptr;
3363 if (request->input_buffer->acquire_fence != -1) {
3364 acquireFence = native_handle_create(1,0);
3365 acquireFence->data[0] = request->input_buffer->acquire_fence;
3366 handlesCreated->push_back(acquireFence);
3367 }
3368 captureRequest->inputBuffer.acquireFence = acquireFence;
3369 captureRequest->inputBuffer.releaseFence = nullptr;
3370
3371 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3372 request->input_buffer->buffer,
3373 request->input_buffer->acquire_fence);
3374 } else {
3375 captureRequest->inputBuffer.streamId = -1;
3376 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3377 }
3378
3379 captureRequest->outputBuffers.resize(request->num_output_buffers);
3380 for (size_t i = 0; i < request->num_output_buffers; i++) {
3381 const camera3_stream_buffer_t *src = request->output_buffers + i;
3382 StreamBuffer &dst = captureRequest->outputBuffers[i];
3383 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3384 buffer_handle_t buf = *(src->buffer);
3385 auto pair = getBufferId(buf, streamId);
3386 bool isNewBuffer = pair.first;
3387 dst.streamId = streamId;
3388 dst.bufferId = pair.second;
3389 dst.buffer = isNewBuffer ? buf : nullptr;
3390 dst.status = BufferStatus::OK;
3391 native_handle_t *acquireFence = nullptr;
3392 if (src->acquire_fence != -1) {
3393 acquireFence = native_handle_create(1,0);
3394 acquireFence->data[0] = src->acquire_fence;
3395 handlesCreated->push_back(acquireFence);
3396 }
3397 dst.acquireFence = acquireFence;
3398 dst.releaseFence = nullptr;
3399
3400 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3401 src->buffer, src->acquire_fence);
3402 }
3403 }
3404}
3405
3406status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3407 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3408 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3409 if (!valid()) return INVALID_OPERATION;
3410
3411 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3412 size_t batchSize = requests.size();
3413 captureRequests.resize(batchSize);
3414 std::vector<native_handle_t*> handlesCreated;
3415
3416 for (size_t i = 0; i < batchSize; i++) {
3417 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3418 }
3419
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003420 std::vector<device::V3_2::BufferCache> cachesToRemove;
3421 {
3422 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3423 for (auto& pair : mFreedBuffers) {
3424 // The stream might have been removed since onBufferFreed
3425 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3426 cachesToRemove.push_back({pair.first, pair.second});
3427 }
3428 }
3429 mFreedBuffers.clear();
3430 }
3431
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003432 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3433 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003434
3435 // Write metadata to FMQ.
3436 for (size_t i = 0; i < batchSize; i++) {
3437 camera3_capture_request_t* request = requests[i];
3438 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3439
3440 if (request->settings != nullptr) {
3441 size_t settingsSize = get_camera_metadata_size(request->settings);
3442 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3443 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3444 captureRequest->settings.resize(0);
3445 captureRequest->fmqSettingsSize = settingsSize;
3446 } else {
3447 if (mRequestMetadataQueue != nullptr) {
3448 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3449 }
3450 captureRequest->settings.setToExternal(
3451 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3452 get_camera_metadata_size(request->settings));
3453 captureRequest->fmqSettingsSize = 0u;
3454 }
3455 } else {
3456 // A null request settings maps to a size-0 CameraMetadata
3457 captureRequest->settings.resize(0);
3458 captureRequest->fmqSettingsSize = 0u;
3459 }
3460 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003461 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003462 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3463 status = s;
3464 *numRequestProcessed = n;
3465 });
3466
3467 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3468 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3469 __FUNCTION__, *numRequestProcessed, batchSize);
3470 status = common::V1_0::Status::INTERNAL_ERROR;
3471 }
3472
3473 for (auto& handle : handlesCreated) {
3474 native_handle_delete(handle);
3475 }
3476 return CameraProviderManager::mapToStatusT(status);
3477}
3478
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003479status_t Camera3Device::HalInterface::processCaptureRequest(
3480 camera3_capture_request_t *request) {
3481 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003482 if (!valid()) return INVALID_OPERATION;
3483 status_t res = OK;
3484
3485 if (mHal3Device != nullptr) {
3486 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3487 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003488 uint32_t numRequestProcessed = 0;
3489 std::vector<camera3_capture_request_t*> requests(1);
3490 requests[0] = request;
3491 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492 }
3493 return res;
3494}
3495
3496status_t Camera3Device::HalInterface::flush() {
3497 ATRACE_NAME("CameraHal::flush");
3498 if (!valid()) return INVALID_OPERATION;
3499 status_t res = OK;
3500
3501 if (mHal3Device != nullptr) {
3502 res = mHal3Device->ops->flush(mHal3Device);
3503 } else {
3504 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3505 }
3506 return res;
3507}
3508
3509status_t Camera3Device::HalInterface::dump(int fd) {
3510 ATRACE_NAME("CameraHal::dump");
3511 if (!valid()) return INVALID_OPERATION;
3512 status_t res = OK;
3513
3514 if (mHal3Device != nullptr) {
3515 mHal3Device->ops->dump(mHal3Device, fd);
3516 } else {
3517 // Handled by CameraProviderManager::dump
3518 }
3519 return res;
3520}
3521
3522status_t Camera3Device::HalInterface::close() {
3523 ATRACE_NAME("CameraHal::close()");
3524 if (!valid()) return INVALID_OPERATION;
3525 status_t res = OK;
3526
3527 if (mHal3Device != nullptr) {
3528 mHal3Device->common.close(&mHal3Device->common);
3529 } else {
3530 mHidlSession->close();
3531 }
3532 return res;
3533}
3534
3535status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003536 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003537 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003538 auto pair = std::make_pair(buffer, acquireFence);
3539 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003540 return OK;
3541}
3542
3543status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003544 int32_t frameNumber, int32_t streamId,
3545 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003546 std::lock_guard<std::mutex> lock(mInflightLock);
3547
3548 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3549 auto it = mInflightBufferMap.find(key);
3550 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003551 auto pair = it->second;
3552 *buffer = pair.first;
3553 int acquireFence = pair.second;
3554 if (acquireFence > 0) {
3555 ::close(acquireFence);
3556 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003557 mInflightBufferMap.erase(it);
3558 return OK;
3559}
3560
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003561std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3562 const buffer_handle_t& buf, int streamId) {
3563 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3564
3565 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3566 auto it = bIdMap.find(buf);
3567 if (it == bIdMap.end()) {
3568 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003569 ALOGV("stream %d now have %zu buffer caches, buf %p",
3570 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003571 return std::make_pair(true, mNextBufferId - 1);
3572 } else {
3573 return std::make_pair(false, it->second);
3574 }
3575}
3576
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003577void Camera3Device::HalInterface::onBufferFreed(
3578 int streamId, const native_handle_t* handle) {
3579 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3580 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3581 auto mapIt = mBufferIdMaps.find(streamId);
3582 if (mapIt == mBufferIdMaps.end()) {
3583 // streamId might be from a deleted stream here
3584 ALOGI("%s: stream %d has been removed",
3585 __FUNCTION__, streamId);
3586 return;
3587 }
3588 BufferIdMap& bIdMap = mapIt->second;
3589 auto it = bIdMap.find(handle);
3590 if (it == bIdMap.end()) {
3591 ALOGW("%s: cannot find buffer %p in stream %d",
3592 __FUNCTION__, handle, streamId);
3593 return;
3594 } else {
3595 bufferId = it->second;
3596 bIdMap.erase(it);
3597 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3598 __FUNCTION__, streamId, bIdMap.size(), handle);
3599 }
3600 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3601}
3602
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003603/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003604 * RequestThread inner class methods
3605 */
3606
3607Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003608 sp<StatusTracker> statusTracker,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003609 HalInterface* interface,
3610 uint32_t deviceVersion,
Chien-Yu Chenab5135b2015-06-30 11:20:58 -07003611 bool aeLockAvailable) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003612 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003613 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003614 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003615 mInterface(interface),
3616 mDeviceVersion(deviceVersion),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003617 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003618 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003619 mReconfigured(false),
3620 mDoPause(false),
3621 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003622 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003623 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003624 mCurrentAfTriggerId(0),
3625 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003626 mRepeatingLastFrameNumber(
3627 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003628 mAeLockAvailable(aeLockAvailable),
3629 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003630 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003631}
3632
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003633Camera3Device::RequestThread::~RequestThread() {}
3634
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003635void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003636 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 Mutex::Autolock l(mRequestLock);
3638 mListener = listener;
3639}
3640
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003641void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003642 Mutex::Autolock l(mRequestLock);
3643 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003644 // Prepare video stream for high speed recording.
3645 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003646}
3647
Jianing Wei90e59c92014-03-12 18:29:36 -07003648status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003649 List<sp<CaptureRequest> > &requests,
3650 /*out*/
3651 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003652 Mutex::Autolock l(mRequestLock);
3653 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3654 ++it) {
3655 mRequestQueue.push_back(*it);
3656 }
3657
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003658 if (lastFrameNumber != NULL) {
3659 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3660 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3661 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3662 *lastFrameNumber);
3663 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003664
Jianing Wei90e59c92014-03-12 18:29:36 -07003665 unpauseForNewRequests();
3666
3667 return OK;
3668}
3669
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003670
3671status_t Camera3Device::RequestThread::queueTrigger(
3672 RequestTrigger trigger[],
3673 size_t count) {
3674
3675 Mutex::Autolock l(mTriggerMutex);
3676 status_t ret;
3677
3678 for (size_t i = 0; i < count; ++i) {
3679 ret = queueTriggerLocked(trigger[i]);
3680
3681 if (ret != OK) {
3682 return ret;
3683 }
3684 }
3685
3686 return OK;
3687}
3688
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003689const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3690 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003691 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003692 if (d != nullptr) return d->mId;
3693 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003694}
3695
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003696status_t Camera3Device::RequestThread::queueTriggerLocked(
3697 RequestTrigger trigger) {
3698
3699 uint32_t tag = trigger.metadataTag;
3700 ssize_t index = mTriggerMap.indexOfKey(tag);
3701
3702 switch (trigger.getTagType()) {
3703 case TYPE_BYTE:
3704 // fall-through
3705 case TYPE_INT32:
3706 break;
3707 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003708 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3709 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003710 return INVALID_OPERATION;
3711 }
3712
3713 /**
3714 * Collect only the latest trigger, since we only have 1 field
3715 * in the request settings per trigger tag, and can't send more than 1
3716 * trigger per request.
3717 */
3718 if (index != NAME_NOT_FOUND) {
3719 mTriggerMap.editValueAt(index) = trigger;
3720 } else {
3721 mTriggerMap.add(tag, trigger);
3722 }
3723
3724 return OK;
3725}
3726
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003727status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003728 const RequestList &requests,
3729 /*out*/
3730 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003731 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003732 if (lastFrameNumber != NULL) {
3733 *lastFrameNumber = mRepeatingLastFrameNumber;
3734 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003735 mRepeatingRequests.clear();
3736 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3737 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003738
3739 unpauseForNewRequests();
3740
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003741 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003742 return OK;
3743}
3744
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003745bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003746 if (mRepeatingRequests.empty()) {
3747 return false;
3748 }
3749 int32_t requestId = requestIn->mResultExtras.requestId;
3750 const RequestList &repeatRequests = mRepeatingRequests;
3751 // All repeating requests are guaranteed to have same id so only check first quest
3752 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3753 return (firstRequest->mResultExtras.requestId == requestId);
3754}
3755
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003756status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003757 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003758 return clearRepeatingRequestsLocked(lastFrameNumber);
3759
3760}
3761
3762status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003763 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003764 if (lastFrameNumber != NULL) {
3765 *lastFrameNumber = mRepeatingLastFrameNumber;
3766 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003767 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003768 return OK;
3769}
3770
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003771status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003772 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003773 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003774 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003775
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003776 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003777
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003778 // Send errors for all requests pending in the request queue, including
3779 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003780 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003781 if (listener != NULL) {
3782 for (RequestList::iterator it = mRequestQueue.begin();
3783 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003784 // Abort the input buffers for reprocess requests.
3785 if ((*it)->mInputStream != NULL) {
3786 camera3_stream_buffer_t inputBuffer;
3787 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3788 if (res != OK) {
3789 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3790 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3791 } else {
3792 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3793 if (res != OK) {
3794 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3795 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3796 }
3797 }
3798 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003799 // Set the frame number this request would have had, if it
3800 // had been submitted; this frame number will not be reused.
3801 // The requestId and burstId fields were set when the request was
3802 // submitted originally (in convertMetadataListToRequestListLocked)
3803 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003804 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003805 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003806 }
3807 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003808 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003809
3810 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003811 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003812 if (lastFrameNumber != NULL) {
3813 *lastFrameNumber = mRepeatingLastFrameNumber;
3814 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003815 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003816 return OK;
3817}
3818
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003819status_t Camera3Device::RequestThread::flush() {
3820 ATRACE_CALL();
3821 Mutex::Autolock l(mFlushLock);
3822
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003823 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_1) {
3824 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003825 }
3826
3827 return -ENOTSUP;
3828}
3829
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003830void Camera3Device::RequestThread::setPaused(bool paused) {
3831 Mutex::Autolock l(mPauseLock);
3832 mDoPause = paused;
3833 mDoPauseSignal.signal();
3834}
3835
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003836status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3837 int32_t requestId, nsecs_t timeout) {
3838 Mutex::Autolock l(mLatestRequestMutex);
3839 status_t res;
3840 while (mLatestRequestId != requestId) {
3841 nsecs_t startTime = systemTime();
3842
3843 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3844 if (res != OK) return res;
3845
3846 timeout -= (systemTime() - startTime);
3847 }
3848
3849 return OK;
3850}
3851
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003852void Camera3Device::RequestThread::requestExit() {
3853 // Call parent to set up shutdown
3854 Thread::requestExit();
3855 // The exit from any possible waits
3856 mDoPauseSignal.signal();
3857 mRequestSignal.signal();
3858}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003859
Chien-Yu Chend196d612015-06-22 19:49:01 -07003860
3861/**
3862 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so
3863 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF
3864 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides
3865 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the
3866 * request.
3867 */
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003868void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(const sp<CaptureRequest>& request) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003869 request->mAeTriggerCancelOverride.applyAeLock = false;
3870 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false;
3871
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003872 if (mDeviceVersion > CAMERA_DEVICE_API_VERSION_3_2) {
Chien-Yu Chend196d612015-06-22 19:49:01 -07003873 return;
3874 }
3875
3876 camera_metadata_entry_t aePrecaptureTrigger =
3877 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3878 if (aePrecaptureTrigger.count > 0 &&
3879 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
3880 // Always override CANCEL to IDLE
3881 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
3882 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
3883 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true;
3884 request->mAeTriggerCancelOverride.aePrecaptureTrigger =
3885 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
3886
3887 if (mAeLockAvailable == true) {
3888 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK);
3889 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) {
3890 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON;
3891 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
3892 request->mAeTriggerCancelOverride.applyAeLock = true;
3893 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
3894 }
3895 }
3896 }
3897}
3898
3899/**
3900 * Override result metadata for cancelling AE precapture trigger applied in
3901 * handleAePrecaptureCancelRequest().
3902 */
3903void Camera3Device::overrideResultForPrecaptureCancel(
3904 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) {
3905 if (aeTriggerCancelOverride.applyAeLock) {
3906 // Only devices <= v3.2 should have this override
3907 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3908 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1);
3909 }
3910
3911 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) {
3912 // Only devices <= v3.2 should have this override
3913 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2);
3914 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
3915 &aeTriggerCancelOverride.aePrecaptureTrigger, 1);
3916 }
3917}
3918
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003919void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003920 bool surfaceAbandoned = false;
3921 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003922 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003923 {
3924 Mutex::Autolock l(mRequestLock);
3925 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3926 // repeating requests.
3927 for (const auto& request : mRepeatingRequests) {
3928 for (const auto& s : request->mOutputStreams) {
3929 if (s->isAbandoned()) {
3930 surfaceAbandoned = true;
3931 clearRepeatingRequestsLocked(&lastFrameNumber);
3932 break;
3933 }
3934 }
3935 if (surfaceAbandoned) {
3936 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003937 }
3938 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003939 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003940 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003941
3942 if (listener != NULL && surfaceAbandoned) {
3943 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003944 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003945}
3946
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003947bool Camera3Device::RequestThread::sendRequestsBatch() {
3948 status_t res;
3949 size_t batchSize = mNextRequests.size();
3950 std::vector<camera3_capture_request_t*> requests(batchSize);
3951 uint32_t numRequestProcessed = 0;
3952 for (size_t i = 0; i < batchSize; i++) {
3953 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3954 }
3955
3956 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3957 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3958
3959 bool triggerRemoveFailed = false;
3960 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3961 for (size_t i = 0; i < numRequestProcessed; i++) {
3962 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3963 nextRequest.submitted = true;
3964
3965
3966 // Update the latest request sent to HAL
3967 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3968 Mutex::Autolock al(mLatestRequestMutex);
3969
3970 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3971 mLatestRequest.acquire(cloned);
3972
3973 sp<Camera3Device> parent = mParent.promote();
3974 if (parent != NULL) {
3975 parent->monitorMetadata(TagMonitor::REQUEST,
3976 nextRequest.halRequest.frame_number,
3977 0, mLatestRequest);
3978 }
3979 }
3980
3981 if (nextRequest.halRequest.settings != NULL) {
3982 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3983 }
3984
3985 if (!triggerRemoveFailed) {
3986 // Remove any previously queued triggers (after unlock)
3987 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3988 if (removeTriggerRes != OK) {
3989 triggerRemoveFailed = true;
3990 triggerFailedRequest = nextRequest;
3991 }
3992 }
3993 }
3994
3995 if (triggerRemoveFailed) {
3996 SET_ERR("RequestThread: Unable to remove triggers "
3997 "(capture request %d, HAL device: %s (%d)",
3998 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3999 cleanUpFailedRequests(/*sendRequestError*/ false);
4000 return false;
4001 }
4002
4003 if (res != OK) {
4004 // Should only get a failure here for malformed requests or device-level
4005 // errors, so consider all errors fatal. Bad metadata failures should
4006 // come through notify.
4007 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4008 mNextRequests[numRequestProcessed].halRequest.frame_number,
4009 strerror(-res), res);
4010 cleanUpFailedRequests(/*sendRequestError*/ false);
4011 return false;
4012 }
4013 return true;
4014}
4015
4016bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4017 status_t res;
4018
4019 for (auto& nextRequest : mNextRequests) {
4020 // Submit request and block until ready for next one
4021 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4022 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4023
4024 if (res != OK) {
4025 // Should only get a failure here for malformed requests or device-level
4026 // errors, so consider all errors fatal. Bad metadata failures should
4027 // come through notify.
4028 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4029 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4030 res);
4031 cleanUpFailedRequests(/*sendRequestError*/ false);
4032 return false;
4033 }
4034
4035 // Mark that the request has be submitted successfully.
4036 nextRequest.submitted = true;
4037
4038 // Update the latest request sent to HAL
4039 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4040 Mutex::Autolock al(mLatestRequestMutex);
4041
4042 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4043 mLatestRequest.acquire(cloned);
4044
4045 sp<Camera3Device> parent = mParent.promote();
4046 if (parent != NULL) {
4047 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4048 0, mLatestRequest);
4049 }
4050 }
4051
4052 if (nextRequest.halRequest.settings != NULL) {
4053 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
4054 }
4055
4056 // Remove any previously queued triggers (after unlock)
4057 res = removeTriggers(mPrevRequest);
4058 if (res != OK) {
4059 SET_ERR("RequestThread: Unable to remove triggers "
4060 "(capture request %d, HAL device: %s (%d)",
4061 nextRequest.halRequest.frame_number, strerror(-res), res);
4062 cleanUpFailedRequests(/*sendRequestError*/ false);
4063 return false;
4064 }
4065 }
4066 return true;
4067}
4068
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004069bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004070 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004071 status_t res;
4072
4073 // Handle paused state.
4074 if (waitIfPaused()) {
4075 return true;
4076 }
4077
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004078 // Wait for the next batch of requests.
4079 waitForNextRequestBatch();
4080 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004081 return true;
4082 }
4083
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004084 // Get the latest request ID, if any
4085 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004086 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004087 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004088 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004089 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004090 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004091 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4092 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004093 }
4094
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004095 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004096 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004097 if (res == TIMED_OUT) {
4098 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004099 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004100 // Check if any stream is abandoned.
4101 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004102 return true;
4103 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004104 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004105 return false;
4106 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004107
Zhijun Hecc27e112013-10-03 16:12:43 -07004108 // Inform waitUntilRequestProcessed thread of a new request ID
4109 {
4110 Mutex::Autolock al(mLatestRequestMutex);
4111
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004112 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004113 mLatestRequestSignal.signal();
4114 }
4115
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004116 // Submit a batch of requests to HAL.
4117 // Use flush lock only when submitting multilple requests in a batch.
4118 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4119 // which may take a long time to finish so synchronizing flush() and
4120 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4121 // For now, only synchronize for high speed recording and we should figure something out for
4122 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004123 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004124
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004125 if (useFlushLock) {
4126 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004127 }
4128
Zhijun Hef0645c12016-08-02 00:58:11 -07004129 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004130 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004131
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004132 bool submitRequestSuccess = false;
4133 if (mInterface->supportBatchRequest()) {
4134 submitRequestSuccess = sendRequestsBatch();
4135 } else {
4136 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004137 }
4138
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004139 if (useFlushLock) {
4140 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004141 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004142
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004143 // Unset as current request
4144 {
4145 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004146 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004147 }
4148
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004149 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004150}
4151
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004152status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004153 ATRACE_CALL();
4154
Shuzhen Wang4a472662017-02-26 23:29:04 -08004155 for (size_t i = 0; i < mNextRequests.size(); i++) {
4156 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004157 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4158 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4159 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4160
4161 // Prepare a request to HAL
4162 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4163
4164 // Insert any queued triggers (before metadata is locked)
4165 status_t res = insertTriggers(captureRequest);
4166
4167 if (res < 0) {
4168 SET_ERR("RequestThread: Unable to insert triggers "
4169 "(capture request %d, HAL device: %s (%d)",
4170 halRequest->frame_number, strerror(-res), res);
4171 return INVALID_OPERATION;
4172 }
4173 int triggerCount = res;
4174 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4175 mPrevTriggers = triggerCount;
4176
4177 // If the request is the same as last, or we had triggers last time
4178 if (mPrevRequest != captureRequest || triggersMixedIn) {
4179 /**
4180 * HAL workaround:
4181 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4182 */
4183 res = addDummyTriggerIds(captureRequest);
4184 if (res != OK) {
4185 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4186 "(capture request %d, HAL device: %s (%d)",
4187 halRequest->frame_number, strerror(-res), res);
4188 return INVALID_OPERATION;
4189 }
4190
4191 /**
4192 * The request should be presorted so accesses in HAL
4193 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4194 */
4195 captureRequest->mSettings.sort();
4196 halRequest->settings = captureRequest->mSettings.getAndLock();
4197 mPrevRequest = captureRequest;
4198 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4199
4200 IF_ALOGV() {
4201 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4202 find_camera_metadata_ro_entry(
4203 halRequest->settings,
4204 ANDROID_CONTROL_AF_TRIGGER,
4205 &e
4206 );
4207 if (e.count > 0) {
4208 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4209 __FUNCTION__,
4210 halRequest->frame_number,
4211 e.data.u8[0]);
4212 }
4213 }
4214 } else {
4215 // leave request.settings NULL to indicate 'reuse latest given'
4216 ALOGVV("%s: Request settings are REUSED",
4217 __FUNCTION__);
4218 }
4219
4220 uint32_t totalNumBuffers = 0;
4221
4222 // Fill in buffers
4223 if (captureRequest->mInputStream != NULL) {
4224 halRequest->input_buffer = &captureRequest->mInputBuffer;
4225 totalNumBuffers += 1;
4226 } else {
4227 halRequest->input_buffer = NULL;
4228 }
4229
4230 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4231 captureRequest->mOutputStreams.size());
4232 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08004233 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4234 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004235
4236 // Prepare video buffers for high speed recording on the first video request.
4237 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4238 // Only try to prepare video stream on the first video request.
4239 mPrepareVideoStream = false;
4240
4241 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4242 while (res == NOT_ENOUGH_DATA) {
4243 res = outputStream->prepareNextBuffer();
4244 }
4245 if (res != OK) {
4246 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4247 __FUNCTION__, strerror(-res), res);
4248 outputStream->cancelPrepare();
4249 }
4250 }
4251
Shuzhen Wang4a472662017-02-26 23:29:04 -08004252 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4253 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004254 if (res != OK) {
4255 // Can't get output buffer from gralloc queue - this could be due to
4256 // abandoned queue or other consumer misbehavior, so not a fatal
4257 // error
4258 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4259 " %s (%d)", strerror(-res), res);
4260
4261 return TIMED_OUT;
4262 }
4263 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07004264
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004265 }
4266 totalNumBuffers += halRequest->num_output_buffers;
4267
4268 // Log request in the in-flight queue
4269 sp<Camera3Device> parent = mParent.promote();
4270 if (parent == NULL) {
4271 // Should not happen, and nowhere to send errors to, so just log it
4272 CLOGE("RequestThread: Parent is gone");
4273 return INVALID_OPERATION;
4274 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004275
4276 // If this request list is for constrained high speed recording (not
4277 // preview), and the current request is not the last one in the batch,
4278 // do not send callback to the app.
4279 bool hasCallback = true;
4280 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4281 hasCallback = false;
4282 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004283 res = parent->registerInFlight(halRequest->frame_number,
4284 totalNumBuffers, captureRequest->mResultExtras,
4285 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004286 captureRequest->mAeTriggerCancelOverride,
4287 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004288 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4289 ", burstId = %" PRId32 ".",
4290 __FUNCTION__,
4291 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4292 captureRequest->mResultExtras.burstId);
4293 if (res != OK) {
4294 SET_ERR("RequestThread: Unable to register new in-flight request:"
4295 " %s (%d)", strerror(-res), res);
4296 return INVALID_OPERATION;
4297 }
4298 }
4299
4300 return OK;
4301}
4302
Igor Murashkin1e479c02013-09-06 16:55:14 -07004303CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4304 Mutex::Autolock al(mLatestRequestMutex);
4305
4306 ALOGV("RequestThread::%s", __FUNCTION__);
4307
4308 return mLatestRequest;
4309}
4310
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004311bool Camera3Device::RequestThread::isStreamPending(
4312 sp<Camera3StreamInterface>& stream) {
4313 Mutex::Autolock l(mRequestLock);
4314
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004315 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004316 if (!nextRequest.submitted) {
4317 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4318 if (stream == s) return true;
4319 }
4320 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004321 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004322 }
4323
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004324 for (const auto& request : mRequestQueue) {
4325 for (const auto& s : request->mOutputStreams) {
4326 if (stream == s) return true;
4327 }
4328 if (stream == request->mInputStream) return true;
4329 }
4330
4331 for (const auto& request : mRepeatingRequests) {
4332 for (const auto& s : request->mOutputStreams) {
4333 if (stream == s) return true;
4334 }
4335 if (stream == request->mInputStream) return true;
4336 }
4337
4338 return false;
4339}
Jianing Weicb0652e2014-03-12 18:29:36 -07004340
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004341void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4342 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004343 return;
4344 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004346 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004347 // Skip the ones that have been submitted successfully.
4348 if (nextRequest.submitted) {
4349 continue;
4350 }
4351
4352 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4353 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4354 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4355
4356 if (halRequest->settings != NULL) {
4357 captureRequest->mSettings.unlock(halRequest->settings);
4358 }
4359
4360 if (captureRequest->mInputStream != NULL) {
4361 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4362 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4363 }
4364
4365 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4366 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4367 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4368 }
4369
4370 if (sendRequestError) {
4371 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004372 sp<NotificationListener> listener = mListener.promote();
4373 if (listener != NULL) {
4374 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004375 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004376 captureRequest->mResultExtras);
4377 }
4378 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004379
4380 // Remove yet-to-be submitted inflight request from inflightMap
4381 {
4382 sp<Camera3Device> parent = mParent.promote();
4383 if (parent != NULL) {
4384 Mutex::Autolock l(parent->mInFlightLock);
4385 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4386 if (idx >= 0) {
4387 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4388 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4389 parent->removeInFlightMapEntryLocked(idx);
4390 }
4391 }
4392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004393 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004394
4395 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004396 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004397}
4398
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004399void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004400 // Optimized a bit for the simple steady-state case (single repeating
4401 // request), to avoid putting that request in the queue temporarily.
4402 Mutex::Autolock l(mRequestLock);
4403
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004404 assert(mNextRequests.empty());
4405
4406 NextRequest nextRequest;
4407 nextRequest.captureRequest = waitForNextRequestLocked();
4408 if (nextRequest.captureRequest == nullptr) {
4409 return;
4410 }
4411
4412 nextRequest.halRequest = camera3_capture_request_t();
4413 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004414 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004415
4416 // Wait for additional requests
4417 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4418
4419 for (size_t i = 1; i < batchSize; i++) {
4420 NextRequest additionalRequest;
4421 additionalRequest.captureRequest = waitForNextRequestLocked();
4422 if (additionalRequest.captureRequest == nullptr) {
4423 break;
4424 }
4425
4426 additionalRequest.halRequest = camera3_capture_request_t();
4427 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004428 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004429 }
4430
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004431 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004432 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004433 mNextRequests.size(), batchSize);
4434 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004435 }
4436
4437 return;
4438}
4439
4440sp<Camera3Device::CaptureRequest>
4441 Camera3Device::RequestThread::waitForNextRequestLocked() {
4442 status_t res;
4443 sp<CaptureRequest> nextRequest;
4444
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004445 while (mRequestQueue.empty()) {
4446 if (!mRepeatingRequests.empty()) {
4447 // Always atomically enqueue all requests in a repeating request
4448 // list. Guarantees a complete in-sequence set of captures to
4449 // application.
4450 const RequestList &requests = mRepeatingRequests;
4451 RequestList::const_iterator firstRequest =
4452 requests.begin();
4453 nextRequest = *firstRequest;
4454 mRequestQueue.insert(mRequestQueue.end(),
4455 ++firstRequest,
4456 requests.end());
4457 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004458
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004459 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004460
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004461 break;
4462 }
4463
4464 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4465
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004466 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4467 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004468 Mutex::Autolock pl(mPauseLock);
4469 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004470 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004471 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004472 // Let the tracker know
4473 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4474 if (statusTracker != 0) {
4475 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4476 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004477 }
4478 // Stop waiting for now and let thread management happen
4479 return NULL;
4480 }
4481 }
4482
4483 if (nextRequest == NULL) {
4484 // Don't have a repeating request already in hand, so queue
4485 // must have an entry now.
4486 RequestList::iterator firstRequest =
4487 mRequestQueue.begin();
4488 nextRequest = *firstRequest;
4489 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004490 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4491 sp<NotificationListener> listener = mListener.promote();
4492 if (listener != NULL) {
4493 listener->notifyRequestQueueEmpty();
4494 }
4495 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004496 }
4497
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004498 // In case we've been unpaused by setPaused clearing mDoPause, need to
4499 // update internal pause state (capture/setRepeatingRequest unpause
4500 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004501 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004502 if (mPaused) {
4503 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4504 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4505 if (statusTracker != 0) {
4506 statusTracker->markComponentActive(mStatusId);
4507 }
4508 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004509 mPaused = false;
4510
4511 // Check if we've reconfigured since last time, and reset the preview
4512 // request if so. Can't use 'NULL request == repeat' across configure calls.
4513 if (mReconfigured) {
4514 mPrevRequest.clear();
4515 mReconfigured = false;
4516 }
4517
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004518 if (nextRequest != NULL) {
4519 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004520 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4521 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004522
4523 // Since RequestThread::clear() removes buffers from the input stream,
4524 // get the right buffer here before unlocking mRequestLock
4525 if (nextRequest->mInputStream != NULL) {
4526 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4527 if (res != OK) {
4528 // Can't get input buffer from gralloc queue - this could be due to
4529 // disconnected queue or other producer misbehavior, so not a fatal
4530 // error
4531 ALOGE("%s: Can't get input buffer, skipping request:"
4532 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004533
4534 sp<NotificationListener> listener = mListener.promote();
4535 if (listener != NULL) {
4536 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004537 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004538 nextRequest->mResultExtras);
4539 }
4540 return NULL;
4541 }
4542 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004543 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004544
4545 handleAePrecaptureCancelRequest(nextRequest);
4546
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004547 return nextRequest;
4548}
4549
4550bool Camera3Device::RequestThread::waitIfPaused() {
4551 status_t res;
4552 Mutex::Autolock l(mPauseLock);
4553 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004554 if (mPaused == false) {
4555 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004556 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4557 // Let the tracker know
4558 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4559 if (statusTracker != 0) {
4560 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4561 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004562 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004564 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004565 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004566 return true;
4567 }
4568 }
4569 // We don't set mPaused to false here, because waitForNextRequest needs
4570 // to further manage the paused state in case of starvation.
4571 return false;
4572}
4573
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004574void Camera3Device::RequestThread::unpauseForNewRequests() {
4575 // With work to do, mark thread as unpaused.
4576 // If paused by request (setPaused), don't resume, to avoid
4577 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004578 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004579 Mutex::Autolock p(mPauseLock);
4580 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004581 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4582 if (mPaused) {
4583 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4584 if (statusTracker != 0) {
4585 statusTracker->markComponentActive(mStatusId);
4586 }
4587 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004588 mPaused = false;
4589 }
4590}
4591
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004592void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4593 sp<Camera3Device> parent = mParent.promote();
4594 if (parent != NULL) {
4595 va_list args;
4596 va_start(args, fmt);
4597
4598 parent->setErrorStateV(fmt, args);
4599
4600 va_end(args);
4601 }
4602}
4603
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004604status_t Camera3Device::RequestThread::insertTriggers(
4605 const sp<CaptureRequest> &request) {
4606
4607 Mutex::Autolock al(mTriggerMutex);
4608
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004609 sp<Camera3Device> parent = mParent.promote();
4610 if (parent == NULL) {
4611 CLOGE("RequestThread: Parent is gone");
4612 return DEAD_OBJECT;
4613 }
4614
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004615 CameraMetadata &metadata = request->mSettings;
4616 size_t count = mTriggerMap.size();
4617
4618 for (size_t i = 0; i < count; ++i) {
4619 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004620 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004621
4622 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4623 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4624 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004625 if (isAeTrigger) {
4626 request->mResultExtras.precaptureTriggerId = triggerId;
4627 mCurrentPreCaptureTriggerId = triggerId;
4628 } else {
4629 request->mResultExtras.afTriggerId = triggerId;
4630 mCurrentAfTriggerId = triggerId;
4631 }
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004632 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
4633 continue; // Trigger ID tag is deprecated since device HAL 3.2
4634 }
4635 }
4636
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004637 camera_metadata_entry entry = metadata.find(tag);
4638
4639 if (entry.count > 0) {
4640 /**
4641 * Already has an entry for this trigger in the request.
4642 * Rewrite it with our requested trigger value.
4643 */
4644 RequestTrigger oldTrigger = trigger;
4645
4646 oldTrigger.entryValue = entry.data.u8[0];
4647
4648 mTriggerReplacedMap.add(tag, oldTrigger);
4649 } else {
4650 /**
4651 * More typical, no trigger entry, so we just add it
4652 */
4653 mTriggerRemovedMap.add(tag, trigger);
4654 }
4655
4656 status_t res;
4657
4658 switch (trigger.getTagType()) {
4659 case TYPE_BYTE: {
4660 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4661 res = metadata.update(tag,
4662 &entryValue,
4663 /*count*/1);
4664 break;
4665 }
4666 case TYPE_INT32:
4667 res = metadata.update(tag,
4668 &trigger.entryValue,
4669 /*count*/1);
4670 break;
4671 default:
4672 ALOGE("%s: Type not supported: 0x%x",
4673 __FUNCTION__,
4674 trigger.getTagType());
4675 return INVALID_OPERATION;
4676 }
4677
4678 if (res != OK) {
4679 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4680 ", value %d", __FUNCTION__, trigger.getTagName(),
4681 trigger.entryValue);
4682 return res;
4683 }
4684
4685 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4686 trigger.getTagName(),
4687 trigger.entryValue);
4688 }
4689
4690 mTriggerMap.clear();
4691
4692 return count;
4693}
4694
4695status_t Camera3Device::RequestThread::removeTriggers(
4696 const sp<CaptureRequest> &request) {
4697 Mutex::Autolock al(mTriggerMutex);
4698
4699 CameraMetadata &metadata = request->mSettings;
4700
4701 /**
4702 * Replace all old entries with their old values.
4703 */
4704 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4705 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4706
4707 status_t res;
4708
4709 uint32_t tag = trigger.metadataTag;
4710 switch (trigger.getTagType()) {
4711 case TYPE_BYTE: {
4712 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4713 res = metadata.update(tag,
4714 &entryValue,
4715 /*count*/1);
4716 break;
4717 }
4718 case TYPE_INT32:
4719 res = metadata.update(tag,
4720 &trigger.entryValue,
4721 /*count*/1);
4722 break;
4723 default:
4724 ALOGE("%s: Type not supported: 0x%x",
4725 __FUNCTION__,
4726 trigger.getTagType());
4727 return INVALID_OPERATION;
4728 }
4729
4730 if (res != OK) {
4731 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4732 ", trigger value %d", __FUNCTION__,
4733 trigger.getTagName(), trigger.entryValue);
4734 return res;
4735 }
4736 }
4737 mTriggerReplacedMap.clear();
4738
4739 /**
4740 * Remove all new entries.
4741 */
4742 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4743 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4744 status_t res = metadata.erase(trigger.metadataTag);
4745
4746 if (res != OK) {
4747 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4748 ", trigger value %d", __FUNCTION__,
4749 trigger.getTagName(), trigger.entryValue);
4750 return res;
4751 }
4752 }
4753 mTriggerRemovedMap.clear();
4754
4755 return OK;
4756}
4757
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004758status_t Camera3Device::RequestThread::addDummyTriggerIds(
4759 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004760 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004761 static const int32_t dummyTriggerId = 1;
4762 status_t res;
4763
4764 CameraMetadata &metadata = request->mSettings;
4765
4766 // If AF trigger is active, insert a dummy AF trigger ID if none already
4767 // exists
4768 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4769 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4770 if (afTrigger.count > 0 &&
4771 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4772 afId.count == 0) {
4773 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4774 if (res != OK) return res;
4775 }
4776
4777 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4778 // if none already exists
4779 camera_metadata_entry pcTrigger =
4780 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4781 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4782 if (pcTrigger.count > 0 &&
4783 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4784 pcId.count == 0) {
4785 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4786 &dummyTriggerId, 1);
4787 if (res != OK) return res;
4788 }
4789
4790 return OK;
4791}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004792
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004793/**
4794 * PreparerThread inner class methods
4795 */
4796
4797Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004798 Thread(/*canCallJava*/false), mListener(nullptr),
4799 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004800}
4801
4802Camera3Device::PreparerThread::~PreparerThread() {
4803 Thread::requestExitAndWait();
4804 if (mCurrentStream != nullptr) {
4805 mCurrentStream->cancelPrepare();
4806 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4807 mCurrentStream.clear();
4808 }
4809 clear();
4810}
4811
Ruben Brunkc78ac262015-08-13 17:58:46 -07004812status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004813 status_t res;
4814
4815 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004816 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817
Ruben Brunkc78ac262015-08-13 17:58:46 -07004818 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004819 if (res == OK) {
4820 // No preparation needed, fire listener right off
4821 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004822 if (listener != NULL) {
4823 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004824 }
4825 return OK;
4826 } else if (res != NOT_ENOUGH_DATA) {
4827 return res;
4828 }
4829
4830 // Need to prepare, start up thread if necessary
4831 if (!mActive) {
4832 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4833 // isn't running
4834 Thread::requestExitAndWait();
4835 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4836 if (res != OK) {
4837 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004838 if (listener != NULL) {
4839 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004840 }
4841 return res;
4842 }
4843 mCancelNow = false;
4844 mActive = true;
4845 ALOGV("%s: Preparer stream started", __FUNCTION__);
4846 }
4847
4848 // queue up the work
4849 mPendingStreams.push_back(stream);
4850 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4851
4852 return OK;
4853}
4854
4855status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004856 Mutex::Autolock l(mLock);
4857
4858 for (const auto& stream : mPendingStreams) {
4859 stream->cancelPrepare();
4860 }
4861 mPendingStreams.clear();
4862 mCancelNow = true;
4863
4864 return OK;
4865}
4866
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004867void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004868 Mutex::Autolock l(mLock);
4869 mListener = listener;
4870}
4871
4872bool Camera3Device::PreparerThread::threadLoop() {
4873 status_t res;
4874 {
4875 Mutex::Autolock l(mLock);
4876 if (mCurrentStream == nullptr) {
4877 // End thread if done with work
4878 if (mPendingStreams.empty()) {
4879 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4880 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4881 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4882 mActive = false;
4883 return false;
4884 }
4885
4886 // Get next stream to prepare
4887 auto it = mPendingStreams.begin();
4888 mCurrentStream = *it;
4889 mPendingStreams.erase(it);
4890 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4891 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4892 } else if (mCancelNow) {
4893 mCurrentStream->cancelPrepare();
4894 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4895 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4896 mCurrentStream.clear();
4897 mCancelNow = false;
4898 return true;
4899 }
4900 }
4901
4902 res = mCurrentStream->prepareNextBuffer();
4903 if (res == NOT_ENOUGH_DATA) return true;
4904 if (res != OK) {
4905 // Something bad happened; try to recover by cancelling prepare and
4906 // signalling listener anyway
4907 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4908 mCurrentStream->getId(), res, strerror(-res));
4909 mCurrentStream->cancelPrepare();
4910 }
4911
4912 // This stream has finished, notify listener
4913 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004914 sp<NotificationListener> listener = mListener.promote();
4915 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004916 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4917 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004918 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004919 }
4920
4921 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4922 mCurrentStream.clear();
4923
4924 return true;
4925}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004926
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004927/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004928 * Static callback forwarding methods from HAL to instance
4929 */
4930
4931void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4932 const camera3_capture_result *result) {
4933 Camera3Device *d =
4934 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004935
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004936 d->processCaptureResult(result);
4937}
4938
4939void Camera3Device::sNotify(const camera3_callback_ops *cb,
4940 const camera3_notify_msg *msg) {
4941 Camera3Device *d =
4942 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4943 d->notify(msg);
4944}
4945
4946}; // namespace android