blob: 04c2c5bec88d9a1a9f8f6aeb35bbc983450223b6 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
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
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
80 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080081{
82 ATRACE_CALL();
83 camera3_callback_ops::notify = &sNotify;
84 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092 disconnect();
93}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
123 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Yifan Hongf79b5542017-04-11 14:44:25 -0700128 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700129 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
130 [&queue](const auto& descriptor) {
131 queue = std::make_shared<RequestMetadataQueue>(descriptor);
132 if (!queue->isValid() || queue->availableToWrite() <= 0) {
133 ALOGE("HAL returns empty request metadata fmq, not use it");
134 queue = nullptr;
135 // don't use the queue onwards.
136 }
137 });
138 if (!requestQueueRet.isOk()) {
139 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
140 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700141 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700143
144 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700145 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700146 [&resQueue](const auto& descriptor) {
147 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
148 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700149 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700150 resQueue = nullptr;
151 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700152 }
153 });
154 if (!resultQueueRet.isOk()) {
155 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
156 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700157 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700158 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700159 IF_ALOGV() {
160 session->interfaceChain([](
161 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
162 ALOGV("Session interface chain:");
163 for (auto iface : interfaceChain) {
164 ALOGV(" %s", iface.c_str());
165 }
166 });
167 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700168
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700169 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000170 std::string providerType;
171 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172
173 return initializeCommonLocked();
174}
175
176status_t Camera3Device::initializeCommonLocked() {
177
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700178 /** Start up status tracker thread */
179 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800180 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700181 if (res != OK) {
182 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
183 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800184 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700185 mStatusTracker.clear();
186 return res;
187 }
188
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700189 /** Register in-flight map to the status tracker */
190 mInFlightStatusId = mStatusTracker->addComponent();
191
Zhijun He125684a2015-12-26 15:07:30 -0800192 /** Create buffer manager */
193 mBufferManager = new Camera3BufferManager();
194
Emilian Peev71c73a22017-03-21 16:35:51 +0000195 mTagMonitor.initialize(mVendorTagId);
196
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000197 Vector<int32_t> sessionParamKeys;
198 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
199 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
200 if (sessionKeysEntry.count > 0) {
201 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
202 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700203 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000204 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800205 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800206 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700207 SET_ERR_L("Unable to start request queue thread: %s (%d)",
208 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800209 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800210 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800211 return res;
212 }
213
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700214 mPreparerThread = new PreparerThread();
215
Ruben Brunk183f0562015-08-12 12:55:02 -0700216 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800217 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700218 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700219 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700220 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800221
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800222 // Measure the clock domain offset between camera and video/hw_composer
223 camera_metadata_entry timestampSource =
224 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
225 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
226 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
227 mTimestampOffset = getMonoToBoottimeOffset();
228 }
229
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700230 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100231 camera_metadata_entry partialResultsCount =
232 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
233 if (partialResultsCount.count > 0) {
234 mNumPartialResults = partialResultsCount.data.i32[0];
235 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700236 }
237
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700238 camera_metadata_entry configs =
239 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
240 for (uint32_t i = 0; i < configs.count; i += 4) {
241 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
242 configs.data.i32[i + 3] ==
243 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
244 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
245 configs.data.i32[i + 2]));
246 }
247 }
248
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800249 return OK;
250}
251
252status_t Camera3Device::disconnect() {
253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800255
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700256 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800257
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700258 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700259 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700260 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 {
262 Mutex::Autolock l(mLock);
263 if (mStatus == STATUS_UNINITIALIZED) return res;
264
265 if (mStatus == STATUS_ACTIVE ||
266 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
267 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700268 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700270 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700271 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700272 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700274 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
275 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 // Continue to close device even in case of error
277 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700278 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800279 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800280
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 if (mStatus == STATUS_ERROR) {
282 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700283 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284
285 if (mStatusTracker != NULL) {
286 mStatusTracker->requestExit();
287 }
288
289 if (mRequestThread != NULL) {
290 mRequestThread->requestExit();
291 }
292
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700293 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
294 for (size_t i = 0; i < mOutputStreams.size(); i++) {
295 streams.push_back(mOutputStreams[i]);
296 }
297 if (mInputStream != nullptr) {
298 streams.push_back(mInputStream);
299 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 }
301
302 // Joining done without holding mLock, otherwise deadlocks may ensue
303 // as the threads try to access parent state
304 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
305 // HAL may be in a bad state, so waiting for request thread
306 // (which may be stuck in the HAL processCaptureRequest call)
307 // could be dangerous.
308 mRequestThread->join();
309 }
310
311 if (mStatusTracker != NULL) {
312 mStatusTracker->join();
313 }
314
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800315 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 {
317 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800318 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800320 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700321 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700323 // Call close without internal mutex held, as the HAL close may need to
324 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800325 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700326
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700327 flushInflightRequests();
328
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700329 {
330 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800331 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700332 mOutputStreams.clear();
333 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700334 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700335 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700336 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700337 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800338
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 for (auto& weakStream : streams) {
340 sp<Camera3StreamInterface> stream = weakStream.promote();
341 if (stream != nullptr) {
342 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
343 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
344 }
345 }
346
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700347 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700348 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800349}
350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700351// For dumping/debugging only -
352// try to acquire a lock a few times, eventually give up to proceed with
353// debug/dump operations
354bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
355 bool gotLock = false;
356 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
357 if (lock.tryLock() == NO_ERROR) {
358 gotLock = true;
359 break;
360 } else {
361 usleep(kDumpSleepDuration);
362 }
363 }
364 return gotLock;
365}
366
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700367Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
368 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100369 const int STREAM_CONFIGURATION_SIZE = 4;
370 const int STREAM_FORMAT_OFFSET = 0;
371 const int STREAM_WIDTH_OFFSET = 1;
372 const int STREAM_HEIGHT_OFFSET = 2;
373 const int STREAM_IS_INPUT_OFFSET = 3;
374 camera_metadata_ro_entry_t availableStreamConfigs =
375 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
376 if (availableStreamConfigs.count == 0 ||
377 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
378 return Size(0, 0);
379 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700380
Emilian Peev08dd2452017-04-06 16:55:14 +0100381 // Get max jpeg size (area-wise).
382 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
383 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
384 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
385 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
386 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
387 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
388 && format == HAL_PIXEL_FORMAT_BLOB &&
389 (width * height > maxJpegWidth * maxJpegHeight)) {
390 maxJpegWidth = width;
391 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700392 }
393 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100394
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700395 return Size(maxJpegWidth, maxJpegHeight);
396}
397
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800398nsecs_t Camera3Device::getMonoToBoottimeOffset() {
399 // try three times to get the clock offset, choose the one
400 // with the minimum gap in measurements.
401 const int tries = 3;
402 nsecs_t bestGap, measured;
403 for (int i = 0; i < tries; ++i) {
404 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
405 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
406 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
407 const nsecs_t gap = tmono2 - tmono;
408 if (i == 0 || gap < bestGap) {
409 bestGap = gap;
410 measured = tbase - ((tmono + tmono2) >> 1);
411 }
412 }
413 return measured;
414}
415
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
417 int frameworkFormat) {
418 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
419}
420
421DataspaceFlags Camera3Device::mapToHidlDataspace(
422 android_dataspace dataSpace) {
423 return dataSpace;
424}
425
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700426BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100427 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700428 return usage;
429}
430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800431StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
432 switch (rotation) {
433 case CAMERA3_STREAM_ROTATION_0:
434 return StreamRotation::ROTATION_0;
435 case CAMERA3_STREAM_ROTATION_90:
436 return StreamRotation::ROTATION_90;
437 case CAMERA3_STREAM_ROTATION_180:
438 return StreamRotation::ROTATION_180;
439 case CAMERA3_STREAM_ROTATION_270:
440 return StreamRotation::ROTATION_270;
441 }
442 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
443 return StreamRotation::ROTATION_0;
444}
445
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800446status_t Camera3Device::mapToStreamConfigurationMode(
447 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
448 if (mode == nullptr) return BAD_VALUE;
449 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
450 switch(operationMode) {
451 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
452 *mode = StreamConfigurationMode::NORMAL_MODE;
453 break;
454 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
455 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
456 break;
457 default:
458 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
459 return BAD_VALUE;
460 }
461 } else {
462 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800463 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800464 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800465}
466
467camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
468 switch (status) {
469 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
470 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
471 }
472 return CAMERA3_BUFFER_STATUS_ERROR;
473}
474
475int Camera3Device::mapToFrameworkFormat(
476 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
477 return static_cast<uint32_t>(pixelFormat);
478}
479
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700480android_dataspace Camera3Device::mapToFrameworkDataspace(
481 DataspaceFlags dataSpace) {
482 return static_cast<android_dataspace>(dataSpace);
483}
484
Emilian Peev050f5dc2017-05-18 14:43:56 +0100485uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700486 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700487 return usage;
488}
489
Emilian Peev050f5dc2017-05-18 14:43:56 +0100490uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700491 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700492 return usage;
493}
494
Zhijun Hef7da0962014-04-24 13:27:56 -0700495ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700496 // Get max jpeg size (area-wise).
497 Size maxJpegResolution = getMaxJpegResolution();
498 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800499 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
500 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700501 return BAD_VALUE;
502 }
503
Zhijun Hef7da0962014-04-24 13:27:56 -0700504 // Get max jpeg buffer size
505 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700506 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
507 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800508 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
509 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700510 return BAD_VALUE;
511 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800513 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700514
515 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700516 float scaleFactor = ((float) (width * height)) /
517 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800518 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
519 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700520 if (jpegBufferSize > maxJpegBufferSize) {
521 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700522 }
523
524 return jpegBufferSize;
525}
526
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700527ssize_t Camera3Device::getPointCloudBufferSize() const {
528 const int FLOATS_PER_POINT=4;
529 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
530 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800531 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
532 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700533 return BAD_VALUE;
534 }
535 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
536 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
537 return maxBytesForPointCloud;
538}
539
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800540ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800541 const int PER_CONFIGURATION_SIZE = 3;
542 const int WIDTH_OFFSET = 0;
543 const int HEIGHT_OFFSET = 1;
544 const int SIZE_OFFSET = 2;
545 camera_metadata_ro_entry rawOpaqueSizes =
546 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800547 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800548 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
550 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800551 return BAD_VALUE;
552 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700553
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800554 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
555 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
556 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
557 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
558 }
559 }
560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800561 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
562 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800563 return BAD_VALUE;
564}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700565
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800566status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
567 ATRACE_CALL();
568 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700569
570 // Try to lock, but continue in case of failure (to avoid blocking in
571 // deadlocks)
572 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
573 bool gotLock = tryLockSpinRightRound(mLock);
574
575 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800576 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
577 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700578 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
580 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700581
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800582 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700583
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800584 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700585 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 int n = args.size();
587 for (int i = 0; i < n; i++) {
588 if (args[i] == templatesOption) {
589 dumpTemplates = true;
590 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700591 if (args[i] == monitorOption) {
592 if (i + 1 < n) {
593 String8 monitorTags = String8(args[i + 1]);
594 if (monitorTags == "off") {
595 mTagMonitor.disableMonitoring();
596 } else {
597 mTagMonitor.parseTagsToMonitor(monitorTags);
598 }
599 } else {
600 mTagMonitor.disableMonitoring();
601 }
602 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800603 }
604
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800605 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800607 const char *status =
608 mStatus == STATUS_ERROR ? "ERROR" :
609 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700610 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
611 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800612 mStatus == STATUS_ACTIVE ? "ACTIVE" :
613 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700614
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800615 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700616 if (mStatus == STATUS_ERROR) {
617 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
618 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800620 const char *mode =
621 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
622 mOperatingMode == static_cast<int>(
623 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
624 "CUSTOM";
625 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800626
627 if (mInputStream != NULL) {
628 write(fd, lines.string(), lines.size());
629 mInputStream->dump(fd, args);
630 } else {
631 lines.appendFormat(" No input stream.\n");
632 write(fd, lines.string(), lines.size());
633 }
634 for (size_t i = 0; i < mOutputStreams.size(); i++) {
635 mOutputStreams[i]->dump(fd,args);
636 }
637
Zhijun He431503c2016-03-07 17:30:16 -0800638 if (mBufferManager != NULL) {
639 lines = String8(" Camera3 Buffer Manager:\n");
640 write(fd, lines.string(), lines.size());
641 mBufferManager->dump(fd, args);
642 }
Zhijun He125684a2015-12-26 15:07:30 -0800643
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700644 lines = String8(" In-flight requests:\n");
645 if (mInFlightMap.size() == 0) {
646 lines.append(" None\n");
647 } else {
648 for (size_t i = 0; i < mInFlightMap.size(); i++) {
649 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700650 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700651 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800652 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700653 r.numBuffersLeft);
654 }
655 }
656 write(fd, lines.string(), lines.size());
657
Shuzhen Wang686f6442017-06-20 16:16:04 -0700658 if (mRequestThread != NULL) {
659 mRequestThread->dumpCaptureRequestLatency(fd,
660 " ProcessCaptureRequest latency histogram:");
661 }
662
Igor Murashkin1e479c02013-09-06 16:55:14 -0700663 {
664 lines = String8(" Last request sent:\n");
665 write(fd, lines.string(), lines.size());
666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700667 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700668 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
669 }
670
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800671 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800672 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 "TEMPLATE_PREVIEW",
674 "TEMPLATE_STILL_CAPTURE",
675 "TEMPLATE_VIDEO_RECORD",
676 "TEMPLATE_VIDEO_SNAPSHOT",
677 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800678 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800679 };
680
681 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800682 camera_metadata_t *templateRequest = nullptr;
683 mInterface->constructDefaultRequestSettings(
684 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800685 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800687 lines.append(" Not supported\n");
688 write(fd, lines.string(), lines.size());
689 } else {
690 write(fd, lines.string(), lines.size());
691 dump_indented_camera_metadata(templateRequest,
692 fd, /*verbosity*/2, /*indentation*/8);
693 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800694 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 }
696 }
697
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700698 mTagMonitor.dumpMonitoredMetadata(fd);
699
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800700 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800701 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800702 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800703 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800704 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800705
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700706 if (gotLock) mLock.unlock();
707 if (gotInterfaceLock) mInterfaceLock.unlock();
708
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800709 return OK;
710}
711
712const CameraMetadata& Camera3Device::info() const {
713 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
715 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700716 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800717 mStatus == STATUS_ERROR ?
718 "when in error state" : "before init");
719 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800720 return mDeviceInfo;
721}
722
Jianing Wei90e59c92014-03-12 18:29:36 -0700723status_t Camera3Device::checkStatusOkToCaptureLocked() {
724 switch (mStatus) {
725 case STATUS_ERROR:
726 CLOGE("Device has encountered a serious error");
727 return INVALID_OPERATION;
728 case STATUS_UNINITIALIZED:
729 CLOGE("Device not initialized");
730 return INVALID_OPERATION;
731 case STATUS_UNCONFIGURED:
732 case STATUS_CONFIGURED:
733 case STATUS_ACTIVE:
734 // OK
735 break;
736 default:
737 SET_ERR_L("Unexpected status: %d", mStatus);
738 return INVALID_OPERATION;
739 }
740 return OK;
741}
742
743status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000744 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700745 const std::list<const SurfaceMap> &surfaceMaps,
746 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700747 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700748 if (requestList == NULL) {
749 CLOGE("requestList cannot be NULL.");
750 return BAD_VALUE;
751 }
752
Jianing Weicb0652e2014-03-12 18:29:36 -0700753 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000754 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700755 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
756 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
757 ++metadataIt, ++surfaceMapIt) {
758 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700759 if (newRequest == 0) {
760 CLOGE("Can't create capture request");
761 return BAD_VALUE;
762 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700763
Shuzhen Wang9d066012016-09-30 11:30:20 -0700764 newRequest->mRepeating = repeating;
765
Jianing Weicb0652e2014-03-12 18:29:36 -0700766 // Setup burst Id and request Id
767 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000768 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
769 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700770 CLOGE("RequestID entry exists; but must not be empty in metadata");
771 return BAD_VALUE;
772 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
774 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700775 } else {
776 CLOGE("RequestID does not exist in metadata");
777 return BAD_VALUE;
778 }
779
Jianing Wei90e59c92014-03-12 18:29:36 -0700780 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700781
782 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700783 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
785 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
786 return BAD_VALUE;
787 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700788
789 // Setup batch size if this is a high speed video recording request.
790 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
791 auto firstRequest = requestList->begin();
792 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
793 if (outputStream->isVideoStream()) {
794 (*firstRequest)->mBatchSize = requestList->size();
795 break;
796 }
797 }
798 }
799
Jianing Wei90e59c92014-03-12 18:29:36 -0700800 return OK;
801}
802
Jianing Weicb0652e2014-03-12 18:29:36 -0700803status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800804 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800805
Emilian Peevaebbe412018-01-15 13:53:24 +0000806 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700807 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000808 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700809
Emilian Peevaebbe412018-01-15 13:53:24 +0000810 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811}
812
Emilian Peevaebbe412018-01-15 13:53:24 +0000813void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700814 std::list<const SurfaceMap>& surfaceMaps,
815 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000816 PhysicalCameraSettingsList requestList;
817 requestList.push_back({std::string(getId().string()), request});
818 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700819
820 SurfaceMap surfaceMap;
821 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
822 // With no surface list passed in, stream and surface will have 1-to-1
823 // mapping. So the surface index is 0 for each stream in the surfaceMap.
824 for (size_t i = 0; i < streams.count; i++) {
825 surfaceMap[streams.data.i32[i]].push_back(0);
826 }
827 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828}
829
Jianing Wei90e59c92014-03-12 18:29:36 -0700830status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000831 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 const std::list<const SurfaceMap> &surfaceMaps,
833 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700834 /*out*/
835 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700836 ATRACE_CALL();
837 Mutex::Autolock il(mInterfaceLock);
838 Mutex::Autolock l(mLock);
839
840 status_t res = checkStatusOkToCaptureLocked();
841 if (res != OK) {
842 // error logged by previous call
843 return res;
844 }
845
846 RequestList requestList;
847
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
849 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850 if (res != OK) {
851 // error logged by previous call
852 return res;
853 }
854
855 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700856 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700857 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700858 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 }
860
861 if (res == OK) {
862 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
863 if (res != OK) {
864 SET_ERR_L("Can't transition to active in %f seconds!",
865 kActiveTimeout/1e9);
866 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800867 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700868 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700869 } else {
870 CLOGE("Cannot queue request. Impossible.");
871 return BAD_VALUE;
872 }
873
874 return res;
875}
876
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800877hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800878 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800879 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700880 // Ideally we should grab mLock, but that can lead to deadlock, and
881 // it's not super important to get up to date value of mStatus for this
882 // warning print, hence skipping the lock here
883 if (mStatus == STATUS_ERROR) {
884 // Per API contract, HAL should act as closed after device error
885 // But mStatus can be set to error by framework as well, so just log
886 // a warning here.
887 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700888 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700889
890 if (mProcessCaptureResultLock.tryLock() != OK) {
891 // This should never happen; it indicates a wrong client implementation
892 // that doesn't follow the contract. But, we can be tolerant here.
893 ALOGE("%s: callback overlapped! waiting 1s...",
894 __FUNCTION__);
895 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
896 ALOGE("%s: cannot acquire lock in 1s, dropping results",
897 __FUNCTION__);
898 // really don't know what to do, so bail out.
899 return hardware::Void();
900 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800901 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700902 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800903 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700904 }
905 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800906 return hardware::Void();
907}
908
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800909// Only one processCaptureResult should be called at a time, so
910// the locks won't block. The locks are present here simply to enforce this.
911hardware::Return<void> Camera3Device::processCaptureResult(
912 const hardware::hidl_vec<
913 hardware::camera::device::V3_2::CaptureResult>& results) {
914 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
915
916 // Ideally we should grab mLock, but that can lead to deadlock, and
917 // it's not super important to get up to date value of mStatus for this
918 // warning print, hence skipping the lock here
919 if (mStatus == STATUS_ERROR) {
920 // Per API contract, HAL should act as closed after device error
921 // But mStatus can be set to error by framework as well, so just log
922 // a warning here.
923 ALOGW("%s: received capture result in error state.", __FUNCTION__);
924 }
925
926 if (mProcessCaptureResultLock.tryLock() != OK) {
927 // This should never happen; it indicates a wrong client implementation
928 // that doesn't follow the contract. But, we can be tolerant here.
929 ALOGE("%s: callback overlapped! waiting 1s...",
930 __FUNCTION__);
931 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
932 ALOGE("%s: cannot acquire lock in 1s, dropping results",
933 __FUNCTION__);
934 // really don't know what to do, so bail out.
935 return hardware::Void();
936 }
937 }
938 for (const auto& result : results) {
939 processOneCaptureResultLocked(result, noPhysMetadata);
940 }
941 mProcessCaptureResultLock.unlock();
942 return hardware::Void();
943}
944
945status_t Camera3Device::readOneCameraMetadataLocked(
946 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
947 const hardware::camera::device::V3_2::CameraMetadata& result) {
948 if (fmqResultSize > 0) {
949 resultMetadata.resize(fmqResultSize);
950 if (mResultMetadataQueue == nullptr) {
951 return NO_MEMORY; // logged in initialize()
952 }
953 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
954 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
955 __FUNCTION__, fmqResultSize);
956 return INVALID_OPERATION;
957 }
958 } else {
959 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
960 result.size());
961 }
962
963 if (resultMetadata.size() != 0) {
964 status_t res;
965 const camera_metadata_t* metadata =
966 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
967 size_t expected_metadata_size = resultMetadata.size();
968 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
969 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
970 __FUNCTION__, strerror(-res), res);
971 return INVALID_OPERATION;
972 }
973 }
974
975 return OK;
976}
977
Yifan Honga640c5a2017-04-12 16:30:31 -0700978void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800979 const hardware::camera::device::V3_2::CaptureResult& result,
980 const hardware::hidl_vec<
981 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800982 camera3_capture_result r;
983 status_t res;
984 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700985
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800986 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -0700987 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800988 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
989 if (res != OK) {
990 ALOGE("%s: Frame %d: Failed to read capture result metadata",
991 __FUNCTION__, result.frameNumber);
992 return;
Yifan Honga640c5a2017-04-12 16:30:31 -0700993 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800994 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -0700995
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800996 // Read and validate physical camera metadata
997 size_t physResultCount = physicalCameraMetadatas.size();
998 std::vector<const char*> physCamIds(physResultCount);
999 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1000 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1001 physResultMetadata.resize(physResultCount);
1002 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1003 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1004 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1005 if (res != OK) {
1006 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1007 __FUNCTION__, result.frameNumber,
1008 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001009 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001010 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001011 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1012 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1013 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001014 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001015 r.num_physcam_metadata = physResultCount;
1016 r.physcam_ids = physCamIds.data();
1017 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001018
1019 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1020 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1021 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1022 auto& bDst = outputBuffers[i];
1023 const StreamBuffer &bSrc = result.outputBuffers[i];
1024
1025 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001026 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001027 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1028 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001029 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001030 }
1031 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1032
1033 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001034 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001035 if (res != OK) {
1036 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1037 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001038 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001039 }
1040 bDst.buffer = buffer;
1041 bDst.status = mapHidlBufferStatus(bSrc.status);
1042 bDst.acquire_fence = -1;
1043 if (bSrc.releaseFence == nullptr) {
1044 bDst.release_fence = -1;
1045 } else if (bSrc.releaseFence->numFds == 1) {
1046 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1047 } else {
1048 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1049 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001050 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001051 }
1052 }
1053 r.num_output_buffers = outputBuffers.size();
1054 r.output_buffers = outputBuffers.data();
1055
1056 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001057 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001058 r.input_buffer = nullptr;
1059 } else {
1060 if (mInputStream->getId() != result.inputBuffer.streamId) {
1061 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1062 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001063 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001064 }
1065 inputBuffer.stream = mInputStream->asHalStream();
1066 buffer_handle_t *buffer;
1067 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1068 &buffer);
1069 if (res != OK) {
1070 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1071 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001072 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001073 }
1074 inputBuffer.buffer = buffer;
1075 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1076 inputBuffer.acquire_fence = -1;
1077 if (result.inputBuffer.releaseFence == nullptr) {
1078 inputBuffer.release_fence = -1;
1079 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1080 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1081 } else {
1082 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1083 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001084 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001085 }
1086 r.input_buffer = &inputBuffer;
1087 }
1088
1089 r.partial_result = result.partialResult;
1090
1091 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001092}
1093
1094hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001095 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001096 // Ideally we should grab mLock, but that can lead to deadlock, and
1097 // it's not super important to get up to date value of mStatus for this
1098 // warning print, hence skipping the lock here
1099 if (mStatus == STATUS_ERROR) {
1100 // Per API contract, HAL should act as closed after device error
1101 // But mStatus can be set to error by framework as well, so just log
1102 // a warning here.
1103 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001104 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001105
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001106 for (const auto& msg : msgs) {
1107 notify(msg);
1108 }
1109 return hardware::Void();
1110}
1111
1112void Camera3Device::notify(
1113 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1114
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001115 camera3_notify_msg m;
1116 switch (msg.type) {
1117 case MsgType::ERROR:
1118 m.type = CAMERA3_MSG_ERROR;
1119 m.message.error.frame_number = msg.msg.error.frameNumber;
1120 if (msg.msg.error.errorStreamId >= 0) {
1121 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001122 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001123 ALOGE("%s: Frame %d: Invalid error stream id %d",
1124 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001125 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001126 }
1127 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1128 } else {
1129 m.message.error.error_stream = nullptr;
1130 }
1131 switch (msg.msg.error.errorCode) {
1132 case ErrorCode::ERROR_DEVICE:
1133 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1134 break;
1135 case ErrorCode::ERROR_REQUEST:
1136 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1137 break;
1138 case ErrorCode::ERROR_RESULT:
1139 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1140 break;
1141 case ErrorCode::ERROR_BUFFER:
1142 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1143 break;
1144 }
1145 break;
1146 case MsgType::SHUTTER:
1147 m.type = CAMERA3_MSG_SHUTTER;
1148 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1149 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1150 break;
1151 }
1152 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001153}
1154
Emilian Peevaebbe412018-01-15 13:53:24 +00001155status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001156 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001157 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001158 ATRACE_CALL();
1159
Emilian Peevaebbe412018-01-15 13:53:24 +00001160 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001161}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001162
Jianing Weicb0652e2014-03-12 18:29:36 -07001163status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1164 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001165 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001166
Emilian Peevaebbe412018-01-15 13:53:24 +00001167 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001168 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001169 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001170
Emilian Peevaebbe412018-01-15 13:53:24 +00001171 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173}
1174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175status_t Camera3Device::setStreamingRequestList(
1176 const List<const PhysicalCameraSettingsList> &requestsList,
1177 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001178 ATRACE_CALL();
1179
Emilian Peevaebbe412018-01-15 13:53:24 +00001180 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001181}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182
1183sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 status_t res;
1186
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001187 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001188 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1189 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001190 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1191 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001192 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001194 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001196 } else if (mStatus == STATUS_UNCONFIGURED) {
1197 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001198 CLOGE("No streams configured");
1199 return NULL;
1200 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 }
1202
Shuzhen Wang0129d522016-10-30 22:43:41 -07001203 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205}
1206
Jianing Weicb0652e2014-03-12 18:29:36 -07001207status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001208 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001209 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 switch (mStatus) {
1213 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001214 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 return INVALID_OPERATION;
1216 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001217 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001219 case STATUS_UNCONFIGURED:
1220 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 case STATUS_ACTIVE:
1222 // OK
1223 break;
1224 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001225 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 return INVALID_OPERATION;
1227 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001228 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001229
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001230 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001231}
1232
1233status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1234 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001236
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001237 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238}
1239
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001240status_t Camera3Device::createInputStream(
1241 uint32_t width, uint32_t height, int format, int *id) {
1242 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001244 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001245 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001246 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1247 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001248
1249 status_t res;
1250 bool wasActive = false;
1251
1252 switch (mStatus) {
1253 case STATUS_ERROR:
1254 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1255 return INVALID_OPERATION;
1256 case STATUS_UNINITIALIZED:
1257 ALOGE("%s: Device not initialized", __FUNCTION__);
1258 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 case STATUS_UNCONFIGURED:
1260 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001261 // OK
1262 break;
1263 case STATUS_ACTIVE:
1264 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001265 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001266 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001268 return res;
1269 }
1270 wasActive = true;
1271 break;
1272 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001273 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001274 return INVALID_OPERATION;
1275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001276 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001277
1278 if (mInputStream != 0) {
1279 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1280 return INVALID_OPERATION;
1281 }
1282
1283 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1284 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001285 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001286
1287 mInputStream = newStream;
1288
1289 *id = mNextStreamId++;
1290
1291 // Continue captures if active at start
1292 if (wasActive) {
1293 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001294 // Reuse current operating mode and session parameters for new stream config
1295 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001296 if (res != OK) {
1297 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1298 __FUNCTION__, mNextStreamId, strerror(-res), res);
1299 return res;
1300 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001302 }
1303
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001304 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001305 return OK;
1306}
1307
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001308status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001309 uint32_t width, uint32_t height, int format,
1310 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001311 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001312 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_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 Wangc28189a2017-11-27 23:05:10 -08001324 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1325 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001326}
1327
1328status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1329 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1330 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001331 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001332 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001333 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001334
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001335 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001336 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001338 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1340 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1341 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001342
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001343 status_t res;
1344 bool wasActive = false;
1345
1346 switch (mStatus) {
1347 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001348 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001349 return INVALID_OPERATION;
1350 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001351 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001353 case STATUS_UNCONFIGURED:
1354 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001355 // OK
1356 break;
1357 case STATUS_ACTIVE:
1358 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001359 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001360 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001361 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 return res;
1363 }
1364 wasActive = true;
1365 break;
1366 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001367 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return INVALID_OPERATION;
1369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001370 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371
1372 sp<Camera3OutputStream> newStream;
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
Shuzhen Wang0129d522016-10-30 22:43:41 -07001379 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001380 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1381 return BAD_VALUE;
1382 }
1383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001385 ssize_t blobBufferSize;
1386 if (dataSpace != HAL_DATASPACE_DEPTH) {
1387 blobBufferSize = getJpegBufferSize(width, height);
1388 if (blobBufferSize <= 0) {
1389 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1390 return BAD_VALUE;
1391 }
1392 } else {
1393 blobBufferSize = getPointCloudBufferSize();
1394 if (blobBufferSize <= 0) {
1395 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1396 return BAD_VALUE;
1397 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001398 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001399 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001400 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001401 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001402 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1403 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1404 if (rawOpaqueBufferSize <= 0) {
1405 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1406 return BAD_VALUE;
1407 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001408 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001409 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001410 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001411 } else if (isShared) {
1412 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1413 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001414 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001415 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001416 newStream = new Camera3OutputStream(mNextStreamId,
1417 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001418 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001420 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001421 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001422 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 }
Emilian Peev40ead602017-09-26 15:46:36 +01001424
1425 size_t consumerCount = consumers.size();
1426 for (size_t i = 0; i < consumerCount; i++) {
1427 int id = newStream->getSurfaceId(consumers[i]);
1428 if (id < 0) {
1429 SET_ERR_L("Invalid surface id");
1430 return BAD_VALUE;
1431 }
1432 if (surfaceIds != nullptr) {
1433 surfaceIds->push_back(id);
1434 }
1435 }
1436
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001437 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438
Emilian Peev08dd2452017-04-06 16:55:14 +01001439 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 res = mOutputStreams.add(mNextStreamId, newStream);
1442 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001444 return res;
1445 }
1446
1447 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001448 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449
1450 // Continue captures if active at start
1451 if (wasActive) {
1452 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001453 // Reuse current operating mode and session parameters for new stream config
1454 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001456 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1457 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 return res;
1459 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001460 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001462 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001464}
1465
Emilian Peev710c1422017-08-30 11:19:38 +01001466status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001468 if (nullptr == streamInfo) {
1469 return BAD_VALUE;
1470 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001471 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001473
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 switch (mStatus) {
1475 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001476 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 return INVALID_OPERATION;
1478 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 case STATUS_UNCONFIGURED:
1482 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 case STATUS_ACTIVE:
1484 // OK
1485 break;
1486 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return INVALID_OPERATION;
1489 }
1490
1491 ssize_t idx = mOutputStreams.indexOfKey(id);
1492 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001493 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 return idx;
1495 }
1496
Emilian Peev710c1422017-08-30 11:19:38 +01001497 streamInfo->width = mOutputStreams[idx]->getWidth();
1498 streamInfo->height = mOutputStreams[idx]->getHeight();
1499 streamInfo->format = mOutputStreams[idx]->getFormat();
1500 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1501 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1502 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001503 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1504 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
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
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001556 if (mStatus == STATUS_ERROR) {
1557 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1558 __FUNCTION__, mId.string());
1559 return -EBUSY;
1560 }
1561
Igor Murashkin2fba5842013-04-22 14:03:54 -07001562 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001563 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 if (mInputStream != NULL && id == mInputStream->getId()) {
1565 deletedStream = mInputStream;
1566 mInputStream.clear();
1567 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001568 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001569 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return BAD_VALUE;
1571 }
Zhijun He5f446352014-01-22 09:49:33 -08001572 }
1573
1574 // Delete output stream or the output part of a bi-directional stream.
1575 if (outputStreamIdx != NAME_NOT_FOUND) {
1576 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 mOutputStreams.removeItem(id);
1578 }
1579
1580 // Free up the stream endpoint so that it can be used by some other stream
1581 res = deletedStream->disconnect();
1582 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001583 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 // fall through since we want to still list the stream as deleted.
1585 }
1586 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001587 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588
1589 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590}
1591
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001592status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001593 ATRACE_CALL();
1594 ALOGV("%s: E", __FUNCTION__);
1595
1596 Mutex::Autolock il(mInterfaceLock);
1597 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001598
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001599 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1600}
1601
1602status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1603 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001604 //Filter out any incoming session parameters
1605 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001606 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1607 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001608 CameraMetadata filteredParams(availableSessionKeys.count);
1609 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1610 filteredParams.getAndLock());
1611 set_camera_metadata_vendor_id(meta, mVendorTagId);
1612 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001613 if (availableSessionKeys.count > 0) {
1614 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1615 camera_metadata_ro_entry entry = params.find(
1616 availableSessionKeys.data.i32[i]);
1617 if (entry.count > 0) {
1618 filteredParams.update(entry);
1619 }
1620 }
1621 }
1622
1623 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001624}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001626status_t Camera3Device::getInputBufferProducer(
1627 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001628 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001629 Mutex::Autolock il(mInterfaceLock);
1630 Mutex::Autolock l(mLock);
1631
1632 if (producer == NULL) {
1633 return BAD_VALUE;
1634 } else if (mInputStream == NULL) {
1635 return INVALID_OPERATION;
1636 }
1637
1638 return mInputStream->getInputBufferProducer(producer);
1639}
1640
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641status_t Camera3Device::createDefaultRequest(int templateId,
1642 CameraMetadata *request) {
1643 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001644 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001645
1646 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1647 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1648 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1649 return BAD_VALUE;
1650 }
1651
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001652 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001653
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001654 {
1655 Mutex::Autolock l(mLock);
1656 switch (mStatus) {
1657 case STATUS_ERROR:
1658 CLOGE("Device has encountered a serious error");
1659 return INVALID_OPERATION;
1660 case STATUS_UNINITIALIZED:
1661 CLOGE("Device is not initialized!");
1662 return INVALID_OPERATION;
1663 case STATUS_UNCONFIGURED:
1664 case STATUS_CONFIGURED:
1665 case STATUS_ACTIVE:
1666 // OK
1667 break;
1668 default:
1669 SET_ERR_L("Unexpected status: %d", mStatus);
1670 return INVALID_OPERATION;
1671 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001673 if (!mRequestTemplateCache[templateId].isEmpty()) {
1674 *request = mRequestTemplateCache[templateId];
1675 return OK;
1676 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001677 }
1678
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001679 camera_metadata_t *rawRequest;
1680 status_t res = mInterface->constructDefaultRequestSettings(
1681 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001682
1683 {
1684 Mutex::Autolock l(mLock);
1685 if (res == BAD_VALUE) {
1686 ALOGI("%s: template %d is not supported on this camera device",
1687 __FUNCTION__, templateId);
1688 return res;
1689 } else if (res != OK) {
1690 CLOGE("Unable to construct request template %d: %s (%d)",
1691 templateId, strerror(-res), res);
1692 return res;
1693 }
1694
1695 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1696 mRequestTemplateCache[templateId].acquire(rawRequest);
1697
1698 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001699 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700 return OK;
1701}
1702
1703status_t Camera3Device::waitUntilDrained() {
1704 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001706 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001707 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001709 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001710}
1711
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001712status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001713 switch (mStatus) {
1714 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001715 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001716 ALOGV("%s: Already idle", __FUNCTION__);
1717 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001718 case STATUS_CONFIGURED:
1719 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001720 case STATUS_ERROR:
1721 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 break;
1724 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001725 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726 return INVALID_OPERATION;
1727 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001728 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1729 maxExpectedDuration);
1730 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001731 if (res != OK) {
1732 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1733 res);
1734 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 return res;
1736}
1737
Ruben Brunk183f0562015-08-12 12:55:02 -07001738
1739void Camera3Device::internalUpdateStatusLocked(Status status) {
1740 mStatus = status;
1741 mRecentStatusUpdates.add(mStatus);
1742 mStatusChanged.broadcast();
1743}
1744
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001745void Camera3Device::pauseStateNotify(bool enable) {
1746 Mutex::Autolock il(mInterfaceLock);
1747 Mutex::Autolock l(mLock);
1748
1749 mPauseStateNotify = enable;
1750}
1751
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001752// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001753status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001755
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001756 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1757 maxExpectedDuration);
1758 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001759 if (res != OK) {
1760 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001761 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 }
1763
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001764 return res;
1765}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001766
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001767// Resume after internalPauseAndWaitLocked
1768status_t Camera3Device::internalResumeLocked() {
1769 status_t res;
1770
1771 mRequestThread->setPaused(false);
1772
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001773 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1774 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001775 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1776 if (res != OK) {
1777 SET_ERR_L("Can't transition to active in %f seconds!",
1778 kActiveTimeout/1e9);
1779 }
1780 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001782}
1783
Ruben Brunk183f0562015-08-12 12:55:02 -07001784status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001786
1787 size_t startIndex = 0;
1788 if (mStatusWaiters == 0) {
1789 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1790 // this status list
1791 mRecentStatusUpdates.clear();
1792 } else {
1793 // If other threads are waiting on updates to this status list, set the position of the
1794 // first element that this list will check rather than clearing the list.
1795 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001796 }
1797
Ruben Brunk183f0562015-08-12 12:55:02 -07001798 mStatusWaiters++;
1799
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 bool stateSeen = false;
1801 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001802 if (active == (mStatus == STATUS_ACTIVE)) {
1803 // Desired state is current
1804 break;
1805 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806
1807 res = mStatusChanged.waitRelative(mLock, timeout);
1808 if (res != OK) break;
1809
Ruben Brunk183f0562015-08-12 12:55:02 -07001810 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1811 // transitions.
1812 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1813 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1814 __FUNCTION__);
1815
1816 // Encountered desired state since we began waiting
1817 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1819 stateSeen = true;
1820 break;
1821 }
1822 }
1823 } while (!stateSeen);
1824
Ruben Brunk183f0562015-08-12 12:55:02 -07001825 mStatusWaiters--;
1826
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827 return res;
1828}
1829
1830
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001831status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001832 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001833 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001834
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001835 if (listener != NULL && mListener != NULL) {
1836 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1837 }
1838 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001839 mRequestThread->setNotificationListener(listener);
1840 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001841
1842 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001843}
1844
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001845bool Camera3Device::willNotify3A() {
1846 return false;
1847}
1848
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001849status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001850 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001851 status_t res;
1852 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001853
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001854 while (mResultQueue.empty()) {
1855 res = mResultSignal.waitRelative(mOutputLock, timeout);
1856 if (res == TIMED_OUT) {
1857 return res;
1858 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001859 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1860 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001861 return res;
1862 }
1863 }
1864 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001865}
1866
Jianing Weicb0652e2014-03-12 18:29:36 -07001867status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001868 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001869 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001870
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001871 if (mResultQueue.empty()) {
1872 return NOT_ENOUGH_DATA;
1873 }
1874
Jianing Weicb0652e2014-03-12 18:29:36 -07001875 if (frame == NULL) {
1876 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1877 return BAD_VALUE;
1878 }
1879
1880 CaptureResult &result = *(mResultQueue.begin());
1881 frame->mResultExtras = result.mResultExtras;
1882 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001883 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001884 mResultQueue.erase(mResultQueue.begin());
1885
1886 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001887}
1888
1889status_t Camera3Device::triggerAutofocus(uint32_t id) {
1890 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001893 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1894 // Mix-in this trigger into the next request and only the next request.
1895 RequestTrigger trigger[] = {
1896 {
1897 ANDROID_CONTROL_AF_TRIGGER,
1898 ANDROID_CONTROL_AF_TRIGGER_START
1899 },
1900 {
1901 ANDROID_CONTROL_AF_TRIGGER_ID,
1902 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001903 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001904 };
1905
1906 return mRequestThread->queueTrigger(trigger,
1907 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001908}
1909
1910status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1911 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001912 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001914 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1915 // Mix-in this trigger into the next request and only the next request.
1916 RequestTrigger trigger[] = {
1917 {
1918 ANDROID_CONTROL_AF_TRIGGER,
1919 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1920 },
1921 {
1922 ANDROID_CONTROL_AF_TRIGGER_ID,
1923 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001924 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001925 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001927 return mRequestThread->queueTrigger(trigger,
1928 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001929}
1930
1931status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1932 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001934
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001935 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1936 // Mix-in this trigger into the next request and only the next request.
1937 RequestTrigger trigger[] = {
1938 {
1939 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1940 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1941 },
1942 {
1943 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1944 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001945 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001946 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001948 return mRequestThread->queueTrigger(trigger,
1949 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950}
1951
Jianing Weicb0652e2014-03-12 18:29:36 -07001952status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001953 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001954 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001955 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001956
Zhijun He7ef20392014-04-21 16:04:17 -07001957 {
1958 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001959 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001960 }
1961
Emilian Peev08dd2452017-04-06 16:55:14 +01001962 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001963}
1964
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001965status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001966 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1967}
1968
1969status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001970 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001971 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001972 Mutex::Autolock il(mInterfaceLock);
1973 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001974
1975 sp<Camera3StreamInterface> stream;
1976 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1977 if (outputStreamIdx == NAME_NOT_FOUND) {
1978 CLOGE("Stream %d does not exist", streamId);
1979 return BAD_VALUE;
1980 }
1981
1982 stream = mOutputStreams.editValueAt(outputStreamIdx);
1983
1984 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001985 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001986 return BAD_VALUE;
1987 }
1988
1989 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001990 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001991 return BAD_VALUE;
1992 }
1993
Ruben Brunkc78ac262015-08-13 17:58:46 -07001994 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001995}
1996
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001997status_t Camera3Device::tearDown(int streamId) {
1998 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001999 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002000 Mutex::Autolock il(mInterfaceLock);
2001 Mutex::Autolock l(mLock);
2002
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002003 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
2012 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2013 CLOGE("Stream %d is a target of a in-progress request", streamId);
2014 return BAD_VALUE;
2015 }
2016
2017 return stream->tearDown();
2018}
2019
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002020status_t Camera3Device::addBufferListenerForStream(int streamId,
2021 wp<Camera3StreamBufferListener> listener) {
2022 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002023 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002024 Mutex::Autolock il(mInterfaceLock);
2025 Mutex::Autolock l(mLock);
2026
2027 sp<Camera3StreamInterface> stream;
2028 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2029 if (outputStreamIdx == NAME_NOT_FOUND) {
2030 CLOGE("Stream %d does not exist", streamId);
2031 return BAD_VALUE;
2032 }
2033
2034 stream = mOutputStreams.editValueAt(outputStreamIdx);
2035 stream->addBufferListener(listener);
2036
2037 return OK;
2038}
2039
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002041 * Methods called by subclasses
2042 */
2043
2044void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002045 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002046 {
2047 // Need mLock to safely update state and synchronize to current
2048 // state of methods in flight.
2049 Mutex::Autolock l(mLock);
2050 // We can get various system-idle notices from the status tracker
2051 // while starting up. Only care about them if we've actually sent
2052 // in some requests recently.
2053 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2054 return;
2055 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002056 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2057 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002058 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002059
2060 // Skip notifying listener if we're doing some user-transparent
2061 // state changes
2062 if (mPauseStateNotify) return;
2063 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002064
2065 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066 {
2067 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002068 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002069 }
2070 if (idle && listener != NULL) {
2071 listener->notifyIdle();
2072 }
2073}
2074
Shuzhen Wang758c2152017-01-10 18:26:18 -08002075status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002076 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002077 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002078 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2079 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002080
2081 if (surfaceIds == nullptr) {
2082 return BAD_VALUE;
2083 }
2084
Zhijun He5d677d12016-05-29 16:52:39 -07002085 Mutex::Autolock il(mInterfaceLock);
2086 Mutex::Autolock l(mLock);
2087
Shuzhen Wang758c2152017-01-10 18:26:18 -08002088 if (consumers.size() == 0) {
2089 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002090 return BAD_VALUE;
2091 }
2092
2093 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2094 if (idx == NAME_NOT_FOUND) {
2095 CLOGE("Stream %d is unknown", streamId);
2096 return idx;
2097 }
2098 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002099 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002100 if (res != OK) {
2101 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2102 return res;
2103 }
2104
Emilian Peev40ead602017-09-26 15:46:36 +01002105 for (auto &consumer : consumers) {
2106 int id = stream->getSurfaceId(consumer);
2107 if (id < 0) {
2108 CLOGE("Invalid surface id!");
2109 return BAD_VALUE;
2110 }
2111 surfaceIds->push_back(id);
2112 }
2113
Shuzhen Wang0129d522016-10-30 22:43:41 -07002114 if (stream->isConsumerConfigurationDeferred()) {
2115 if (!stream->isConfiguring()) {
2116 CLOGE("Stream %d was already fully configured.", streamId);
2117 return INVALID_OPERATION;
2118 }
Zhijun He5d677d12016-05-29 16:52:39 -07002119
Shuzhen Wang0129d522016-10-30 22:43:41 -07002120 res = stream->finishConfiguration();
2121 if (res != OK) {
2122 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2123 stream->getId(), strerror(-res), res);
2124 return res;
2125 }
Zhijun He5d677d12016-05-29 16:52:39 -07002126 }
2127
2128 return OK;
2129}
2130
Emilian Peev40ead602017-09-26 15:46:36 +01002131status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2132 const std::vector<OutputStreamInfo> &outputInfo,
2133 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2134 Mutex::Autolock il(mInterfaceLock);
2135 Mutex::Autolock l(mLock);
2136
2137 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2138 if (idx == NAME_NOT_FOUND) {
2139 CLOGE("Stream %d is unknown", streamId);
2140 return idx;
2141 }
2142
2143 for (const auto &it : removedSurfaceIds) {
2144 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2145 CLOGE("Shared surface still part of a pending request!");
2146 return -EBUSY;
2147 }
2148 }
2149
2150 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2151 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2152 if (res != OK) {
2153 CLOGE("Stream %d failed to update stream (error %d %s) ",
2154 streamId, res, strerror(-res));
2155 if (res == UNKNOWN_ERROR) {
2156 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2157 __FUNCTION__);
2158 }
2159 return res;
2160 }
2161
2162 return res;
2163}
2164
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002165status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2166 Mutex::Autolock il(mInterfaceLock);
2167 Mutex::Autolock l(mLock);
2168
2169 int idx = mOutputStreams.indexOfKey(streamId);
2170 if (idx == NAME_NOT_FOUND) {
2171 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2172 return BAD_VALUE;
2173 }
2174
2175 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2176 return stream->dropBuffers(dropping);
2177}
2178
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002179/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002180 * Camera3Device private methods
2181 */
2182
2183sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002184 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185 ATRACE_CALL();
2186 status_t res;
2187
2188 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002189 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002190
2191 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002192 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 if (inputStreams.count > 0) {
2194 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002195 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002196 CLOGE("Request references unknown input stream %d",
2197 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198 return NULL;
2199 }
2200 // Lazy completion of stream configuration (allocation/registration)
2201 // on first use
2202 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002203 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002204 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002205 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002206 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002207 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002208 return NULL;
2209 }
2210 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002211 // Check if stream is being prepared
2212 if (mInputStream->isPreparing()) {
2213 CLOGE("Request references an input stream that's being prepared!");
2214 return NULL;
2215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002216
2217 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002218 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002219 }
2220
2221 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002222 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002224 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225 return NULL;
2226 }
2227
2228 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002229 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002230 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002231 CLOGE("Request references unknown stream %d",
2232 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002233 return NULL;
2234 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002235 sp<Camera3OutputStreamInterface> stream =
2236 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002237
Zhijun He5d677d12016-05-29 16:52:39 -07002238 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002239 auto iter = surfaceMap.find(streams.data.i32[i]);
2240 if (iter != surfaceMap.end()) {
2241 const std::vector<size_t>& surfaces = iter->second;
2242 for (const auto& surface : surfaces) {
2243 if (stream->isConsumerConfigurationDeferred(surface)) {
2244 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2245 "due to deferred consumer", stream->getId(), surface);
2246 return NULL;
2247 }
2248 }
2249 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002250 }
2251
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 // Lazy completion of stream configuration (allocation/registration)
2253 // on first use
2254 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002255 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002256 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002257 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2258 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259 return NULL;
2260 }
2261 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002262 // Check if stream is being prepared
2263 if (stream->isPreparing()) {
2264 CLOGE("Request references an output stream that's being prepared!");
2265 return NULL;
2266 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002267
2268 newRequest->mOutputStreams.push(stream);
2269 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002270 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002271 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002272
2273 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002274}
2275
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002276bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2277 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2278 Size size = mSupportedOpaqueInputSizes[i];
2279 if (size.width == width && size.height == height) {
2280 return true;
2281 }
2282 }
2283
2284 return false;
2285}
2286
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002287void Camera3Device::cancelStreamsConfigurationLocked() {
2288 int res = OK;
2289 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2290 res = mInputStream->cancelConfiguration();
2291 if (res != OK) {
2292 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2293 mInputStream->getId(), strerror(-res), res);
2294 }
2295 }
2296
2297 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2298 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2299 if (outputStream->isConfiguring()) {
2300 res = outputStream->cancelConfiguration();
2301 if (res != OK) {
2302 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2303 outputStream->getId(), strerror(-res), res);
2304 }
2305 }
2306 }
2307
2308 // Return state to that at start of call, so that future configures
2309 // properly clean things up
2310 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2311 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002312
2313 res = mPreparerThread->resume();
2314 if (res != OK) {
2315 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2316 }
2317}
2318
2319bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2320 ATRACE_CALL();
2321 bool ret = false;
2322
2323 Mutex::Autolock il(mInterfaceLock);
2324 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2325
2326 Mutex::Autolock l(mLock);
2327 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2328 if (rc == NO_ERROR) {
2329 mNeedConfig = true;
2330 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2331 if (rc == NO_ERROR) {
2332 ret = true;
2333 mPauseStateNotify = false;
2334 //Moving to active state while holding 'mLock' is important.
2335 //There could be pending calls to 'create-/deleteStream' which
2336 //will trigger another stream configuration while the already
2337 //present streams end up with outstanding buffers that will
2338 //not get drained.
2339 internalUpdateStatusLocked(STATUS_ACTIVE);
2340 } else {
2341 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2342 __FUNCTION__, rc);
2343 }
2344 } else {
2345 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2346 }
2347
2348 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002349}
2350
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002351status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002352 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002353 ATRACE_CALL();
2354 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002355
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002356 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002357 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002358 return INVALID_OPERATION;
2359 }
2360
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002361 if (operatingMode < 0) {
2362 CLOGE("Invalid operating mode: %d", operatingMode);
2363 return BAD_VALUE;
2364 }
2365
2366 bool isConstrainedHighSpeed =
2367 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2368 operatingMode;
2369
2370 if (mOperatingMode != operatingMode) {
2371 mNeedConfig = true;
2372 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2373 mOperatingMode = operatingMode;
2374 }
2375
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002376 if (!mNeedConfig) {
2377 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2378 return OK;
2379 }
2380
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002381 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2382 // adding a dummy stream instead.
2383 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2384 if (mOutputStreams.size() == 0) {
2385 addDummyStreamLocked();
2386 } else {
2387 tryRemoveDummyStreamLocked();
2388 }
2389
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002391 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002393 mPreparerThread->pause();
2394
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002396 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2398
2399 Vector<camera3_stream_t*> streams;
2400 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002401 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002402
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002403
2404 if (mInputStream != NULL) {
2405 camera3_stream_t *inputStream;
2406 inputStream = mInputStream->startConfiguration();
2407 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002408 CLOGE("Can't start input stream configuration");
2409 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002410 return INVALID_OPERATION;
2411 }
2412 streams.add(inputStream);
2413 }
2414
2415 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002416
2417 // Don't configure bidi streams twice, nor add them twice to the list
2418 if (mOutputStreams[i].get() ==
2419 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2420
2421 config.num_streams--;
2422 continue;
2423 }
2424
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 camera3_stream_t *outputStream;
2426 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2427 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002428 CLOGE("Can't start output stream configuration");
2429 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002430 return INVALID_OPERATION;
2431 }
2432 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002433
2434 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2435 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002436 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2437 // always occupy the initial entry.
2438 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002439 getJpegBufferSize(outputStream->width, outputStream->height));
2440 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441 }
2442
2443 config.streams = streams.editArray();
2444
2445 // Do the HAL configuration; will potentially touch stream
2446 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002447
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002448 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002449 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002450 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002451
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002452 if (res == BAD_VALUE) {
2453 // HAL rejected this set of streams as unsupported, clean up config
2454 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002455 CLOGE("Set of requested inputs/outputs not supported by HAL");
2456 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002457 return BAD_VALUE;
2458 } else if (res != OK) {
2459 // Some other kind of error from configure_streams - this is not
2460 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002461 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2462 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002463 return res;
2464 }
2465
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002466 // Finish all stream configuration immediately.
2467 // TODO: Try to relax this later back to lazy completion, which should be
2468 // faster
2469
Igor Murashkin073f8572013-05-02 14:59:28 -07002470 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002471 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002472 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002473 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002474 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002475 cancelStreamsConfigurationLocked();
2476 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002477 }
2478 }
2479
2480 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002481 sp<Camera3OutputStreamInterface> outputStream =
2482 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002483 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002484 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002485 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002486 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002487 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002488 cancelStreamsConfigurationLocked();
2489 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002490 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002491 }
2492 }
2493
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002494 // Request thread needs to know to avoid using repeat-last-settings protocol
2495 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002496 if (notifyRequestThread) {
2497 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2498 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002499
Zhijun He90f7c372016-08-16 16:19:43 -07002500 char value[PROPERTY_VALUE_MAX];
2501 property_get("camera.fifo.disable", value, "0");
2502 int32_t disableFifo = atoi(value);
2503 if (disableFifo != 1) {
2504 // Boost priority of request thread to SCHED_FIFO.
2505 pid_t requestThreadTid = mRequestThread->getTid();
2506 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002507 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002508 if (res != OK) {
2509 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2510 strerror(-res), res);
2511 } else {
2512 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2513 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002514 }
2515
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002516 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002517 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2518 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2519 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2520 sessionParams.unlock(newSessionParams);
2521 mSessionParams.unlock(currentSessionParams);
2522 if (updateSessionParams) {
2523 mSessionParams = sessionParams;
2524 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002525
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002526 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002527
Ruben Brunk183f0562015-08-12 12:55:02 -07002528 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2529 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002530
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002531 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002532
Zhijun He0a210512014-07-24 13:45:15 -07002533 // tear down the deleted streams after configure streams.
2534 mDeletedStreams.clear();
2535
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002536 auto rc = mPreparerThread->resume();
2537 if (rc != OK) {
2538 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2539 return rc;
2540 }
2541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002542 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002543}
2544
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002545status_t Camera3Device::addDummyStreamLocked() {
2546 ATRACE_CALL();
2547 status_t res;
2548
2549 if (mDummyStreamId != NO_STREAM) {
2550 // Should never be adding a second dummy stream when one is already
2551 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002552 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2553 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002554 return INVALID_OPERATION;
2555 }
2556
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002557 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002558
2559 sp<Camera3OutputStreamInterface> dummyStream =
2560 new Camera3DummyStream(mNextStreamId);
2561
2562 res = mOutputStreams.add(mNextStreamId, dummyStream);
2563 if (res < 0) {
2564 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2565 return res;
2566 }
2567
2568 mDummyStreamId = mNextStreamId;
2569 mNextStreamId++;
2570
2571 return OK;
2572}
2573
2574status_t Camera3Device::tryRemoveDummyStreamLocked() {
2575 ATRACE_CALL();
2576 status_t res;
2577
2578 if (mDummyStreamId == NO_STREAM) return OK;
2579 if (mOutputStreams.size() == 1) return OK;
2580
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002581 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002582
2583 // Ok, have a dummy stream and there's at least one other output stream,
2584 // so remove the dummy
2585
2586 sp<Camera3StreamInterface> deletedStream;
2587 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2588 if (outputStreamIdx == NAME_NOT_FOUND) {
2589 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2590 return INVALID_OPERATION;
2591 }
2592
2593 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2594 mOutputStreams.removeItemsAt(outputStreamIdx);
2595
2596 // Free up the stream endpoint so that it can be used by some other stream
2597 res = deletedStream->disconnect();
2598 if (res != OK) {
2599 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2600 // fall through since we want to still list the stream as deleted.
2601 }
2602 mDeletedStreams.add(deletedStream);
2603 mDummyStreamId = NO_STREAM;
2604
2605 return res;
2606}
2607
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002608void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002609 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002610 Mutex::Autolock l(mLock);
2611 va_list args;
2612 va_start(args, fmt);
2613
2614 setErrorStateLockedV(fmt, args);
2615
2616 va_end(args);
2617}
2618
2619void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002620 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002621 Mutex::Autolock l(mLock);
2622 setErrorStateLockedV(fmt, args);
2623}
2624
2625void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2626 va_list args;
2627 va_start(args, fmt);
2628
2629 setErrorStateLockedV(fmt, args);
2630
2631 va_end(args);
2632}
2633
2634void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002635 // Print out all error messages to log
2636 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002637 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002638
2639 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002640 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002641
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002642 mErrorCause = errorCause;
2643
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002644 if (mRequestThread != nullptr) {
2645 mRequestThread->setPaused(true);
2646 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002647 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002648
2649 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002650 sp<NotificationListener> listener = mListener.promote();
2651 if (listener != NULL) {
2652 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002653 CaptureResultExtras());
2654 }
2655
2656 // Save stack trace. View by dumping it later.
2657 CameraTraces::saveTrace();
2658 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002659}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
2661/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002662 * In-flight request management
2663 */
2664
Jianing Weicb0652e2014-03-12 18:29:36 -07002665status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002666 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002667 bool hasAppCallback, nsecs_t maxExpectedDuration,
2668 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002669 ATRACE_CALL();
2670 Mutex::Autolock l(mInFlightLock);
2671
2672 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002673 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002674 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002675 if (res < 0) return res;
2676
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002677 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002678 // hold mLock to prevent race with disconnect
2679 Mutex::Autolock l(mLock);
2680 if (mStatusTracker != nullptr) {
2681 mStatusTracker->markComponentActive(mInFlightStatusId);
2682 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002683 }
2684
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002685 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002686 return OK;
2687}
2688
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002689void Camera3Device::returnOutputBuffers(
2690 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2691 nsecs_t timestamp) {
2692 for (size_t i = 0; i < numBuffers; i++)
2693 {
2694 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2695 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2696 // Note: stream may be deallocated at this point, if this buffer was
2697 // the last reference to it.
2698 if (res != OK) {
2699 ALOGE("Can't return buffer to its stream: %s (%d)",
2700 strerror(-res), res);
2701 }
2702 }
2703}
2704
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002705void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002706 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002707 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002708 mInFlightMap.removeItemsAt(idx, 1);
2709
2710 // Indicate idle inFlightMap to the status tracker
2711 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002712 // hold mLock to prevent race with disconnect
2713 Mutex::Autolock l(mLock);
2714 if (mStatusTracker != nullptr) {
2715 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2716 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002717 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002718 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002719}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002720
2721void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2722
2723 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2724 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2725
2726 nsecs_t sensorTimestamp = request.sensorTimestamp;
2727 nsecs_t shutterTimestamp = request.shutterTimestamp;
2728
2729 // Check if it's okay to remove the request from InFlightMap:
2730 // In the case of a successful request:
2731 // all input and output buffers, all result metadata, shutter callback
2732 // arrived.
2733 // In the case of a unsuccessful request:
2734 // all input and output buffers arrived.
2735 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002736 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002737 (request.haveResultMetadata && shutterTimestamp != 0))) {
2738 ATRACE_ASYNC_END("frame capture", frameNumber);
2739
Shuzhen Wang403044a2017-02-26 23:29:04 -08002740 // Sanity check - if sensor timestamp matches shutter timestamp in the
2741 // case of request having callback.
2742 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002743 sensorTimestamp != shutterTimestamp) {
2744 SET_ERR("sensor timestamp (%" PRId64
2745 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2746 sensorTimestamp, frameNumber, shutterTimestamp);
2747 }
2748
2749 // for an unsuccessful request, it may have pending output buffers to
2750 // return.
2751 assert(request.requestStatus != OK ||
2752 request.pendingOutputBuffers.size() == 0);
2753 returnOutputBuffers(request.pendingOutputBuffers.array(),
2754 request.pendingOutputBuffers.size(), 0);
2755
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002756 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2758 }
2759
2760 // Sanity check - if we have too many in-flight frames, something has
2761 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002762 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002763 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002764 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2765 kInFlightWarnLimitHighSpeed) {
2766 CLOGE("In-flight list too large for high speed configuration: %zu",
2767 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002768 }
2769}
2770
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002771void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002772 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002773 { // First return buffers cached in mInFlightMap
2774 Mutex::Autolock l(mInFlightLock);
2775 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2776 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2777 returnOutputBuffers(request.pendingOutputBuffers.array(),
2778 request.pendingOutputBuffers.size(), 0);
2779 }
2780 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002781 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002782 }
2783
2784 // Then return all inflight buffers not returned by HAL
2785 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2786 mInterface->getInflightBufferKeys(&inflightKeys);
2787
2788 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2789 for (auto& pair : inflightKeys) {
2790 int32_t frameNumber = pair.first;
2791 int32_t streamId = pair.second;
2792 buffer_handle_t* buffer;
2793 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2794 if (res != OK) {
2795 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2796 __FUNCTION__, frameNumber, streamId);
2797 continue;
2798 }
2799
2800 camera3_stream_buffer_t streamBuffer;
2801 streamBuffer.buffer = buffer;
2802 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2803 streamBuffer.acquire_fence = -1;
2804 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002805
2806 // First check if the buffer belongs to deleted stream
2807 bool streamDeleted = false;
2808 for (auto& stream : mDeletedStreams) {
2809 if (streamId == stream->getId()) {
2810 streamDeleted = true;
2811 // Return buffer to deleted stream
2812 camera3_stream* halStream = stream->asHalStream();
2813 streamBuffer.stream = halStream;
2814 switch (halStream->stream_type) {
2815 case CAMERA3_STREAM_OUTPUT:
2816 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2817 if (res != OK) {
2818 ALOGE("%s: Can't return output buffer for frame %d to"
2819 " stream %d: %s (%d)", __FUNCTION__,
2820 frameNumber, streamId, strerror(-res), res);
2821 }
2822 break;
2823 case CAMERA3_STREAM_INPUT:
2824 res = stream->returnInputBuffer(streamBuffer);
2825 if (res != OK) {
2826 ALOGE("%s: Can't return input buffer for frame %d to"
2827 " stream %d: %s (%d)", __FUNCTION__,
2828 frameNumber, streamId, strerror(-res), res);
2829 }
2830 break;
2831 default: // Bi-direcitonal stream is deprecated
2832 ALOGE("%s: stream %d has unknown stream type %d",
2833 __FUNCTION__, streamId, halStream->stream_type);
2834 break;
2835 }
2836 break;
2837 }
2838 }
2839 if (streamDeleted) {
2840 continue;
2841 }
2842
2843 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002844 if (streamId == inputStreamId) {
2845 streamBuffer.stream = mInputStream->asHalStream();
2846 res = mInputStream->returnInputBuffer(streamBuffer);
2847 if (res != OK) {
2848 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002849 " stream %d: %s (%d)", __FUNCTION__,
2850 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002851 }
2852 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002853 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2854 if (idx == NAME_NOT_FOUND) {
2855 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2856 continue;
2857 }
2858 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002859 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2860 }
2861 }
2862}
2863
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002864void Camera3Device::insertResultLocked(CaptureResult *result,
2865 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002866 if (result == nullptr) return;
2867
Emilian Peev71c73a22017-03-21 16:35:51 +00002868 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2869 result->mMetadata.getAndLock());
2870 set_camera_metadata_vendor_id(meta, mVendorTagId);
2871 result->mMetadata.unlock(meta);
2872
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002873 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2874 (int32_t*)&frameNumber, 1) != OK) {
2875 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2876 return;
2877 }
2878
2879 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2880 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2881 return;
2882 }
2883
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002884 // Valid result, insert into queue
2885 List<CaptureResult>::iterator queuedResult =
2886 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2887 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2888 ", burstId = %" PRId32, __FUNCTION__,
2889 queuedResult->mResultExtras.requestId,
2890 queuedResult->mResultExtras.frameNumber,
2891 queuedResult->mResultExtras.burstId);
2892
2893 mResultSignal.signal();
2894}
2895
2896
2897void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002898 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002899 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002900 Mutex::Autolock l(mOutputLock);
2901
2902 CaptureResult captureResult;
2903 captureResult.mResultExtras = resultExtras;
2904 captureResult.mMetadata = partialResult;
2905
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002906 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002907}
2908
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002909
2910void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2911 CaptureResultExtras &resultExtras,
2912 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002913 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002914 bool reprocess,
2915 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002916 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002917 if (pendingMetadata.isEmpty())
2918 return;
2919
2920 Mutex::Autolock l(mOutputLock);
2921
2922 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002923 if (reprocess) {
2924 if (frameNumber < mNextReprocessResultFrameNumber) {
2925 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002926 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002927 frameNumber, mNextReprocessResultFrameNumber);
2928 return;
2929 }
2930 mNextReprocessResultFrameNumber = frameNumber + 1;
2931 } else {
2932 if (frameNumber < mNextResultFrameNumber) {
2933 SET_ERR("Out-of-order capture result metadata submitted! "
2934 "(got frame number %d, expecting %d)",
2935 frameNumber, mNextResultFrameNumber);
2936 return;
2937 }
2938 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002939 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002940
2941 CaptureResult captureResult;
2942 captureResult.mResultExtras = resultExtras;
2943 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002944 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002945
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002946 // Append any previous partials to form a complete result
2947 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2948 captureResult.mMetadata.append(collectedPartialResult);
2949 }
2950
2951 captureResult.mMetadata.sort();
2952
2953 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002954 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2955 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002956 SET_ERR("No timestamp provided by HAL for frame %d!",
2957 frameNumber);
2958 return;
2959 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002960 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
2961 camera_metadata_entry timestamp =
2962 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2963 if (timestamp.count == 0) {
2964 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
2965 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
2966 return;
2967 }
2968 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002969
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002970 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2971 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2972
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002973 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002974}
2975
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002976/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977 * Camera HAL device callback methods
2978 */
2979
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002980void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002981 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002982
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002983 status_t res;
2984
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002985 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002986 if (result->result == NULL && result->num_output_buffers == 0 &&
2987 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002988 SET_ERR("No result data provided by HAL for frame %d",
2989 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002990 return;
2991 }
Zhijun He204e3292014-07-14 17:09:23 -07002992
Zhijun He204e3292014-07-14 17:09:23 -07002993 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002994 result->result != NULL &&
2995 result->partial_result != 1) {
2996 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2997 " if partial result is not supported",
2998 frameNumber, result->partial_result);
2999 return;
3000 }
3001
3002 bool isPartialResult = false;
3003 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003004 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003005
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003006 // Get shutter timestamp and resultExtras from list of in-flight requests,
3007 // where it was added by the shutter notification for this frame. If the
3008 // shutter timestamp isn't received yet, append the output buffers to the
3009 // in-flight request and they will be returned when the shutter timestamp
3010 // arrives. Update the in-flight status and remove the in-flight entry if
3011 // all result data and shutter timestamp have been received.
3012 nsecs_t shutterTimestamp = 0;
3013
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003014 {
3015 Mutex::Autolock l(mInFlightLock);
3016 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3017 if (idx == NAME_NOT_FOUND) {
3018 SET_ERR("Unknown frame number for capture result: %d",
3019 frameNumber);
3020 return;
3021 }
3022 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003023 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3024 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003025 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003026 __FUNCTION__, request.resultExtras.requestId,
3027 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003028 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003029 // Always update the partial count to the latest one if it's not 0
3030 // (buffers only). When framework aggregates adjacent partial results
3031 // into one, the latest partial count will be used.
3032 if (result->partial_result != 0)
3033 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003034
3035 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003036 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003037 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3038 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3039 " the range of [1, %d] when metadata is included in the result",
3040 frameNumber, result->partial_result, mNumPartialResults);
3041 return;
3042 }
3043 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003044 if (isPartialResult && result->num_physcam_metadata) {
3045 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3046 " physical camera result", frameNumber);
3047 return;
3048 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003049 if (isPartialResult) {
3050 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003051 }
3052
Shuzhen Wang4a472662017-02-26 23:29:04 -08003053 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003054 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003055 sendPartialCaptureResult(result->result, request.resultExtras,
3056 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003057 }
3058 }
3059
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003060 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003061 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003062
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003063 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003064 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003065 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3066 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3067 request.physicalCameraIds.size(), result->num_physcam_metadata);
3068 return;
3069 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003070 if (request.haveResultMetadata) {
3071 SET_ERR("Called multiple times with metadata for frame %d",
3072 frameNumber);
3073 return;
3074 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003075 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3076 String8 physicalId(result->physcam_ids[i]);
3077 std::set<String8>::iterator cameraIdIter =
3078 request.physicalCameraIds.find(physicalId);
3079 if (cameraIdIter != request.physicalCameraIds.end()) {
3080 request.physicalCameraIds.erase(cameraIdIter);
3081 } else {
3082 SET_ERR("Total result for frame %d has already returned for camera %s",
3083 frameNumber, physicalId.c_str());
3084 return;
3085 }
3086 }
Zhijun He204e3292014-07-14 17:09:23 -07003087 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003088 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003089 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003090 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003091 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003092 request.haveResultMetadata = true;
3093 }
3094
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003095 uint32_t numBuffersReturned = result->num_output_buffers;
3096 if (result->input_buffer != NULL) {
3097 if (hasInputBufferInRequest) {
3098 numBuffersReturned += 1;
3099 } else {
3100 ALOGW("%s: Input buffer should be NULL if there is no input"
3101 " buffer sent in the request",
3102 __FUNCTION__);
3103 }
3104 }
3105 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003106 if (request.numBuffersLeft < 0) {
3107 SET_ERR("Too many buffers returned for frame %d",
3108 frameNumber);
3109 return;
3110 }
3111
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003112 camera_metadata_ro_entry_t entry;
3113 res = find_camera_metadata_ro_entry(result->result,
3114 ANDROID_SENSOR_TIMESTAMP, &entry);
3115 if (res == OK && entry.count == 1) {
3116 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003117 }
3118
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003119 // If shutter event isn't received yet, append the output buffers to
3120 // the in-flight request. Otherwise, return the output buffers to
3121 // streams.
3122 if (shutterTimestamp == 0) {
3123 request.pendingOutputBuffers.appendArray(result->output_buffers,
3124 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003125 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003126 returnOutputBuffers(result->output_buffers,
3127 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003128 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003129
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003130 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003131 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3132 CameraMetadata physicalMetadata;
3133 physicalMetadata.append(result->physcam_metadata[i]);
3134 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3135 physicalMetadata});
3136 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003137 if (shutterTimestamp == 0) {
3138 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003139 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003140 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003141 CameraMetadata metadata;
3142 metadata = result->result;
3143 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003144 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003145 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003146 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003147 }
3148
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003149 removeInFlightRequestIfReadyLocked(idx);
3150 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003151
Zhijun Hef0d962a2014-06-30 10:24:11 -07003152 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003153 if (hasInputBufferInRequest) {
3154 Camera3Stream *stream =
3155 Camera3Stream::cast(result->input_buffer->stream);
3156 res = stream->returnInputBuffer(*(result->input_buffer));
3157 // Note: stream may be deallocated at this point, if this buffer was the
3158 // last reference to it.
3159 if (res != OK) {
3160 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3161 " its stream:%s (%d)", __FUNCTION__,
3162 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003163 }
3164 } else {
3165 ALOGW("%s: Input buffer should be NULL if there is no input"
3166 " buffer sent in the request, skipping input buffer return.",
3167 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003168 }
3169 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003170}
3171
3172void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003173 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003174 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003175 {
3176 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003177 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003178 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003179
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003180 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003181 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003182 return;
3183 }
3184
3185 switch (msg->type) {
3186 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003187 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003188 break;
3189 }
3190 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003191 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003192 break;
3193 }
3194 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003195 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003196 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003197 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003198}
3199
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003200void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003201 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003202 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003203 // Map camera HAL error codes to ICameraDeviceCallback error codes
3204 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003205 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003206 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003207 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003208 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003209 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003210 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003211 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003212 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003213 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003214 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003215 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003216 };
3217
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003218 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003219 ((msg.error_code >= 0) &&
3220 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3221 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003222 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003223
3224 int streamId = 0;
3225 if (msg.error_stream != NULL) {
3226 Camera3Stream *stream =
3227 Camera3Stream::cast(msg.error_stream);
3228 streamId = stream->getId();
3229 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003230 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3231 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003232 streamId, msg.error_code);
3233
3234 CaptureResultExtras resultExtras;
3235 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003236 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003237 // SET_ERR calls notifyError
3238 SET_ERR("Camera HAL reported serious device error");
3239 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003240 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3241 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3242 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003243 {
3244 Mutex::Autolock l(mInFlightLock);
3245 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3246 if (idx >= 0) {
3247 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3248 r.requestStatus = msg.error_code;
3249 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003250 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3251 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3252 errorCode) {
3253 r.skipResultMetadata = true;
3254 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003255 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3256 errorCode) {
3257 // In case of missing result check whether the buffers
3258 // returned. If they returned, then remove inflight
3259 // request.
3260 removeInFlightRequestIfReadyLocked(idx);
3261 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003262 } else {
3263 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003264 ALOGE("Camera %s: %s: cannot find in-flight request on "
3265 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003266 resultExtras.frameNumber);
3267 }
3268 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003269 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003270 if (listener != NULL) {
3271 listener->notifyError(errorCode, resultExtras);
3272 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003273 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003274 }
3275 break;
3276 default:
3277 // SET_ERR calls notifyError
3278 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3279 break;
3280 }
3281}
3282
3283void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003284 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003285 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003286 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003287
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288 // Set timestamp for the request in the in-flight tracking
3289 // and get the request ID to send upstream
3290 {
3291 Mutex::Autolock l(mInFlightLock);
3292 idx = mInFlightMap.indexOfKey(msg.frame_number);
3293 if (idx >= 0) {
3294 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003295
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003296 // Verify ordering of shutter notifications
3297 {
3298 Mutex::Autolock l(mOutputLock);
3299 // TODO: need to track errors for tighter bounds on expected frame number.
3300 if (r.hasInputBuffer) {
3301 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3302 SET_ERR("Shutter notification out-of-order. Expected "
3303 "notification for frame %d, got frame %d",
3304 mNextReprocessShutterFrameNumber, msg.frame_number);
3305 return;
3306 }
3307 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3308 } else {
3309 if (msg.frame_number < mNextShutterFrameNumber) {
3310 SET_ERR("Shutter notification out-of-order. Expected "
3311 "notification for frame %d, got frame %d",
3312 mNextShutterFrameNumber, msg.frame_number);
3313 return;
3314 }
3315 mNextShutterFrameNumber = msg.frame_number + 1;
3316 }
3317 }
3318
Shuzhen Wang4a472662017-02-26 23:29:04 -08003319 r.shutterTimestamp = msg.timestamp;
3320 if (r.hasCallback) {
3321 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003322 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003323 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003324 // Call listener, if any
3325 if (listener != NULL) {
3326 listener->notifyShutter(r.resultExtras, msg.timestamp);
3327 }
3328 // send pending result and buffers
3329 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3330 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003331 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003332 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003333 returnOutputBuffers(r.pendingOutputBuffers.array(),
3334 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3335 r.pendingOutputBuffers.clear();
3336
3337 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003338 }
3339 }
3340 if (idx < 0) {
3341 SET_ERR("Shutter notification for non-existent frame number %d",
3342 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003343 }
3344}
3345
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003346CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003347 ALOGV("%s", __FUNCTION__);
3348
Igor Murashkin1e479c02013-09-06 16:55:14 -07003349 CameraMetadata retVal;
3350
3351 if (mRequestThread != NULL) {
3352 retVal = mRequestThread->getLatestRequest();
3353 }
3354
Igor Murashkin1e479c02013-09-06 16:55:14 -07003355 return retVal;
3356}
3357
Jianing Weicb0652e2014-03-12 18:29:36 -07003358
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003359void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3360 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3361 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3362}
3363
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003364/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003365 * HalInterface inner class methods
3366 */
3367
Yifan Hongf79b5542017-04-11 14:44:25 -07003368Camera3Device::HalInterface::HalInterface(
3369 sp<ICameraDeviceSession> &session,
3370 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003371 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003372 mRequestMetadataQueue(queue) {
3373 // Check with hardware service manager if we can downcast these interfaces
3374 // Somewhat expensive, so cache the results at startup
3375 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3376 if (castResult_3_4.isOk()) {
3377 mHidlSession_3_4 = castResult_3_4;
3378 }
3379 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3380 if (castResult_3_3.isOk()) {
3381 mHidlSession_3_3 = castResult_3_3;
3382 }
3383}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003384
Emilian Peev31abd0a2017-05-11 18:37:46 +01003385Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003386
3387Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003388 mHidlSession(other.mHidlSession),
3389 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003390
3391bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003392 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003393}
3394
3395void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003396 mHidlSession_3_4.clear();
3397 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003398 mHidlSession.clear();
3399}
3400
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003401bool Camera3Device::HalInterface::supportBatchRequest() {
3402 return mHidlSession != nullptr;
3403}
3404
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003405status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3406 camera3_request_template_t templateId,
3407 /*out*/ camera_metadata_t **requestTemplate) {
3408 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3409 if (!valid()) return INVALID_OPERATION;
3410 status_t res = OK;
3411
Emilian Peev31abd0a2017-05-11 18:37:46 +01003412 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003413
3414 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003415 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003416 status = s;
3417 if (status == common::V1_0::Status::OK) {
3418 const camera_metadata *r =
3419 reinterpret_cast<const camera_metadata_t*>(request.data());
3420 size_t expectedSize = request.size();
3421 int ret = validate_camera_metadata_structure(r, &expectedSize);
3422 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3423 *requestTemplate = clone_camera_metadata(r);
3424 if (*requestTemplate == nullptr) {
3425 ALOGE("%s: Unable to clone camera metadata received from HAL",
3426 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003427 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003428 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003429 } else {
3430 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3431 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003432 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003433 }
3434 };
3435 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003436 RequestTemplate id;
3437 switch (templateId) {
3438 case CAMERA3_TEMPLATE_PREVIEW:
3439 id = RequestTemplate::PREVIEW;
3440 break;
3441 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3442 id = RequestTemplate::STILL_CAPTURE;
3443 break;
3444 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3445 id = RequestTemplate::VIDEO_RECORD;
3446 break;
3447 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3448 id = RequestTemplate::VIDEO_SNAPSHOT;
3449 break;
3450 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3451 id = RequestTemplate::ZERO_SHUTTER_LAG;
3452 break;
3453 case CAMERA3_TEMPLATE_MANUAL:
3454 id = RequestTemplate::MANUAL;
3455 break;
3456 default:
3457 // Unknown template ID, or this HAL is too old to support it
3458 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003459 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003460 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003461
Emilian Peev31abd0a2017-05-11 18:37:46 +01003462 if (!err.isOk()) {
3463 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3464 res = DEAD_OBJECT;
3465 } else {
3466 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003467 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003468
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003469 return res;
3470}
3471
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003472status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003473 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003474 ATRACE_NAME("CameraHal::configureStreams");
3475 if (!valid()) return INVALID_OPERATION;
3476 status_t res = OK;
3477
Emilian Peev31abd0a2017-05-11 18:37:46 +01003478 // Convert stream config to HIDL
3479 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003480 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3481 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3482 requestedConfiguration3_2.streams.resize(config->num_streams);
3483 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003484 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003485 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3486 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003487 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003488
Emilian Peev31abd0a2017-05-11 18:37:46 +01003489 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3490 cam3stream->setBufferFreedListener(this);
3491 int streamId = cam3stream->getId();
3492 StreamType streamType;
3493 switch (src->stream_type) {
3494 case CAMERA3_STREAM_OUTPUT:
3495 streamType = StreamType::OUTPUT;
3496 break;
3497 case CAMERA3_STREAM_INPUT:
3498 streamType = StreamType::INPUT;
3499 break;
3500 default:
3501 ALOGE("%s: Stream %d: Unsupported stream type %d",
3502 __FUNCTION__, streamId, config->streams[i]->stream_type);
3503 return BAD_VALUE;
3504 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003505 dst3_2.id = streamId;
3506 dst3_2.streamType = streamType;
3507 dst3_2.width = src->width;
3508 dst3_2.height = src->height;
3509 dst3_2.format = mapToPixelFormat(src->format);
3510 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3511 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3512 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3513 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003514 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003515 if (src->physical_camera_id != nullptr) {
3516 dst3_4.physicalCameraId = src->physical_camera_id;
3517 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003518
3519 activeStreams.insert(streamId);
3520 // Create Buffer ID map if necessary
3521 if (mBufferIdMaps.count(streamId) == 0) {
3522 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3523 }
3524 }
3525 // remove BufferIdMap for deleted streams
3526 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3527 int streamId = it->first;
3528 bool active = activeStreams.count(streamId) > 0;
3529 if (!active) {
3530 it = mBufferIdMaps.erase(it);
3531 } else {
3532 ++it;
3533 }
3534 }
3535
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003536 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003537 res = mapToStreamConfigurationMode(
3538 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003539 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003540 if (res != OK) {
3541 return res;
3542 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003543 requestedConfiguration3_2.operationMode = operationMode;
3544 requestedConfiguration3_4.operationMode = operationMode;
3545 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003546 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3547 get_camera_metadata_size(sessionParams));
3548
Emilian Peev31abd0a2017-05-11 18:37:46 +01003549 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003550 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003552
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003553 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003554 if (mHidlSession_3_4 != nullptr) {
3555 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003556 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003557 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003558 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003559 [&status, &finalConfiguration3_4]
3560 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3561 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003562 status = s;
3563 });
3564 if (!err.isOk()) {
3565 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3566 return DEAD_OBJECT;
3567 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003568 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3569 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3570 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3571 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003572 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003573 // We do; use v3.3 for the call
3574 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003575 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003576 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003577 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003578 finalConfiguration = halConfiguration;
3579 status = s;
3580 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003581 if (!err.isOk()) {
3582 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3583 return DEAD_OBJECT;
3584 }
3585 } else {
3586 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3587 ALOGV("%s: v3.2 device found", __FUNCTION__);
3588 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003589 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003590 [&status, &finalConfiguration_3_2]
3591 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3592 finalConfiguration_3_2 = halConfiguration;
3593 status = s;
3594 });
3595 if (!err.isOk()) {
3596 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3597 return DEAD_OBJECT;
3598 }
3599 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3600 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3601 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3602 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003603 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003604 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003605 }
3606
3607 if (status != common::V1_0::Status::OK ) {
3608 return CameraProviderManager::mapToStatusT(status);
3609 }
3610
3611 // And convert output stream configuration from HIDL
3612
3613 for (size_t i = 0; i < config->num_streams; i++) {
3614 camera3_stream_t *dst = config->streams[i];
3615 int streamId = Camera3Stream::cast(dst)->getId();
3616
3617 // Start scan at i, with the assumption that the stream order matches
3618 size_t realIdx = i;
3619 bool found = false;
3620 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003621 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003622 found = true;
3623 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003624 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003625 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3626 }
3627 if (!found) {
3628 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3629 __FUNCTION__, streamId);
3630 return INVALID_OPERATION;
3631 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003632 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003633
Emilian Peev710c1422017-08-30 11:19:38 +01003634 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3635 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003636 dstStream->setDataSpaceOverride(false);
3637 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3638 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3639
Emilian Peev31abd0a2017-05-11 18:37:46 +01003640 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3641 if (dst->format != overrideFormat) {
3642 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3643 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003644 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003645 if (dst->data_space != overrideDataSpace) {
3646 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3647 streamId, dst->format);
3648 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003649 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003650 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003651 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3652
Emilian Peev31abd0a2017-05-11 18:37:46 +01003653 // Override allowed with IMPLEMENTATION_DEFINED
3654 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003655 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003656 }
3657
Emilian Peev31abd0a2017-05-11 18:37:46 +01003658 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003659 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003660 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003661 __FUNCTION__, streamId);
3662 return INVALID_OPERATION;
3663 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003664 dstStream->setUsage(
3665 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003666 } else {
3667 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003668 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003669 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3670 __FUNCTION__, streamId);
3671 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003672 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003673 dstStream->setUsage(
3674 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003675 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003676 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003677 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003678
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003679 return res;
3680}
3681
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003682void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3683 /*out*/device::V3_2::CaptureRequest* captureRequest,
3684 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003685 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003686 if (captureRequest == nullptr || handlesCreated == nullptr) {
3687 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3688 __FUNCTION__, captureRequest, handlesCreated);
3689 return;
3690 }
3691
3692 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003693
3694 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003695
3696 {
3697 std::lock_guard<std::mutex> lock(mInflightLock);
3698 if (request->input_buffer != nullptr) {
3699 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3700 buffer_handle_t buf = *(request->input_buffer->buffer);
3701 auto pair = getBufferId(buf, streamId);
3702 bool isNewBuffer = pair.first;
3703 uint64_t bufferId = pair.second;
3704 captureRequest->inputBuffer.streamId = streamId;
3705 captureRequest->inputBuffer.bufferId = bufferId;
3706 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3707 captureRequest->inputBuffer.status = BufferStatus::OK;
3708 native_handle_t *acquireFence = nullptr;
3709 if (request->input_buffer->acquire_fence != -1) {
3710 acquireFence = native_handle_create(1,0);
3711 acquireFence->data[0] = request->input_buffer->acquire_fence;
3712 handlesCreated->push_back(acquireFence);
3713 }
3714 captureRequest->inputBuffer.acquireFence = acquireFence;
3715 captureRequest->inputBuffer.releaseFence = nullptr;
3716
3717 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3718 request->input_buffer->buffer,
3719 request->input_buffer->acquire_fence);
3720 } else {
3721 captureRequest->inputBuffer.streamId = -1;
3722 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3723 }
3724
3725 captureRequest->outputBuffers.resize(request->num_output_buffers);
3726 for (size_t i = 0; i < request->num_output_buffers; i++) {
3727 const camera3_stream_buffer_t *src = request->output_buffers + i;
3728 StreamBuffer &dst = captureRequest->outputBuffers[i];
3729 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3730 buffer_handle_t buf = *(src->buffer);
3731 auto pair = getBufferId(buf, streamId);
3732 bool isNewBuffer = pair.first;
3733 dst.streamId = streamId;
3734 dst.bufferId = pair.second;
3735 dst.buffer = isNewBuffer ? buf : nullptr;
3736 dst.status = BufferStatus::OK;
3737 native_handle_t *acquireFence = nullptr;
3738 if (src->acquire_fence != -1) {
3739 acquireFence = native_handle_create(1,0);
3740 acquireFence->data[0] = src->acquire_fence;
3741 handlesCreated->push_back(acquireFence);
3742 }
3743 dst.acquireFence = acquireFence;
3744 dst.releaseFence = nullptr;
3745
3746 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3747 src->buffer, src->acquire_fence);
3748 }
3749 }
3750}
3751
3752status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3753 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3754 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3755 if (!valid()) return INVALID_OPERATION;
3756
Emilian Peevaebbe412018-01-15 13:53:24 +00003757 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3758 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3759 if (castResult_3_4.isOk()) {
3760 hidlSession_3_4 = castResult_3_4;
3761 }
3762
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003763 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003764 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003765 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003766 if (hidlSession_3_4 != nullptr) {
3767 captureRequests_3_4.resize(batchSize);
3768 } else {
3769 captureRequests.resize(batchSize);
3770 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003771 std::vector<native_handle_t*> handlesCreated;
3772
3773 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003774 if (hidlSession_3_4 != nullptr) {
3775 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3776 /*out*/&handlesCreated);
3777 } else {
3778 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3779 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003780 }
3781
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003782 std::vector<device::V3_2::BufferCache> cachesToRemove;
3783 {
3784 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3785 for (auto& pair : mFreedBuffers) {
3786 // The stream might have been removed since onBufferFreed
3787 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3788 cachesToRemove.push_back({pair.first, pair.second});
3789 }
3790 }
3791 mFreedBuffers.clear();
3792 }
3793
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003794 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3795 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003796
3797 // Write metadata to FMQ.
3798 for (size_t i = 0; i < batchSize; i++) {
3799 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003800 device::V3_2::CaptureRequest* captureRequest;
3801 if (hidlSession_3_4 != nullptr) {
3802 captureRequest = &captureRequests_3_4[i].v3_2;
3803 } else {
3804 captureRequest = &captureRequests[i];
3805 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003806
3807 if (request->settings != nullptr) {
3808 size_t settingsSize = get_camera_metadata_size(request->settings);
3809 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3810 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3811 captureRequest->settings.resize(0);
3812 captureRequest->fmqSettingsSize = settingsSize;
3813 } else {
3814 if (mRequestMetadataQueue != nullptr) {
3815 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3816 }
3817 captureRequest->settings.setToExternal(
3818 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3819 get_camera_metadata_size(request->settings));
3820 captureRequest->fmqSettingsSize = 0u;
3821 }
3822 } else {
3823 // A null request settings maps to a size-0 CameraMetadata
3824 captureRequest->settings.resize(0);
3825 captureRequest->fmqSettingsSize = 0u;
3826 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003827
3828 if (hidlSession_3_4 != nullptr) {
3829 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3830 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003831 if (request->physcam_settings != nullptr) {
3832 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3833 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3834 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3835 settingsSize)) {
3836 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3837 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3838 settingsSize;
3839 } else {
3840 if (mRequestMetadataQueue != nullptr) {
3841 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3842 }
3843 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3844 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3845 request->physcam_settings[j])),
3846 get_camera_metadata_size(request->physcam_settings[j]));
3847 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003848 }
Emilian Peev00420d22018-02-05 21:33:13 +00003849 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003850 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003851 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003852 }
3853 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3854 request->physcam_id[j];
3855 }
3856 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003857 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003858
3859 hardware::details::return_status err;
3860 if (hidlSession_3_4 != nullptr) {
3861 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003862 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3863 status = s;
3864 *numRequestProcessed = n;
3865 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003866 } else {
3867 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3868 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3869 status = s;
3870 *numRequestProcessed = n;
3871 });
3872 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003873 if (!err.isOk()) {
3874 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3875 return DEAD_OBJECT;
3876 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003877 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3878 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3879 __FUNCTION__, *numRequestProcessed, batchSize);
3880 status = common::V1_0::Status::INTERNAL_ERROR;
3881 }
3882
3883 for (auto& handle : handlesCreated) {
3884 native_handle_delete(handle);
3885 }
3886 return CameraProviderManager::mapToStatusT(status);
3887}
3888
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003889status_t Camera3Device::HalInterface::processCaptureRequest(
3890 camera3_capture_request_t *request) {
3891 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003892 if (!valid()) return INVALID_OPERATION;
3893 status_t res = OK;
3894
Emilian Peev31abd0a2017-05-11 18:37:46 +01003895 uint32_t numRequestProcessed = 0;
3896 std::vector<camera3_capture_request_t*> requests(1);
3897 requests[0] = request;
3898 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3899
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003900 return res;
3901}
3902
3903status_t Camera3Device::HalInterface::flush() {
3904 ATRACE_NAME("CameraHal::flush");
3905 if (!valid()) return INVALID_OPERATION;
3906 status_t res = OK;
3907
Emilian Peev31abd0a2017-05-11 18:37:46 +01003908 auto err = mHidlSession->flush();
3909 if (!err.isOk()) {
3910 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3911 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003912 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003913 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003914 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003915
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003916 return res;
3917}
3918
Emilian Peev31abd0a2017-05-11 18:37:46 +01003919status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003920 ATRACE_NAME("CameraHal::dump");
3921 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003922
Emilian Peev31abd0a2017-05-11 18:37:46 +01003923 // Handled by CameraProviderManager::dump
3924
3925 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003926}
3927
3928status_t Camera3Device::HalInterface::close() {
3929 ATRACE_NAME("CameraHal::close()");
3930 if (!valid()) return INVALID_OPERATION;
3931 status_t res = OK;
3932
Emilian Peev31abd0a2017-05-11 18:37:46 +01003933 auto err = mHidlSession->close();
3934 // Interface will be dead shortly anyway, so don't log errors
3935 if (!err.isOk()) {
3936 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003937 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003938
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003939 return res;
3940}
3941
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003942void Camera3Device::HalInterface::getInflightBufferKeys(
3943 std::vector<std::pair<int32_t, int32_t>>* out) {
3944 std::lock_guard<std::mutex> lock(mInflightLock);
3945 out->clear();
3946 out->reserve(mInflightBufferMap.size());
3947 for (auto& pair : mInflightBufferMap) {
3948 uint64_t key = pair.first;
3949 int32_t streamId = key & 0xFFFFFFFF;
3950 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
3951 out->push_back(std::make_pair(frameNumber, streamId));
3952 }
3953 return;
3954}
3955
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003956status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003957 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003958 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003959 auto pair = std::make_pair(buffer, acquireFence);
3960 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003961 return OK;
3962}
3963
3964status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003965 int32_t frameNumber, int32_t streamId,
3966 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003967 std::lock_guard<std::mutex> lock(mInflightLock);
3968
3969 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3970 auto it = mInflightBufferMap.find(key);
3971 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003972 auto pair = it->second;
3973 *buffer = pair.first;
3974 int acquireFence = pair.second;
3975 if (acquireFence > 0) {
3976 ::close(acquireFence);
3977 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978 mInflightBufferMap.erase(it);
3979 return OK;
3980}
3981
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003982std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3983 const buffer_handle_t& buf, int streamId) {
3984 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3985
3986 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3987 auto it = bIdMap.find(buf);
3988 if (it == bIdMap.end()) {
3989 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003990 ALOGV("stream %d now have %zu buffer caches, buf %p",
3991 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003992 return std::make_pair(true, mNextBufferId - 1);
3993 } else {
3994 return std::make_pair(false, it->second);
3995 }
3996}
3997
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003998void Camera3Device::HalInterface::onBufferFreed(
3999 int streamId, const native_handle_t* handle) {
4000 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4001 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4002 auto mapIt = mBufferIdMaps.find(streamId);
4003 if (mapIt == mBufferIdMaps.end()) {
4004 // streamId might be from a deleted stream here
4005 ALOGI("%s: stream %d has been removed",
4006 __FUNCTION__, streamId);
4007 return;
4008 }
4009 BufferIdMap& bIdMap = mapIt->second;
4010 auto it = bIdMap.find(handle);
4011 if (it == bIdMap.end()) {
4012 ALOGW("%s: cannot find buffer %p in stream %d",
4013 __FUNCTION__, handle, streamId);
4014 return;
4015 } else {
4016 bufferId = it->second;
4017 bIdMap.erase(it);
4018 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4019 __FUNCTION__, streamId, bIdMap.size(), handle);
4020 }
4021 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4022}
4023
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004024/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004025 * RequestThread inner class methods
4026 */
4027
4028Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004029 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004030 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004031 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004032 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004033 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004034 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004035 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004036 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004037 mReconfigured(false),
4038 mDoPause(false),
4039 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004040 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004041 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004042 mCurrentAfTriggerId(0),
4043 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004044 mRepeatingLastFrameNumber(
4045 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004046 mPrepareVideoStream(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004047 mRequestLatency(kRequestLatencyBinSize),
4048 mSessionParamKeys(sessionParamKeys),
4049 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004050 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004051}
4052
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004053Camera3Device::RequestThread::~RequestThread() {}
4054
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004055void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004056 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004057 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004058 Mutex::Autolock l(mRequestLock);
4059 mListener = listener;
4060}
4061
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004062void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4063 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004064 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004065 Mutex::Autolock l(mRequestLock);
4066 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004067 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004068 // Prepare video stream for high speed recording.
4069 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004070}
4071
Jianing Wei90e59c92014-03-12 18:29:36 -07004072status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004073 List<sp<CaptureRequest> > &requests,
4074 /*out*/
4075 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004076 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004077 Mutex::Autolock l(mRequestLock);
4078 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4079 ++it) {
4080 mRequestQueue.push_back(*it);
4081 }
4082
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004083 if (lastFrameNumber != NULL) {
4084 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4085 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4086 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4087 *lastFrameNumber);
4088 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004089
Jianing Wei90e59c92014-03-12 18:29:36 -07004090 unpauseForNewRequests();
4091
4092 return OK;
4093}
4094
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004095
4096status_t Camera3Device::RequestThread::queueTrigger(
4097 RequestTrigger trigger[],
4098 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004099 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004100 Mutex::Autolock l(mTriggerMutex);
4101 status_t ret;
4102
4103 for (size_t i = 0; i < count; ++i) {
4104 ret = queueTriggerLocked(trigger[i]);
4105
4106 if (ret != OK) {
4107 return ret;
4108 }
4109 }
4110
4111 return OK;
4112}
4113
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004114const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4115 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004116 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117 if (d != nullptr) return d->mId;
4118 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004119}
4120
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004121status_t Camera3Device::RequestThread::queueTriggerLocked(
4122 RequestTrigger trigger) {
4123
4124 uint32_t tag = trigger.metadataTag;
4125 ssize_t index = mTriggerMap.indexOfKey(tag);
4126
4127 switch (trigger.getTagType()) {
4128 case TYPE_BYTE:
4129 // fall-through
4130 case TYPE_INT32:
4131 break;
4132 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004133 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4134 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004135 return INVALID_OPERATION;
4136 }
4137
4138 /**
4139 * Collect only the latest trigger, since we only have 1 field
4140 * in the request settings per trigger tag, and can't send more than 1
4141 * trigger per request.
4142 */
4143 if (index != NAME_NOT_FOUND) {
4144 mTriggerMap.editValueAt(index) = trigger;
4145 } else {
4146 mTriggerMap.add(tag, trigger);
4147 }
4148
4149 return OK;
4150}
4151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004153 const RequestList &requests,
4154 /*out*/
4155 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004156 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004158 if (lastFrameNumber != NULL) {
4159 *lastFrameNumber = mRepeatingLastFrameNumber;
4160 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004161 mRepeatingRequests.clear();
4162 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4163 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004164
4165 unpauseForNewRequests();
4166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004167 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004168 return OK;
4169}
4170
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004171bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004172 if (mRepeatingRequests.empty()) {
4173 return false;
4174 }
4175 int32_t requestId = requestIn->mResultExtras.requestId;
4176 const RequestList &repeatRequests = mRepeatingRequests;
4177 // All repeating requests are guaranteed to have same id so only check first quest
4178 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4179 return (firstRequest->mResultExtras.requestId == requestId);
4180}
4181
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004182status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004183 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004184 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004185 return clearRepeatingRequestsLocked(lastFrameNumber);
4186
4187}
4188
4189status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004190 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004191 if (lastFrameNumber != NULL) {
4192 *lastFrameNumber = mRepeatingLastFrameNumber;
4193 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004194 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004195 return OK;
4196}
4197
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004198status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004199 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004200 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004201 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004202 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004203
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004204 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004205
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004206 // Send errors for all requests pending in the request queue, including
4207 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004208 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004209 if (listener != NULL) {
4210 for (RequestList::iterator it = mRequestQueue.begin();
4211 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004212 // Abort the input buffers for reprocess requests.
4213 if ((*it)->mInputStream != NULL) {
4214 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004215 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4216 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004217 if (res != OK) {
4218 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4219 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4220 } else {
4221 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4222 if (res != OK) {
4223 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4224 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4225 }
4226 }
4227 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004228 // Set the frame number this request would have had, if it
4229 // had been submitted; this frame number will not be reused.
4230 // The requestId and burstId fields were set when the request was
4231 // submitted originally (in convertMetadataListToRequestListLocked)
4232 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004233 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004234 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004235 }
4236 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004237 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004238
4239 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004240 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004241 if (lastFrameNumber != NULL) {
4242 *lastFrameNumber = mRepeatingLastFrameNumber;
4243 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004244 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004245 return OK;
4246}
4247
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004248status_t Camera3Device::RequestThread::flush() {
4249 ATRACE_CALL();
4250 Mutex::Autolock l(mFlushLock);
4251
Emilian Peev08dd2452017-04-06 16:55:14 +01004252 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004253}
4254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004256 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004257 Mutex::Autolock l(mPauseLock);
4258 mDoPause = paused;
4259 mDoPauseSignal.signal();
4260}
4261
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004262status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4263 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004264 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004265 Mutex::Autolock l(mLatestRequestMutex);
4266 status_t res;
4267 while (mLatestRequestId != requestId) {
4268 nsecs_t startTime = systemTime();
4269
4270 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4271 if (res != OK) return res;
4272
4273 timeout -= (systemTime() - startTime);
4274 }
4275
4276 return OK;
4277}
4278
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004279void Camera3Device::RequestThread::requestExit() {
4280 // Call parent to set up shutdown
4281 Thread::requestExit();
4282 // The exit from any possible waits
4283 mDoPauseSignal.signal();
4284 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004285
4286 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4287 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004288}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004289
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004290void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004291 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004292 bool surfaceAbandoned = false;
4293 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004294 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004295 {
4296 Mutex::Autolock l(mRequestLock);
4297 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4298 // repeating requests.
4299 for (const auto& request : mRepeatingRequests) {
4300 for (const auto& s : request->mOutputStreams) {
4301 if (s->isAbandoned()) {
4302 surfaceAbandoned = true;
4303 clearRepeatingRequestsLocked(&lastFrameNumber);
4304 break;
4305 }
4306 }
4307 if (surfaceAbandoned) {
4308 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004309 }
4310 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004311 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004312 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004313
4314 if (listener != NULL && surfaceAbandoned) {
4315 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004316 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004317}
4318
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004319bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004320 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004321 status_t res;
4322 size_t batchSize = mNextRequests.size();
4323 std::vector<camera3_capture_request_t*> requests(batchSize);
4324 uint32_t numRequestProcessed = 0;
4325 for (size_t i = 0; i < batchSize; i++) {
4326 requests[i] = &mNextRequests.editItemAt(i).halRequest;
4327 }
4328
4329 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
4330 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4331
4332 bool triggerRemoveFailed = false;
4333 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4334 for (size_t i = 0; i < numRequestProcessed; i++) {
4335 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4336 nextRequest.submitted = true;
4337
4338
4339 // Update the latest request sent to HAL
4340 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4341 Mutex::Autolock al(mLatestRequestMutex);
4342
4343 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4344 mLatestRequest.acquire(cloned);
4345
4346 sp<Camera3Device> parent = mParent.promote();
4347 if (parent != NULL) {
4348 parent->monitorMetadata(TagMonitor::REQUEST,
4349 nextRequest.halRequest.frame_number,
4350 0, mLatestRequest);
4351 }
4352 }
4353
4354 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004355 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4356 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004357 }
4358
Emilian Peevaebbe412018-01-15 13:53:24 +00004359 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4360
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004361 if (!triggerRemoveFailed) {
4362 // Remove any previously queued triggers (after unlock)
4363 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4364 if (removeTriggerRes != OK) {
4365 triggerRemoveFailed = true;
4366 triggerFailedRequest = nextRequest;
4367 }
4368 }
4369 }
4370
4371 if (triggerRemoveFailed) {
4372 SET_ERR("RequestThread: Unable to remove triggers "
4373 "(capture request %d, HAL device: %s (%d)",
4374 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4375 cleanUpFailedRequests(/*sendRequestError*/ false);
4376 return false;
4377 }
4378
4379 if (res != OK) {
4380 // Should only get a failure here for malformed requests or device-level
4381 // errors, so consider all errors fatal. Bad metadata failures should
4382 // come through notify.
4383 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4384 mNextRequests[numRequestProcessed].halRequest.frame_number,
4385 strerror(-res), res);
4386 cleanUpFailedRequests(/*sendRequestError*/ false);
4387 return false;
4388 }
4389 return true;
4390}
4391
4392bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4393 status_t res;
4394
4395 for (auto& nextRequest : mNextRequests) {
4396 // Submit request and block until ready for next one
4397 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4398 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4399
4400 if (res != OK) {
4401 // Should only get a failure here for malformed requests or device-level
4402 // errors, so consider all errors fatal. Bad metadata failures should
4403 // come through notify.
4404 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4405 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4406 res);
4407 cleanUpFailedRequests(/*sendRequestError*/ false);
4408 return false;
4409 }
4410
4411 // Mark that the request has be submitted successfully.
4412 nextRequest.submitted = true;
4413
4414 // Update the latest request sent to HAL
4415 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4416 Mutex::Autolock al(mLatestRequestMutex);
4417
4418 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4419 mLatestRequest.acquire(cloned);
4420
4421 sp<Camera3Device> parent = mParent.promote();
4422 if (parent != NULL) {
4423 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4424 0, mLatestRequest);
4425 }
4426 }
4427
4428 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004429 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4430 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004431 }
4432
Emilian Peevaebbe412018-01-15 13:53:24 +00004433 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4434
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004435 // Remove any previously queued triggers (after unlock)
4436 res = removeTriggers(mPrevRequest);
4437 if (res != OK) {
4438 SET_ERR("RequestThread: Unable to remove triggers "
4439 "(capture request %d, HAL device: %s (%d)",
4440 nextRequest.halRequest.frame_number, strerror(-res), res);
4441 cleanUpFailedRequests(/*sendRequestError*/ false);
4442 return false;
4443 }
4444 }
4445 return true;
4446}
4447
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004448nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4449 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4450 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4451 find_camera_metadata_ro_entry(request,
4452 ANDROID_CONTROL_AE_MODE,
4453 &e);
4454 if (e.count == 0) return maxExpectedDuration;
4455
4456 switch (e.data.u8[0]) {
4457 case ANDROID_CONTROL_AE_MODE_OFF:
4458 find_camera_metadata_ro_entry(request,
4459 ANDROID_SENSOR_EXPOSURE_TIME,
4460 &e);
4461 if (e.count > 0) {
4462 maxExpectedDuration = e.data.i64[0];
4463 }
4464 find_camera_metadata_ro_entry(request,
4465 ANDROID_SENSOR_FRAME_DURATION,
4466 &e);
4467 if (e.count > 0) {
4468 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4469 }
4470 break;
4471 default:
4472 find_camera_metadata_ro_entry(request,
4473 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4474 &e);
4475 if (e.count > 1) {
4476 maxExpectedDuration = 1e9 / e.data.u8[0];
4477 }
4478 break;
4479 }
4480
4481 return maxExpectedDuration;
4482}
4483
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004484bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4485 ATRACE_CALL();
4486 bool updatesDetected = false;
4487
4488 for (auto tag : mSessionParamKeys) {
4489 camera_metadata_ro_entry entry = settings.find(tag);
4490 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4491
4492 if (entry.count > 0) {
4493 bool isDifferent = false;
4494 if (lastEntry.count > 0) {
4495 // Have a last value, compare to see if changed
4496 if (lastEntry.type == entry.type &&
4497 lastEntry.count == entry.count) {
4498 // Same type and count, compare values
4499 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4500 size_t entryBytes = bytesPerValue * lastEntry.count;
4501 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4502 if (cmp != 0) {
4503 isDifferent = true;
4504 }
4505 } else {
4506 // Count or type has changed
4507 isDifferent = true;
4508 }
4509 } else {
4510 // No last entry, so always consider to be different
4511 isDifferent = true;
4512 }
4513
4514 if (isDifferent) {
4515 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
4516 mLatestSessionParams.update(entry);
4517 updatesDetected = true;
4518 }
4519 } else if (lastEntry.count > 0) {
4520 // Value has been removed
4521 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4522 mLatestSessionParams.erase(tag);
4523 updatesDetected = true;
4524 }
4525 }
4526
4527 return updatesDetected;
4528}
4529
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004530bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004531 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004532 status_t res;
4533
4534 // Handle paused state.
4535 if (waitIfPaused()) {
4536 return true;
4537 }
4538
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004539 // Wait for the next batch of requests.
4540 waitForNextRequestBatch();
4541 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004542 return true;
4543 }
4544
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004545 // Get the latest request ID, if any
4546 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004547 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004548 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004549 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004550 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004551 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004552 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4553 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004554 }
4555
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004556 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4557 // or a single request from streaming or burst. In either case the first element
4558 // should contain the latest camera settings that we need to check for any session
4559 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004560 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004561 res = OK;
4562
4563 //Input stream buffers are already acquired at this point so an input stream
4564 //will not be able to move to idle state unless we force it.
4565 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4566 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4567 if (res != OK) {
4568 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4569 cleanUpFailedRequests(/*sendRequestError*/ false);
4570 return false;
4571 }
4572 }
4573
4574 if (res == OK) {
4575 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4576 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004577 sp<Camera3Device> parent = mParent.promote();
4578 if (parent != nullptr) {
4579 parent->pauseStateNotify(true);
4580 }
4581
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004582 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4583
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004584 if (parent != nullptr) {
4585 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4586 }
4587
4588 statusTracker->markComponentActive(mStatusId);
4589 setPaused(false);
4590 }
4591
4592 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4593 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4594 if (res != OK) {
4595 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4596 cleanUpFailedRequests(/*sendRequestError*/ false);
4597 return false;
4598 }
4599 }
4600 }
4601 }
4602
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004603 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004604 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004605 if (res == TIMED_OUT) {
4606 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004607 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004608 // Check if any stream is abandoned.
4609 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004610 return true;
4611 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004612 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004613 return false;
4614 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004615
Zhijun Hecc27e112013-10-03 16:12:43 -07004616 // Inform waitUntilRequestProcessed thread of a new request ID
4617 {
4618 Mutex::Autolock al(mLatestRequestMutex);
4619
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004620 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004621 mLatestRequestSignal.signal();
4622 }
4623
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004624 // Submit a batch of requests to HAL.
4625 // Use flush lock only when submitting multilple requests in a batch.
4626 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4627 // which may take a long time to finish so synchronizing flush() and
4628 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4629 // For now, only synchronize for high speed recording and we should figure something out for
4630 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004631 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004632
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004633 if (useFlushLock) {
4634 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004635 }
4636
Zhijun Hef0645c12016-08-02 00:58:11 -07004637 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004638 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004639
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004640 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004641 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004642 if (mInterface->supportBatchRequest()) {
4643 submitRequestSuccess = sendRequestsBatch();
4644 } else {
4645 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004646 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004647 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4648 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004649
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004650 if (useFlushLock) {
4651 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004652 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004653
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004654 // Unset as current request
4655 {
4656 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004657 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004658 }
4659
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004660 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004661}
4662
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004663status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004664 ATRACE_CALL();
4665
Shuzhen Wang4a472662017-02-26 23:29:04 -08004666 for (size_t i = 0; i < mNextRequests.size(); i++) {
4667 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004668 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4669 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4670 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4671
4672 // Prepare a request to HAL
4673 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4674
4675 // Insert any queued triggers (before metadata is locked)
4676 status_t res = insertTriggers(captureRequest);
4677
4678 if (res < 0) {
4679 SET_ERR("RequestThread: Unable to insert triggers "
4680 "(capture request %d, HAL device: %s (%d)",
4681 halRequest->frame_number, strerror(-res), res);
4682 return INVALID_OPERATION;
4683 }
4684 int triggerCount = res;
4685 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4686 mPrevTriggers = triggerCount;
4687
4688 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004689 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4690 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004691 /**
4692 * HAL workaround:
4693 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4694 */
4695 res = addDummyTriggerIds(captureRequest);
4696 if (res != OK) {
4697 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4698 "(capture request %d, HAL device: %s (%d)",
4699 halRequest->frame_number, strerror(-res), res);
4700 return INVALID_OPERATION;
4701 }
4702
4703 /**
4704 * The request should be presorted so accesses in HAL
4705 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4706 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004707 captureRequest->mSettingsList.begin()->metadata.sort();
4708 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004709 mPrevRequest = captureRequest;
4710 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4711
4712 IF_ALOGV() {
4713 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4714 find_camera_metadata_ro_entry(
4715 halRequest->settings,
4716 ANDROID_CONTROL_AF_TRIGGER,
4717 &e
4718 );
4719 if (e.count > 0) {
4720 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4721 __FUNCTION__,
4722 halRequest->frame_number,
4723 e.data.u8[0]);
4724 }
4725 }
4726 } else {
4727 // leave request.settings NULL to indicate 'reuse latest given'
4728 ALOGVV("%s: Request settings are REUSED",
4729 __FUNCTION__);
4730 }
4731
Emilian Peevaebbe412018-01-15 13:53:24 +00004732 if (captureRequest->mSettingsList.size() > 1) {
4733 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4734 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004735 if (newRequest) {
4736 halRequest->physcam_settings =
4737 new const camera_metadata* [halRequest->num_physcam_settings];
4738 } else {
4739 halRequest->physcam_settings = nullptr;
4740 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004741 auto it = ++captureRequest->mSettingsList.begin();
4742 size_t i = 0;
4743 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4744 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004745 if (newRequest) {
4746 it->metadata.sort();
4747 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4748 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004749 }
4750 }
4751
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004752 uint32_t totalNumBuffers = 0;
4753
4754 // Fill in buffers
4755 if (captureRequest->mInputStream != NULL) {
4756 halRequest->input_buffer = &captureRequest->mInputBuffer;
4757 totalNumBuffers += 1;
4758 } else {
4759 halRequest->input_buffer = NULL;
4760 }
4761
4762 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4763 captureRequest->mOutputStreams.size());
4764 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004765 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004766 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4767 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004768
4769 // Prepare video buffers for high speed recording on the first video request.
4770 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4771 // Only try to prepare video stream on the first video request.
4772 mPrepareVideoStream = false;
4773
4774 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4775 while (res == NOT_ENOUGH_DATA) {
4776 res = outputStream->prepareNextBuffer();
4777 }
4778 if (res != OK) {
4779 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4780 __FUNCTION__, strerror(-res), res);
4781 outputStream->cancelPrepare();
4782 }
4783 }
4784
Shuzhen Wang4a472662017-02-26 23:29:04 -08004785 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4786 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787 if (res != OK) {
4788 // Can't get output buffer from gralloc queue - this could be due to
4789 // abandoned queue or other consumer misbehavior, so not a fatal
4790 // error
4791 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4792 " %s (%d)", strerror(-res), res);
4793
4794 return TIMED_OUT;
4795 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004796
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004797 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4798
4799 if (!physicalCameraId.isEmpty()) {
4800 // Physical stream isn't supported for input request.
4801 if (halRequest->input_buffer) {
4802 CLOGE("Physical stream is not supported for input request");
4803 return INVALID_OPERATION;
4804 }
4805 requestedPhysicalCameras.insert(physicalCameraId);
4806 }
4807 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 }
4809 totalNumBuffers += halRequest->num_output_buffers;
4810
4811 // Log request in the in-flight queue
4812 sp<Camera3Device> parent = mParent.promote();
4813 if (parent == NULL) {
4814 // Should not happen, and nowhere to send errors to, so just log it
4815 CLOGE("RequestThread: Parent is gone");
4816 return INVALID_OPERATION;
4817 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004818
4819 // If this request list is for constrained high speed recording (not
4820 // preview), and the current request is not the last one in the batch,
4821 // do not send callback to the app.
4822 bool hasCallback = true;
4823 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4824 hasCallback = false;
4825 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004826 res = parent->registerInFlight(halRequest->frame_number,
4827 totalNumBuffers, captureRequest->mResultExtras,
4828 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004829 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004830 calculateMaxExpectedDuration(halRequest->settings),
4831 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004832 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4833 ", burstId = %" PRId32 ".",
4834 __FUNCTION__,
4835 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4836 captureRequest->mResultExtras.burstId);
4837 if (res != OK) {
4838 SET_ERR("RequestThread: Unable to register new in-flight request:"
4839 " %s (%d)", strerror(-res), res);
4840 return INVALID_OPERATION;
4841 }
4842 }
4843
4844 return OK;
4845}
4846
Igor Murashkin1e479c02013-09-06 16:55:14 -07004847CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004848 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004849 Mutex::Autolock al(mLatestRequestMutex);
4850
4851 ALOGV("RequestThread::%s", __FUNCTION__);
4852
4853 return mLatestRequest;
4854}
4855
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004856bool Camera3Device::RequestThread::isStreamPending(
4857 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004858 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004859 Mutex::Autolock l(mRequestLock);
4860
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004861 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004862 if (!nextRequest.submitted) {
4863 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4864 if (stream == s) return true;
4865 }
4866 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004867 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004868 }
4869
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004870 for (const auto& request : mRequestQueue) {
4871 for (const auto& s : request->mOutputStreams) {
4872 if (stream == s) return true;
4873 }
4874 if (stream == request->mInputStream) return true;
4875 }
4876
4877 for (const auto& request : mRepeatingRequests) {
4878 for (const auto& s : request->mOutputStreams) {
4879 if (stream == s) return true;
4880 }
4881 if (stream == request->mInputStream) return true;
4882 }
4883
4884 return false;
4885}
Jianing Weicb0652e2014-03-12 18:29:36 -07004886
Emilian Peev40ead602017-09-26 15:46:36 +01004887bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4888 ATRACE_CALL();
4889 Mutex::Autolock l(mRequestLock);
4890
4891 for (const auto& nextRequest : mNextRequests) {
4892 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4893 if (s.first == streamId) {
4894 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4895 if (it != s.second.end()) {
4896 return true;
4897 }
4898 }
4899 }
4900 }
4901
4902 for (const auto& request : mRequestQueue) {
4903 for (const auto& s : request->mOutputSurfaces) {
4904 if (s.first == streamId) {
4905 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4906 if (it != s.second.end()) {
4907 return true;
4908 }
4909 }
4910 }
4911 }
4912
4913 for (const auto& request : mRepeatingRequests) {
4914 for (const auto& s : request->mOutputSurfaces) {
4915 if (s.first == streamId) {
4916 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4917 if (it != s.second.end()) {
4918 return true;
4919 }
4920 }
4921 }
4922 }
4923
4924 return false;
4925}
4926
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004927nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004928 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004929 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004930 return mExpectedInflightDuration > kMinInflightDuration ?
4931 mExpectedInflightDuration : kMinInflightDuration;
4932}
4933
Emilian Peevaebbe412018-01-15 13:53:24 +00004934void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4935 camera3_capture_request_t *halRequest) {
4936 if ((request == nullptr) || (halRequest == nullptr)) {
4937 ALOGE("%s: Invalid request!", __FUNCTION__);
4938 return;
4939 }
4940
4941 if (halRequest->num_physcam_settings > 0) {
4942 if (halRequest->physcam_id != nullptr) {
4943 delete [] halRequest->physcam_id;
4944 halRequest->physcam_id = nullptr;
4945 }
4946 if (halRequest->physcam_settings != nullptr) {
4947 auto it = ++(request->mSettingsList.begin());
4948 size_t i = 0;
4949 for (; it != request->mSettingsList.end(); it++, i++) {
4950 it->metadata.unlock(halRequest->physcam_settings[i]);
4951 }
4952 delete [] halRequest->physcam_settings;
4953 halRequest->physcam_settings = nullptr;
4954 }
4955 }
4956}
4957
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004958void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4959 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004960 return;
4961 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004962
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004963 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004964 // Skip the ones that have been submitted successfully.
4965 if (nextRequest.submitted) {
4966 continue;
4967 }
4968
4969 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4970 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4971 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4972
4973 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004974 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 }
4976
Emilian Peevaebbe412018-01-15 13:53:24 +00004977 cleanupPhysicalSettings(captureRequest, halRequest);
4978
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004979 if (captureRequest->mInputStream != NULL) {
4980 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4981 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4982 }
4983
4984 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004985 //Buffers that failed processing could still have
4986 //valid acquire fence.
4987 int acquireFence = (*outputBuffers)[i].acquire_fence;
4988 if (0 <= acquireFence) {
4989 close(acquireFence);
4990 outputBuffers->editItemAt(i).acquire_fence = -1;
4991 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004992 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4993 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4994 }
4995
4996 if (sendRequestError) {
4997 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004998 sp<NotificationListener> listener = mListener.promote();
4999 if (listener != NULL) {
5000 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005001 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005002 captureRequest->mResultExtras);
5003 }
5004 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005005
5006 // Remove yet-to-be submitted inflight request from inflightMap
5007 {
5008 sp<Camera3Device> parent = mParent.promote();
5009 if (parent != NULL) {
5010 Mutex::Autolock l(parent->mInFlightLock);
5011 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5012 if (idx >= 0) {
5013 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5014 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5015 parent->removeInFlightMapEntryLocked(idx);
5016 }
5017 }
5018 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005019 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005020
5021 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005022 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005023}
5024
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005025void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005026 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005027 // Optimized a bit for the simple steady-state case (single repeating
5028 // request), to avoid putting that request in the queue temporarily.
5029 Mutex::Autolock l(mRequestLock);
5030
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005031 assert(mNextRequests.empty());
5032
5033 NextRequest nextRequest;
5034 nextRequest.captureRequest = waitForNextRequestLocked();
5035 if (nextRequest.captureRequest == nullptr) {
5036 return;
5037 }
5038
5039 nextRequest.halRequest = camera3_capture_request_t();
5040 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005041 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005042
5043 // Wait for additional requests
5044 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5045
5046 for (size_t i = 1; i < batchSize; i++) {
5047 NextRequest additionalRequest;
5048 additionalRequest.captureRequest = waitForNextRequestLocked();
5049 if (additionalRequest.captureRequest == nullptr) {
5050 break;
5051 }
5052
5053 additionalRequest.halRequest = camera3_capture_request_t();
5054 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005055 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005056 }
5057
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005058 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005059 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005060 mNextRequests.size(), batchSize);
5061 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005062 }
5063
5064 return;
5065}
5066
5067sp<Camera3Device::CaptureRequest>
5068 Camera3Device::RequestThread::waitForNextRequestLocked() {
5069 status_t res;
5070 sp<CaptureRequest> nextRequest;
5071
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005072 while (mRequestQueue.empty()) {
5073 if (!mRepeatingRequests.empty()) {
5074 // Always atomically enqueue all requests in a repeating request
5075 // list. Guarantees a complete in-sequence set of captures to
5076 // application.
5077 const RequestList &requests = mRepeatingRequests;
5078 RequestList::const_iterator firstRequest =
5079 requests.begin();
5080 nextRequest = *firstRequest;
5081 mRequestQueue.insert(mRequestQueue.end(),
5082 ++firstRequest,
5083 requests.end());
5084 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005086 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005087
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005088 break;
5089 }
5090
5091 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5092
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005093 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5094 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005095 Mutex::Autolock pl(mPauseLock);
5096 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005097 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005098 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005099 // Let the tracker know
5100 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5101 if (statusTracker != 0) {
5102 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5103 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104 }
5105 // Stop waiting for now and let thread management happen
5106 return NULL;
5107 }
5108 }
5109
5110 if (nextRequest == NULL) {
5111 // Don't have a repeating request already in hand, so queue
5112 // must have an entry now.
5113 RequestList::iterator firstRequest =
5114 mRequestQueue.begin();
5115 nextRequest = *firstRequest;
5116 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005117 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5118 sp<NotificationListener> listener = mListener.promote();
5119 if (listener != NULL) {
5120 listener->notifyRequestQueueEmpty();
5121 }
5122 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005123 }
5124
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005125 // In case we've been unpaused by setPaused clearing mDoPause, need to
5126 // update internal pause state (capture/setRepeatingRequest unpause
5127 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005128 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005129 if (mPaused) {
5130 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5131 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5132 if (statusTracker != 0) {
5133 statusTracker->markComponentActive(mStatusId);
5134 }
5135 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005136 mPaused = false;
5137
5138 // Check if we've reconfigured since last time, and reset the preview
5139 // request if so. Can't use 'NULL request == repeat' across configure calls.
5140 if (mReconfigured) {
5141 mPrevRequest.clear();
5142 mReconfigured = false;
5143 }
5144
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005145 if (nextRequest != NULL) {
5146 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005147 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5148 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005149
5150 // Since RequestThread::clear() removes buffers from the input stream,
5151 // get the right buffer here before unlocking mRequestLock
5152 if (nextRequest->mInputStream != NULL) {
5153 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5154 if (res != OK) {
5155 // Can't get input buffer from gralloc queue - this could be due to
5156 // disconnected queue or other producer misbehavior, so not a fatal
5157 // error
5158 ALOGE("%s: Can't get input buffer, skipping request:"
5159 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005160
5161 sp<NotificationListener> listener = mListener.promote();
5162 if (listener != NULL) {
5163 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005164 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005165 nextRequest->mResultExtras);
5166 }
5167 return NULL;
5168 }
5169 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005170 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005171
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005172 return nextRequest;
5173}
5174
5175bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005176 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005177 status_t res;
5178 Mutex::Autolock l(mPauseLock);
5179 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005180 if (mPaused == false) {
5181 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005182 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5183 // Let the tracker know
5184 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5185 if (statusTracker != 0) {
5186 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5187 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005188 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005189
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005190 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005191 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005192 return true;
5193 }
5194 }
5195 // We don't set mPaused to false here, because waitForNextRequest needs
5196 // to further manage the paused state in case of starvation.
5197 return false;
5198}
5199
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005200void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005201 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005202 // With work to do, mark thread as unpaused.
5203 // If paused by request (setPaused), don't resume, to avoid
5204 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005205 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005206 Mutex::Autolock p(mPauseLock);
5207 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005208 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5209 if (mPaused) {
5210 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5211 if (statusTracker != 0) {
5212 statusTracker->markComponentActive(mStatusId);
5213 }
5214 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005215 mPaused = false;
5216 }
5217}
5218
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005219void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5220 sp<Camera3Device> parent = mParent.promote();
5221 if (parent != NULL) {
5222 va_list args;
5223 va_start(args, fmt);
5224
5225 parent->setErrorStateV(fmt, args);
5226
5227 va_end(args);
5228 }
5229}
5230
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005231status_t Camera3Device::RequestThread::insertTriggers(
5232 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005233 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005234 Mutex::Autolock al(mTriggerMutex);
5235
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005236 sp<Camera3Device> parent = mParent.promote();
5237 if (parent == NULL) {
5238 CLOGE("RequestThread: Parent is gone");
5239 return DEAD_OBJECT;
5240 }
5241
Emilian Peevaebbe412018-01-15 13:53:24 +00005242 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005243 size_t count = mTriggerMap.size();
5244
5245 for (size_t i = 0; i < count; ++i) {
5246 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005247 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005248
5249 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5250 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5251 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005252 if (isAeTrigger) {
5253 request->mResultExtras.precaptureTriggerId = triggerId;
5254 mCurrentPreCaptureTriggerId = triggerId;
5255 } else {
5256 request->mResultExtras.afTriggerId = triggerId;
5257 mCurrentAfTriggerId = triggerId;
5258 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005259 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005260 }
5261
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005262 camera_metadata_entry entry = metadata.find(tag);
5263
5264 if (entry.count > 0) {
5265 /**
5266 * Already has an entry for this trigger in the request.
5267 * Rewrite it with our requested trigger value.
5268 */
5269 RequestTrigger oldTrigger = trigger;
5270
5271 oldTrigger.entryValue = entry.data.u8[0];
5272
5273 mTriggerReplacedMap.add(tag, oldTrigger);
5274 } else {
5275 /**
5276 * More typical, no trigger entry, so we just add it
5277 */
5278 mTriggerRemovedMap.add(tag, trigger);
5279 }
5280
5281 status_t res;
5282
5283 switch (trigger.getTagType()) {
5284 case TYPE_BYTE: {
5285 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5286 res = metadata.update(tag,
5287 &entryValue,
5288 /*count*/1);
5289 break;
5290 }
5291 case TYPE_INT32:
5292 res = metadata.update(tag,
5293 &trigger.entryValue,
5294 /*count*/1);
5295 break;
5296 default:
5297 ALOGE("%s: Type not supported: 0x%x",
5298 __FUNCTION__,
5299 trigger.getTagType());
5300 return INVALID_OPERATION;
5301 }
5302
5303 if (res != OK) {
5304 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5305 ", value %d", __FUNCTION__, trigger.getTagName(),
5306 trigger.entryValue);
5307 return res;
5308 }
5309
5310 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5311 trigger.getTagName(),
5312 trigger.entryValue);
5313 }
5314
5315 mTriggerMap.clear();
5316
5317 return count;
5318}
5319
5320status_t Camera3Device::RequestThread::removeTriggers(
5321 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005322 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005323 Mutex::Autolock al(mTriggerMutex);
5324
Emilian Peevaebbe412018-01-15 13:53:24 +00005325 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005326
5327 /**
5328 * Replace all old entries with their old values.
5329 */
5330 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5331 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5332
5333 status_t res;
5334
5335 uint32_t tag = trigger.metadataTag;
5336 switch (trigger.getTagType()) {
5337 case TYPE_BYTE: {
5338 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5339 res = metadata.update(tag,
5340 &entryValue,
5341 /*count*/1);
5342 break;
5343 }
5344 case TYPE_INT32:
5345 res = metadata.update(tag,
5346 &trigger.entryValue,
5347 /*count*/1);
5348 break;
5349 default:
5350 ALOGE("%s: Type not supported: 0x%x",
5351 __FUNCTION__,
5352 trigger.getTagType());
5353 return INVALID_OPERATION;
5354 }
5355
5356 if (res != OK) {
5357 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5358 ", trigger value %d", __FUNCTION__,
5359 trigger.getTagName(), trigger.entryValue);
5360 return res;
5361 }
5362 }
5363 mTriggerReplacedMap.clear();
5364
5365 /**
5366 * Remove all new entries.
5367 */
5368 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5369 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5370 status_t res = metadata.erase(trigger.metadataTag);
5371
5372 if (res != OK) {
5373 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5374 ", trigger value %d", __FUNCTION__,
5375 trigger.getTagName(), trigger.entryValue);
5376 return res;
5377 }
5378 }
5379 mTriggerRemovedMap.clear();
5380
5381 return OK;
5382}
5383
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005384status_t Camera3Device::RequestThread::addDummyTriggerIds(
5385 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005386 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005387 static const int32_t dummyTriggerId = 1;
5388 status_t res;
5389
Emilian Peevaebbe412018-01-15 13:53:24 +00005390 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005391
5392 // If AF trigger is active, insert a dummy AF trigger ID if none already
5393 // exists
5394 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5395 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5396 if (afTrigger.count > 0 &&
5397 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5398 afId.count == 0) {
5399 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5400 if (res != OK) return res;
5401 }
5402
5403 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5404 // if none already exists
5405 camera_metadata_entry pcTrigger =
5406 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5407 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5408 if (pcTrigger.count > 0 &&
5409 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5410 pcId.count == 0) {
5411 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5412 &dummyTriggerId, 1);
5413 if (res != OK) return res;
5414 }
5415
5416 return OK;
5417}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005418
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005419/**
5420 * PreparerThread inner class methods
5421 */
5422
5423Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005424 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005425 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005426}
5427
5428Camera3Device::PreparerThread::~PreparerThread() {
5429 Thread::requestExitAndWait();
5430 if (mCurrentStream != nullptr) {
5431 mCurrentStream->cancelPrepare();
5432 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5433 mCurrentStream.clear();
5434 }
5435 clear();
5436}
5437
Ruben Brunkc78ac262015-08-13 17:58:46 -07005438status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005439 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005440 status_t res;
5441
5442 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005443 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005444
Ruben Brunkc78ac262015-08-13 17:58:46 -07005445 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005446 if (res == OK) {
5447 // No preparation needed, fire listener right off
5448 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005449 if (listener != NULL) {
5450 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005451 }
5452 return OK;
5453 } else if (res != NOT_ENOUGH_DATA) {
5454 return res;
5455 }
5456
5457 // Need to prepare, start up thread if necessary
5458 if (!mActive) {
5459 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5460 // isn't running
5461 Thread::requestExitAndWait();
5462 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5463 if (res != OK) {
5464 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005465 if (listener != NULL) {
5466 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005467 }
5468 return res;
5469 }
5470 mCancelNow = false;
5471 mActive = true;
5472 ALOGV("%s: Preparer stream started", __FUNCTION__);
5473 }
5474
5475 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005476 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005477 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5478
5479 return OK;
5480}
5481
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005482void Camera3Device::PreparerThread::pause() {
5483 ATRACE_CALL();
5484
5485 Mutex::Autolock l(mLock);
5486
5487 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5488 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5489 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5490 int currentMaxCount = mCurrentMaxCount;
5491 mPendingStreams.clear();
5492 mCancelNow = true;
5493 while (mActive) {
5494 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5495 if (res == TIMED_OUT) {
5496 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5497 return;
5498 } else if (res != OK) {
5499 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5500 return;
5501 }
5502 }
5503
5504 //Check whether the prepare thread was able to complete the current
5505 //stream. In case work is still pending emplace it along with the rest
5506 //of the streams in the pending list.
5507 if (currentStream != nullptr) {
5508 if (!mCurrentPrepareComplete) {
5509 pendingStreams.emplace(currentMaxCount, currentStream);
5510 }
5511 }
5512
5513 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5514 for (const auto& it : mPendingStreams) {
5515 it.second->cancelPrepare();
5516 }
5517}
5518
5519status_t Camera3Device::PreparerThread::resume() {
5520 ATRACE_CALL();
5521 status_t res;
5522
5523 Mutex::Autolock l(mLock);
5524 sp<NotificationListener> listener = mListener.promote();
5525
5526 if (mActive) {
5527 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5528 return NO_INIT;
5529 }
5530
5531 auto it = mPendingStreams.begin();
5532 for (; it != mPendingStreams.end();) {
5533 res = it->second->startPrepare(it->first);
5534 if (res == OK) {
5535 if (listener != NULL) {
5536 listener->notifyPrepared(it->second->getId());
5537 }
5538 it = mPendingStreams.erase(it);
5539 } else if (res != NOT_ENOUGH_DATA) {
5540 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5541 res, strerror(-res));
5542 it = mPendingStreams.erase(it);
5543 } else {
5544 it++;
5545 }
5546 }
5547
5548 if (mPendingStreams.empty()) {
5549 return OK;
5550 }
5551
5552 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5553 if (res != OK) {
5554 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5555 __FUNCTION__, res, strerror(-res));
5556 return res;
5557 }
5558 mCancelNow = false;
5559 mActive = true;
5560 ALOGV("%s: Preparer stream started", __FUNCTION__);
5561
5562 return OK;
5563}
5564
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005565status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005566 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005567 Mutex::Autolock l(mLock);
5568
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005569 for (const auto& it : mPendingStreams) {
5570 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005571 }
5572 mPendingStreams.clear();
5573 mCancelNow = true;
5574
5575 return OK;
5576}
5577
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005578void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005579 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005580 Mutex::Autolock l(mLock);
5581 mListener = listener;
5582}
5583
5584bool Camera3Device::PreparerThread::threadLoop() {
5585 status_t res;
5586 {
5587 Mutex::Autolock l(mLock);
5588 if (mCurrentStream == nullptr) {
5589 // End thread if done with work
5590 if (mPendingStreams.empty()) {
5591 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5592 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5593 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5594 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005595 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596 return false;
5597 }
5598
5599 // Get next stream to prepare
5600 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005601 mCurrentStream = it->second;
5602 mCurrentMaxCount = it->first;
5603 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005604 mPendingStreams.erase(it);
5605 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5606 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5607 } else if (mCancelNow) {
5608 mCurrentStream->cancelPrepare();
5609 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5610 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5611 mCurrentStream.clear();
5612 mCancelNow = false;
5613 return true;
5614 }
5615 }
5616
5617 res = mCurrentStream->prepareNextBuffer();
5618 if (res == NOT_ENOUGH_DATA) return true;
5619 if (res != OK) {
5620 // Something bad happened; try to recover by cancelling prepare and
5621 // signalling listener anyway
5622 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5623 mCurrentStream->getId(), res, strerror(-res));
5624 mCurrentStream->cancelPrepare();
5625 }
5626
5627 // This stream has finished, notify listener
5628 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005629 sp<NotificationListener> listener = mListener.promote();
5630 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005631 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5632 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005633 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005634 }
5635
5636 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5637 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005638 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005639
5640 return true;
5641}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005642
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005643/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005644 * Static callback forwarding methods from HAL to instance
5645 */
5646
5647void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5648 const camera3_capture_result *result) {
5649 Camera3Device *d =
5650 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005651
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005652 d->processCaptureResult(result);
5653}
5654
5655void Camera3Device::sNotify(const camera3_callback_ops *cb,
5656 const camera3_notify_msg *msg) {
5657 Camera3Device *d =
5658 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5659 d->notify(msg);
5660}
5661
5662}; // namespace android