blob: 6b60132b0467c6cf245b90465d212a2d37afdc0a [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080042#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070045#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070046
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080047#include <android/hardware/camera2/ICameraDeviceUser.h>
48
Igor Murashkinff3e31d2013-10-23 16:40:06 -070049#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070050#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051#include "device3/Camera3Device.h"
52#include "device3/Camera3OutputStream.h"
53#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070054#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070055#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070056#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080057
58using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080059using namespace android::hardware::camera;
60using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080061
62namespace android {
63
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080064Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080065 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080066 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070067 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070068 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070069 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070070 mUsePartialResult(false),
71 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080072 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070073 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070074 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070076 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000077 mListener(NULL),
78 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080079{
80 ATRACE_CALL();
81 camera3_callback_ops::notify = &sNotify;
82 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080083 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084}
85
86Camera3Device::~Camera3Device()
87{
88 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080089 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080090 disconnect();
91}
92
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080094 return mId;
95}
96
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080097status_t Camera3Device::initialize(sp<CameraProviderManager> manager) {
98 ATRACE_CALL();
99 Mutex::Autolock il(mInterfaceLock);
100 Mutex::Autolock l(mLock);
101
102 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
103 if (mStatus != STATUS_UNINITIALIZED) {
104 CLOGE("Already initialized!");
105 return INVALID_OPERATION;
106 }
107 if (manager == nullptr) return INVALID_OPERATION;
108
109 sp<ICameraDeviceSession> session;
110 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800111 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112 /*out*/ &session);
113 ATRACE_END();
114 if (res != OK) {
115 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
116 return res;
117 }
118
Steven Moreland5ff9c912017-03-09 23:13:00 -0800119 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 if (res != OK) {
121 SET_ERR_L("Could not retrive camera characteristics: %s (%d)", strerror(-res), res);
122 session->close();
123 return res;
124 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800125
Yifan Hongf79b5542017-04-11 14:44:25 -0700126 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700127 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
128 [&queue](const auto& descriptor) {
129 queue = std::make_shared<RequestMetadataQueue>(descriptor);
130 if (!queue->isValid() || queue->availableToWrite() <= 0) {
131 ALOGE("HAL returns empty request metadata fmq, not use it");
132 queue = nullptr;
133 // don't use the queue onwards.
134 }
135 });
136 if (!requestQueueRet.isOk()) {
137 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
138 requestQueueRet.description().c_str());
Yifan Hongf79b5542017-04-11 14:44:25 -0700139 queue = nullptr;
140 // Don't use the queue onwards.
141 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700142 auto resultQueueRet = session->getCaptureResultMetadataQueue(
143 [&queue = mResultMetadataQueue](const auto& descriptor) {
144 queue = std::make_unique<ResultMetadataQueue>(descriptor);
145 if (!queue->isValid() || queue->availableToWrite() <= 0) {
146 ALOGE("HAL returns empty result metadata fmq, not use it");
147 queue = nullptr;
148 // Don't use the queue onwards.
149 }
150 });
151 if (!resultQueueRet.isOk()) {
152 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
153 resultQueueRet.description().c_str());
154 mResultMetadataQueue = nullptr;
155 // Don't use the queue onwards.
156 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700157
Yifan Hongf79b5542017-04-11 14:44:25 -0700158 mInterface = std::make_unique<HalInterface>(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000159 std::string providerType;
160 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800161
162 return initializeCommonLocked();
163}
164
165status_t Camera3Device::initializeCommonLocked() {
166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700167 /** Start up status tracker thread */
168 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800169 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700170 if (res != OK) {
171 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
172 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700174 mStatusTracker.clear();
175 return res;
176 }
177
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700178 /** Register in-flight map to the status tracker */
179 mInFlightStatusId = mStatusTracker->addComponent();
180
Zhijun He125684a2015-12-26 15:07:30 -0800181 /** Create buffer manager */
182 mBufferManager = new Camera3BufferManager();
183
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 mTagMonitor.initialize(mVendorTagId);
185
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700186 /** Start up request queue thread */
Emilian Peev7e25e5e2017-04-07 15:48:49 +0100187 mRequestThread = new RequestThread(this, mStatusTracker, mInterface.get());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800188 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700190 SET_ERR_L("Unable to start request queue thread: %s (%d)",
191 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800192 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800193 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800194 return res;
195 }
196
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700197 mPreparerThread = new PreparerThread();
198
Ruben Brunk183f0562015-08-12 12:55:02 -0700199 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800200 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700201 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700202 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800204
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800205 // Measure the clock domain offset between camera and video/hw_composer
206 camera_metadata_entry timestampSource =
207 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
208 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
209 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
210 mTimestampOffset = getMonoToBoottimeOffset();
211 }
212
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700213 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100214 camera_metadata_entry partialResultsCount =
215 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
216 if (partialResultsCount.count > 0) {
217 mNumPartialResults = partialResultsCount.data.i32[0];
218 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700219 }
220
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700221 camera_metadata_entry configs =
222 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
223 for (uint32_t i = 0; i < configs.count; i += 4) {
224 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
225 configs.data.i32[i + 3] ==
226 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
227 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
228 configs.data.i32[i + 2]));
229 }
230 }
231
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800232 return OK;
233}
234
235status_t Camera3Device::disconnect() {
236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800238
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700239 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800240
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700241 status_t res = OK;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800242
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700243 {
244 Mutex::Autolock l(mLock);
245 if (mStatus == STATUS_UNINITIALIZED) return res;
246
247 if (mStatus == STATUS_ACTIVE ||
248 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
249 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 } else {
254 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
255 if (res != OK) {
256 SET_ERR_L("Timeout waiting for HAL to drain");
257 // Continue to close device even in case of error
258 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700259 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800260 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 if (mStatus == STATUS_ERROR) {
263 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700264 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265
266 if (mStatusTracker != NULL) {
267 mStatusTracker->requestExit();
268 }
269
270 if (mRequestThread != NULL) {
271 mRequestThread->requestExit();
272 }
273
274 mOutputStreams.clear();
275 mInputStream.clear();
276 }
277
278 // Joining done without holding mLock, otherwise deadlocks may ensue
279 // as the threads try to access parent state
280 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
281 // HAL may be in a bad state, so waiting for request thread
282 // (which may be stuck in the HAL processCaptureRequest call)
283 // could be dangerous.
284 mRequestThread->join();
285 }
286
287 if (mStatusTracker != NULL) {
288 mStatusTracker->join();
289 }
290
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800291 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292 {
293 Mutex::Autolock l(mLock);
294
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800295 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 mStatusTracker.clear();
Zhijun He125684a2015-12-26 15:07:30 -0800297 mBufferManager.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800298
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800299 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700300 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800301
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700302 // Call close without internal mutex held, as the HAL close may need to
303 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800304 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700305
306 {
307 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800308 mInterface->clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700309 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800311
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700312 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700313 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800314}
315
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316// For dumping/debugging only -
317// try to acquire a lock a few times, eventually give up to proceed with
318// debug/dump operations
319bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
320 bool gotLock = false;
321 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
322 if (lock.tryLock() == NO_ERROR) {
323 gotLock = true;
324 break;
325 } else {
326 usleep(kDumpSleepDuration);
327 }
328 }
329 return gotLock;
330}
331
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700332Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
333 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100334 const int STREAM_CONFIGURATION_SIZE = 4;
335 const int STREAM_FORMAT_OFFSET = 0;
336 const int STREAM_WIDTH_OFFSET = 1;
337 const int STREAM_HEIGHT_OFFSET = 2;
338 const int STREAM_IS_INPUT_OFFSET = 3;
339 camera_metadata_ro_entry_t availableStreamConfigs =
340 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
341 if (availableStreamConfigs.count == 0 ||
342 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
343 return Size(0, 0);
344 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700345
Emilian Peev08dd2452017-04-06 16:55:14 +0100346 // Get max jpeg size (area-wise).
347 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
348 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
349 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
350 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
351 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
352 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
353 && format == HAL_PIXEL_FORMAT_BLOB &&
354 (width * height > maxJpegWidth * maxJpegHeight)) {
355 maxJpegWidth = width;
356 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700357 }
358 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100359
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700360 return Size(maxJpegWidth, maxJpegHeight);
361}
362
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800363nsecs_t Camera3Device::getMonoToBoottimeOffset() {
364 // try three times to get the clock offset, choose the one
365 // with the minimum gap in measurements.
366 const int tries = 3;
367 nsecs_t bestGap, measured;
368 for (int i = 0; i < tries; ++i) {
369 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
371 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
372 const nsecs_t gap = tmono2 - tmono;
373 if (i == 0 || gap < bestGap) {
374 bestGap = gap;
375 measured = tbase - ((tmono + tmono2) >> 1);
376 }
377 }
378 return measured;
379}
380
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800381hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
382 int frameworkFormat) {
383 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
384}
385
386DataspaceFlags Camera3Device::mapToHidlDataspace(
387 android_dataspace dataSpace) {
388 return dataSpace;
389}
390
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700391BufferUsageFlags Camera3Device::mapToConsumerUsage(
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700392 uint32_t usage) {
393 return usage;
394}
395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800396StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
397 switch (rotation) {
398 case CAMERA3_STREAM_ROTATION_0:
399 return StreamRotation::ROTATION_0;
400 case CAMERA3_STREAM_ROTATION_90:
401 return StreamRotation::ROTATION_90;
402 case CAMERA3_STREAM_ROTATION_180:
403 return StreamRotation::ROTATION_180;
404 case CAMERA3_STREAM_ROTATION_270:
405 return StreamRotation::ROTATION_270;
406 }
407 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
408 return StreamRotation::ROTATION_0;
409}
410
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800411status_t Camera3Device::mapToStreamConfigurationMode(
412 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
413 if (mode == nullptr) return BAD_VALUE;
414 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
415 switch(operationMode) {
416 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
417 *mode = StreamConfigurationMode::NORMAL_MODE;
418 break;
419 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
420 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
421 break;
422 default:
423 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
424 return BAD_VALUE;
425 }
426 } else {
427 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800428 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800429 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800430}
431
432camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
433 switch (status) {
434 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
435 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
436 }
437 return CAMERA3_BUFFER_STATUS_ERROR;
438}
439
440int Camera3Device::mapToFrameworkFormat(
441 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
442 return static_cast<uint32_t>(pixelFormat);
443}
444
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700445uint32_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700446 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700447 return usage;
448}
449
450uint32_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700451 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700452 return usage;
453}
454
Zhijun Hef7da0962014-04-24 13:27:56 -0700455ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700456 // Get max jpeg size (area-wise).
457 Size maxJpegResolution = getMaxJpegResolution();
458 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800459 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
460 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700461 return BAD_VALUE;
462 }
463
Zhijun Hef7da0962014-04-24 13:27:56 -0700464 // Get max jpeg buffer size
465 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700466 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
467 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800468 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
469 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700470 return BAD_VALUE;
471 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700472 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800473 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700474
475 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700476 float scaleFactor = ((float) (width * height)) /
477 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800478 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
479 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700480 if (jpegBufferSize > maxJpegBufferSize) {
481 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700482 }
483
484 return jpegBufferSize;
485}
486
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700487ssize_t Camera3Device::getPointCloudBufferSize() const {
488 const int FLOATS_PER_POINT=4;
489 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
490 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800491 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
492 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700493 return BAD_VALUE;
494 }
495 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
496 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
497 return maxBytesForPointCloud;
498}
499
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800500ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800501 const int PER_CONFIGURATION_SIZE = 3;
502 const int WIDTH_OFFSET = 0;
503 const int HEIGHT_OFFSET = 1;
504 const int SIZE_OFFSET = 2;
505 camera_metadata_ro_entry rawOpaqueSizes =
506 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800507 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800508 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800509 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
510 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800511 return BAD_VALUE;
512 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700513
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800514 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
515 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
516 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
517 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
518 }
519 }
520
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800521 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
522 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800523 return BAD_VALUE;
524}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700525
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800526status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
527 ATRACE_CALL();
528 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700529
530 // Try to lock, but continue in case of failure (to avoid blocking in
531 // deadlocks)
532 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
533 bool gotLock = tryLockSpinRightRound(mLock);
534
535 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
537 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700538 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800539 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
540 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700541
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800542 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700543
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800544 String16 templatesOption("-t");
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700545 String16 monitorOption("-m");
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800546 int n = args.size();
547 for (int i = 0; i < n; i++) {
548 if (args[i] == templatesOption) {
549 dumpTemplates = true;
550 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700551 if (args[i] == monitorOption) {
552 if (i + 1 < n) {
553 String8 monitorTags = String8(args[i + 1]);
554 if (monitorTags == "off") {
555 mTagMonitor.disableMonitoring();
556 } else {
557 mTagMonitor.parseTagsToMonitor(monitorTags);
558 }
559 } else {
560 mTagMonitor.disableMonitoring();
561 }
562 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800563 }
564
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800565 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800566
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800567 const char *status =
568 mStatus == STATUS_ERROR ? "ERROR" :
569 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700570 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
571 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800572 mStatus == STATUS_ACTIVE ? "ACTIVE" :
573 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700574
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800575 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700576 if (mStatus == STATUS_ERROR) {
577 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
578 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800579 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800580 const char *mode =
581 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
582 mOperatingMode == static_cast<int>(
583 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
584 "CUSTOM";
585 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800586
587 if (mInputStream != NULL) {
588 write(fd, lines.string(), lines.size());
589 mInputStream->dump(fd, args);
590 } else {
591 lines.appendFormat(" No input stream.\n");
592 write(fd, lines.string(), lines.size());
593 }
594 for (size_t i = 0; i < mOutputStreams.size(); i++) {
595 mOutputStreams[i]->dump(fd,args);
596 }
597
Zhijun He431503c2016-03-07 17:30:16 -0800598 if (mBufferManager != NULL) {
599 lines = String8(" Camera3 Buffer Manager:\n");
600 write(fd, lines.string(), lines.size());
601 mBufferManager->dump(fd, args);
602 }
Zhijun He125684a2015-12-26 15:07:30 -0800603
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700604 lines = String8(" In-flight requests:\n");
605 if (mInFlightMap.size() == 0) {
606 lines.append(" None\n");
607 } else {
608 for (size_t i = 0; i < mInFlightMap.size(); i++) {
609 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700610 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700611 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800612 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700613 r.numBuffersLeft);
614 }
615 }
616 write(fd, lines.string(), lines.size());
617
Igor Murashkin1e479c02013-09-06 16:55:14 -0700618 {
619 lines = String8(" Last request sent:\n");
620 write(fd, lines.string(), lines.size());
621
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700622 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700623 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
624 }
625
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 if (dumpTemplates) {
627 const char *templateNames[] = {
628 "TEMPLATE_PREVIEW",
629 "TEMPLATE_STILL_CAPTURE",
630 "TEMPLATE_VIDEO_RECORD",
631 "TEMPLATE_VIDEO_SNAPSHOT",
632 "TEMPLATE_ZERO_SHUTTER_LAG",
633 "TEMPLATE_MANUAL"
634 };
635
636 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 camera_metadata_t *templateRequest = nullptr;
638 mInterface->constructDefaultRequestSettings(
639 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800640 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800642 lines.append(" Not supported\n");
643 write(fd, lines.string(), lines.size());
644 } else {
645 write(fd, lines.string(), lines.size());
646 dump_indented_camera_metadata(templateRequest,
647 fd, /*verbosity*/2, /*indentation*/8);
648 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800649 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800650 }
651 }
652
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700653 mTagMonitor.dumpMonitoredMetadata(fd);
654
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800655 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800656 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800659 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800660
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700661 if (gotLock) mLock.unlock();
662 if (gotInterfaceLock) mInterfaceLock.unlock();
663
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800664 return OK;
665}
666
667const CameraMetadata& Camera3Device::info() const {
668 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800669 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
670 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700671 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 mStatus == STATUS_ERROR ?
673 "when in error state" : "before init");
674 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800675 return mDeviceInfo;
676}
677
Jianing Wei90e59c92014-03-12 18:29:36 -0700678status_t Camera3Device::checkStatusOkToCaptureLocked() {
679 switch (mStatus) {
680 case STATUS_ERROR:
681 CLOGE("Device has encountered a serious error");
682 return INVALID_OPERATION;
683 case STATUS_UNINITIALIZED:
684 CLOGE("Device not initialized");
685 return INVALID_OPERATION;
686 case STATUS_UNCONFIGURED:
687 case STATUS_CONFIGURED:
688 case STATUS_ACTIVE:
689 // OK
690 break;
691 default:
692 SET_ERR_L("Unexpected status: %d", mStatus);
693 return INVALID_OPERATION;
694 }
695 return OK;
696}
697
698status_t Camera3Device::convertMetadataListToRequestListLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700699 const List<const CameraMetadata> &metadataList,
700 const std::list<const SurfaceMap> &surfaceMaps,
701 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700702 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700703 if (requestList == NULL) {
704 CLOGE("requestList cannot be NULL.");
705 return BAD_VALUE;
706 }
707
Jianing Weicb0652e2014-03-12 18:29:36 -0700708 int32_t burstId = 0;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700709 List<const CameraMetadata>::const_iterator metadataIt = metadataList.begin();
710 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
711 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
712 ++metadataIt, ++surfaceMapIt) {
713 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700714 if (newRequest == 0) {
715 CLOGE("Can't create capture request");
716 return BAD_VALUE;
717 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700718
Shuzhen Wang9d066012016-09-30 11:30:20 -0700719 newRequest->mRepeating = repeating;
720
Jianing Weicb0652e2014-03-12 18:29:36 -0700721 // Setup burst Id and request Id
722 newRequest->mResultExtras.burstId = burstId++;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700723 if (metadataIt->exists(ANDROID_REQUEST_ID)) {
724 if (metadataIt->find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700725 CLOGE("RequestID entry exists; but must not be empty in metadata");
726 return BAD_VALUE;
727 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700728 newRequest->mResultExtras.requestId = metadataIt->find(ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700729 } else {
730 CLOGE("RequestID does not exist in metadata");
731 return BAD_VALUE;
732 }
733
Jianing Wei90e59c92014-03-12 18:29:36 -0700734 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700735
736 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700737 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700738 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
739 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
740 return BAD_VALUE;
741 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700742
743 // Setup batch size if this is a high speed video recording request.
744 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
745 auto firstRequest = requestList->begin();
746 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
747 if (outputStream->isVideoStream()) {
748 (*firstRequest)->mBatchSize = requestList->size();
749 break;
750 }
751 }
752 }
753
Jianing Wei90e59c92014-03-12 18:29:36 -0700754 return OK;
755}
756
Jianing Weicb0652e2014-03-12 18:29:36 -0700757status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800758 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800759
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700760 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761 std::list<const SurfaceMap> surfaceMaps;
762 convertToRequestList(requests, surfaceMaps, request);
763
764 return captureList(requests, surfaceMaps, /*lastFrameNumber*/NULL);
765}
766
767void Camera3Device::convertToRequestList(List<const CameraMetadata>& requests,
768 std::list<const SurfaceMap>& surfaceMaps,
769 const CameraMetadata& request) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700770 requests.push_back(request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700771
772 SurfaceMap surfaceMap;
773 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
774 // With no surface list passed in, stream and surface will have 1-to-1
775 // mapping. So the surface index is 0 for each stream in the surfaceMap.
776 for (size_t i = 0; i < streams.count; i++) {
777 surfaceMap[streams.data.i32[i]].push_back(0);
778 }
779 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800780}
781
Jianing Wei90e59c92014-03-12 18:29:36 -0700782status_t Camera3Device::submitRequestsHelper(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700783 const List<const CameraMetadata> &requests,
784 const std::list<const SurfaceMap> &surfaceMaps,
785 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700786 /*out*/
787 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700788 ATRACE_CALL();
789 Mutex::Autolock il(mInterfaceLock);
790 Mutex::Autolock l(mLock);
791
792 status_t res = checkStatusOkToCaptureLocked();
793 if (res != OK) {
794 // error logged by previous call
795 return res;
796 }
797
798 RequestList requestList;
799
Shuzhen Wang0129d522016-10-30 22:43:41 -0700800 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
801 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 if (res != OK) {
803 // error logged by previous call
804 return res;
805 }
806
807 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700808 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700809 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700810 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 }
812
813 if (res == OK) {
814 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
815 if (res != OK) {
816 SET_ERR_L("Can't transition to active in %f seconds!",
817 kActiveTimeout/1e9);
818 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800819 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700820 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700821 } else {
822 CLOGE("Cannot queue request. Impossible.");
823 return BAD_VALUE;
824 }
825
826 return res;
827}
828
Yifan Honga640c5a2017-04-12 16:30:31 -0700829// Only one processCaptureResult should be called at a time, so
830// the locks won't block. The locks are present here simply to enforce this.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800831hardware::Return<void> Camera3Device::processCaptureResult(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800832 const hardware::hidl_vec<
833 hardware::camera::device::V3_2::CaptureResult>& results) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700834
835 if (mProcessCaptureResultLock.tryLock() != OK) {
836 // This should never happen; it indicates a wrong client implementation
837 // that doesn't follow the contract. But, we can be tolerant here.
838 ALOGE("%s: callback overlapped! waiting 1s...",
839 __FUNCTION__);
840 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
841 ALOGE("%s: cannot acquire lock in 1s, dropping results",
842 __FUNCTION__);
843 // really don't know what to do, so bail out.
844 return hardware::Void();
845 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800846 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700847 for (const auto& result : results) {
848 processOneCaptureResultLocked(result);
849 }
850 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800851 return hardware::Void();
852}
853
Yifan Honga640c5a2017-04-12 16:30:31 -0700854void Camera3Device::processOneCaptureResultLocked(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800855 const hardware::camera::device::V3_2::CaptureResult& result) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800856 camera3_capture_result r;
857 status_t res;
858 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -0700859
860 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
861 if (result.fmqResultSize > 0) {
862 resultMetadata.resize(result.fmqResultSize);
863 if (mResultMetadataQueue == nullptr) {
864 return; // logged in initialize()
865 }
866 if (!mResultMetadataQueue->read(resultMetadata.data(), result.fmqResultSize)) {
867 ALOGE("%s: Frame %d: Cannot read camera metadata from fmq, size = %" PRIu64,
868 __FUNCTION__, result.frameNumber, result.fmqResultSize);
869 return;
870 }
871 } else {
872 resultMetadata.setToExternal(const_cast<uint8_t *>(result.result.data()),
873 result.result.size());
874 }
875
876 if (resultMetadata.size() != 0) {
877 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
878 size_t expected_metadata_size = resultMetadata.size();
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800879 if ((res = validate_camera_metadata_structure(r.result, &expected_metadata_size)) != OK) {
880 ALOGE("%s: Frame %d: Invalid camera metadata received by camera service from HAL: %s (%d)",
881 __FUNCTION__, result.frameNumber, strerror(-res), res);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800882 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800883 }
884 } else {
885 r.result = nullptr;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800886 }
887
888 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
889 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
890 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
891 auto& bDst = outputBuffers[i];
892 const StreamBuffer &bSrc = result.outputBuffers[i];
893
894 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100895 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800896 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
897 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800898 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800899 }
900 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
901
902 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -0800903 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800904 if (res != OK) {
905 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
906 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800907 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800908 }
909 bDst.buffer = buffer;
910 bDst.status = mapHidlBufferStatus(bSrc.status);
911 bDst.acquire_fence = -1;
912 if (bSrc.releaseFence == nullptr) {
913 bDst.release_fence = -1;
914 } else if (bSrc.releaseFence->numFds == 1) {
915 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
916 } else {
917 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
918 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800919 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800920 }
921 }
922 r.num_output_buffers = outputBuffers.size();
923 r.output_buffers = outputBuffers.data();
924
925 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800926 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800927 r.input_buffer = nullptr;
928 } else {
929 if (mInputStream->getId() != result.inputBuffer.streamId) {
930 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
931 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800932 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800933 }
934 inputBuffer.stream = mInputStream->asHalStream();
935 buffer_handle_t *buffer;
936 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
937 &buffer);
938 if (res != OK) {
939 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
940 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800941 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800942 }
943 inputBuffer.buffer = buffer;
944 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
945 inputBuffer.acquire_fence = -1;
946 if (result.inputBuffer.releaseFence == nullptr) {
947 inputBuffer.release_fence = -1;
948 } else if (result.inputBuffer.releaseFence->numFds == 1) {
949 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
950 } else {
951 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
952 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800953 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800954 }
955 r.input_buffer = &inputBuffer;
956 }
957
958 r.partial_result = result.partialResult;
959
960 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800961}
962
963hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800964 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
965 for (const auto& msg : msgs) {
966 notify(msg);
967 }
968 return hardware::Void();
969}
970
971void Camera3Device::notify(
972 const hardware::camera::device::V3_2::NotifyMsg& msg) {
973
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800974 camera3_notify_msg m;
975 switch (msg.type) {
976 case MsgType::ERROR:
977 m.type = CAMERA3_MSG_ERROR;
978 m.message.error.frame_number = msg.msg.error.frameNumber;
979 if (msg.msg.error.errorStreamId >= 0) {
980 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +0100981 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800982 ALOGE("%s: Frame %d: Invalid error stream id %d",
983 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800984 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800985 }
986 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
987 } else {
988 m.message.error.error_stream = nullptr;
989 }
990 switch (msg.msg.error.errorCode) {
991 case ErrorCode::ERROR_DEVICE:
992 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
993 break;
994 case ErrorCode::ERROR_REQUEST:
995 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
996 break;
997 case ErrorCode::ERROR_RESULT:
998 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
999 break;
1000 case ErrorCode::ERROR_BUFFER:
1001 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1002 break;
1003 }
1004 break;
1005 case MsgType::SHUTTER:
1006 m.type = CAMERA3_MSG_SHUTTER;
1007 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1008 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1009 break;
1010 }
1011 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001012}
1013
Jianing Weicb0652e2014-03-12 18:29:36 -07001014status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001015 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001016 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001017 ATRACE_CALL();
1018
Shuzhen Wang0129d522016-10-30 22:43:41 -07001019 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001020}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001021
Jianing Weicb0652e2014-03-12 18:29:36 -07001022status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1023 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001024 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001025
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001026 List<const CameraMetadata> requests;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001027 std::list<const SurfaceMap> surfaceMaps;
1028 convertToRequestList(requests, surfaceMaps, request);
1029
1030 return setStreamingRequestList(requests, /*surfaceMap*/surfaceMaps,
1031 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001032}
1033
Jianing Weicb0652e2014-03-12 18:29:36 -07001034status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001035 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001036 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001037 ATRACE_CALL();
1038
Shuzhen Wang0129d522016-10-30 22:43:41 -07001039 return submitRequestsHelper(requests, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001040}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001041
1042sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001043 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001044 status_t res;
1045
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001046 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001047 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1048 // so unilaterally select normal operating mode.
1049 res = configureStreamsLocked(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001050 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001052 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001053 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001054 } else if (mStatus == STATUS_UNCONFIGURED) {
1055 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001056 CLOGE("No streams configured");
1057 return NULL;
1058 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001059 }
1060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001063}
1064
Jianing Weicb0652e2014-03-12 18:29:36 -07001065status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001066 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001067 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001068 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001069
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001070 switch (mStatus) {
1071 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001072 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073 return INVALID_OPERATION;
1074 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001075 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001076 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001077 case STATUS_UNCONFIGURED:
1078 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 case STATUS_ACTIVE:
1080 // OK
1081 break;
1082 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001083 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001084 return INVALID_OPERATION;
1085 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001086 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001087
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001088 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001089}
1090
1091status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1092 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001093 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001094
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001095 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001096}
1097
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001098status_t Camera3Device::createInputStream(
1099 uint32_t width, uint32_t height, int format, int *id) {
1100 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001101 Mutex::Autolock il(mInterfaceLock);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001102 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001103 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1104 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001105
1106 status_t res;
1107 bool wasActive = false;
1108
1109 switch (mStatus) {
1110 case STATUS_ERROR:
1111 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1112 return INVALID_OPERATION;
1113 case STATUS_UNINITIALIZED:
1114 ALOGE("%s: Device not initialized", __FUNCTION__);
1115 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001116 case STATUS_UNCONFIGURED:
1117 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001118 // OK
1119 break;
1120 case STATUS_ACTIVE:
1121 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001122 res = internalPauseAndWaitLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001123 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001124 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001125 return res;
1126 }
1127 wasActive = true;
1128 break;
1129 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001130 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001131 return INVALID_OPERATION;
1132 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001133 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001134
1135 if (mInputStream != 0) {
1136 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1137 return INVALID_OPERATION;
1138 }
1139
1140 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1141 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001142 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001143
1144 mInputStream = newStream;
1145
1146 *id = mNextStreamId++;
1147
1148 // Continue captures if active at start
1149 if (wasActive) {
1150 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001151 // Reuse current operating mode for new stream config
1152 res = configureStreamsLocked(mOperatingMode);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001153 if (res != OK) {
1154 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1155 __FUNCTION__, mNextStreamId, strerror(-res), res);
1156 return res;
1157 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001158 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001159 }
1160
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001161 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001162 return OK;
1163}
1164
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001165status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001166 uint32_t width, uint32_t height, int format,
1167 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001168 int streamSetId, bool isShared, uint32_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001169 ATRACE_CALL();
1170
1171 if (consumer == nullptr) {
1172 ALOGE("%s: consumer must not be null", __FUNCTION__);
1173 return BAD_VALUE;
1174 }
1175
1176 std::vector<sp<Surface>> consumers;
1177 consumers.push_back(consumer);
1178
1179 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001180 format, dataSpace, rotation, id, streamSetId, isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001181}
1182
1183status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1184 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1185 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wang758c2152017-01-10 18:26:18 -08001186 int streamSetId, bool isShared, uint32_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001187 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001188 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001190 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang758c2152017-01-10 18:26:18 -08001191 " consumer usage 0x%x, isShared %d", mId.string(), mNextStreamId, width, height, format,
1192 dataSpace, rotation, consumerUsage, isShared);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 status_t res;
1195 bool wasActive = false;
1196
1197 switch (mStatus) {
1198 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001199 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 return INVALID_OPERATION;
1201 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001202 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 case STATUS_UNCONFIGURED:
1205 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 // OK
1207 break;
1208 case STATUS_ACTIVE:
1209 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 res = internalPauseAndWaitLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 return res;
1214 }
1215 wasActive = true;
1216 break;
1217 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
1220 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222
1223 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001224
Shuzhen Wang0129d522016-10-30 22:43:41 -07001225 if (consumers.size() == 0 && !hasDeferredConsumer) {
1226 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1227 return BAD_VALUE;
1228 }
Zhijun He5d677d12016-05-29 16:52:39 -07001229
Shuzhen Wang0129d522016-10-30 22:43:41 -07001230 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001231 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1232 return BAD_VALUE;
1233 }
1234
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001236 ssize_t blobBufferSize;
1237 if (dataSpace != HAL_DATASPACE_DEPTH) {
1238 blobBufferSize = getJpegBufferSize(width, height);
1239 if (blobBufferSize <= 0) {
1240 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1241 return BAD_VALUE;
1242 }
1243 } else {
1244 blobBufferSize = getPointCloudBufferSize();
1245 if (blobBufferSize <= 0) {
1246 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1247 return BAD_VALUE;
1248 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001249 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001250 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001251 width, height, blobBufferSize, format, dataSpace, rotation,
1252 mTimestampOffset, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001253 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1254 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1255 if (rawOpaqueBufferSize <= 0) {
1256 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1257 return BAD_VALUE;
1258 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001259 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001260 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1261 mTimestampOffset, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001262 } else if (isShared) {
1263 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1264 width, height, format, consumerUsage, dataSpace, rotation,
1265 mTimestampOffset, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001266 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001267 newStream = new Camera3OutputStream(mNextStreamId,
1268 width, height, format, consumerUsage, dataSpace, rotation,
1269 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001271 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001272 width, height, format, dataSpace, rotation,
1273 mTimestampOffset, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276
Emilian Peev08dd2452017-04-06 16:55:14 +01001277 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001278
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001279 res = mOutputStreams.add(mNextStreamId, newStream);
1280 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001281 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 return res;
1283 }
1284
1285 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001286 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287
1288 // Continue captures if active at start
1289 if (wasActive) {
1290 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001291 // Reuse current operating mode for new stream config
1292 res = configureStreamsLocked(mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001294 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1295 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 return res;
1297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001298 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001300 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001302}
1303
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001304status_t Camera3Device::getStreamInfo(int id,
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001305 uint32_t *width, uint32_t *height,
1306 uint32_t *format, android_dataspace *dataSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001307 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001308 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001310
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001311 switch (mStatus) {
1312 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001313 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001314 return INVALID_OPERATION;
1315 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001316 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001318 case STATUS_UNCONFIGURED:
1319 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001320 case STATUS_ACTIVE:
1321 // OK
1322 break;
1323 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001324 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001325 return INVALID_OPERATION;
1326 }
1327
1328 ssize_t idx = mOutputStreams.indexOfKey(id);
1329 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001330 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331 return idx;
1332 }
1333
1334 if (width) *width = mOutputStreams[idx]->getWidth();
1335 if (height) *height = mOutputStreams[idx]->getHeight();
1336 if (format) *format = mOutputStreams[idx]->getFormat();
Eino-Ville Talvalad46a6b92015-05-14 17:26:24 -07001337 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001338 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001339}
1340
1341status_t Camera3Device::setStreamTransform(int id,
1342 int transform) {
1343 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001344 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 switch (mStatus) {
1348 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001349 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350 return INVALID_OPERATION;
1351 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001352 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001354 case STATUS_UNCONFIGURED:
1355 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 case STATUS_ACTIVE:
1357 // OK
1358 break;
1359 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001360 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001361 return INVALID_OPERATION;
1362 }
1363
1364 ssize_t idx = mOutputStreams.indexOfKey(id);
1365 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Stream %d does not exist",
1367 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return BAD_VALUE;
1369 }
1370
1371 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001372}
1373
1374status_t Camera3Device::deleteStream(int id) {
1375 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001376 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 Mutex::Autolock l(mLock);
1378 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001379
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001380 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 // CameraDevice semantics require device to already be idle before
1383 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001384 if (mStatus == STATUS_ACTIVE) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001385 ALOGV("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001386 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 }
1388
Igor Murashkin2fba5842013-04-22 14:03:54 -07001389 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001390 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 if (mInputStream != NULL && id == mInputStream->getId()) {
1392 deletedStream = mInputStream;
1393 mInputStream.clear();
1394 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001395 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001396 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 return BAD_VALUE;
1398 }
Zhijun He5f446352014-01-22 09:49:33 -08001399 }
1400
1401 // Delete output stream or the output part of a bi-directional stream.
1402 if (outputStreamIdx != NAME_NOT_FOUND) {
1403 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 mOutputStreams.removeItem(id);
1405 }
1406
1407 // Free up the stream endpoint so that it can be used by some other stream
1408 res = deletedStream->disconnect();
1409 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 // fall through since we want to still list the stream as deleted.
1412 }
1413 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001414 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415
1416 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001417}
1418
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08001419status_t Camera3Device::configureStreams(int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001420 ATRACE_CALL();
1421 ALOGV("%s: E", __FUNCTION__);
1422
1423 Mutex::Autolock il(mInterfaceLock);
1424 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001425
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001426 return configureStreamsLocked(operatingMode);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001427}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001428
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001429status_t Camera3Device::getInputBufferProducer(
1430 sp<IGraphicBufferProducer> *producer) {
1431 Mutex::Autolock il(mInterfaceLock);
1432 Mutex::Autolock l(mLock);
1433
1434 if (producer == NULL) {
1435 return BAD_VALUE;
1436 } else if (mInputStream == NULL) {
1437 return INVALID_OPERATION;
1438 }
1439
1440 return mInputStream->getInputBufferProducer(producer);
1441}
1442
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001443status_t Camera3Device::createDefaultRequest(int templateId,
1444 CameraMetadata *request) {
1445 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001446 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001447
1448 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1449 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1450 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1451 return BAD_VALUE;
1452 }
1453
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001454 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 Mutex::Autolock l(mLock);
1456
1457 switch (mStatus) {
1458 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 return INVALID_OPERATION;
1461 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001462 CLOGE("Device is not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001464 case STATUS_UNCONFIGURED:
1465 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 case STATUS_ACTIVE:
1467 // OK
1468 break;
1469 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001470 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 return INVALID_OPERATION;
1472 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001473
Zhijun Hea1530f12014-09-14 12:44:20 -07001474 if (!mRequestTemplateCache[templateId].isEmpty()) {
1475 *request = mRequestTemplateCache[templateId];
1476 return OK;
1477 }
1478
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001479 camera_metadata_t *rawRequest;
1480 status_t res = mInterface->constructDefaultRequestSettings(
1481 (camera3_request_template_t) templateId, &rawRequest);
1482 if (res == BAD_VALUE) {
Yin-Chia Yeh0336d362015-04-14 12:34:22 -07001483 ALOGI("%s: template %d is not supported on this camera device",
1484 __FUNCTION__, templateId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001485 return res;
1486 } else if (res != OK) {
1487 CLOGE("Unable to construct request template %d: %s (%d)",
1488 templateId, strerror(-res), res);
1489 return res;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 }
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001491
Emilian Peev71c73a22017-03-21 16:35:51 +00001492 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001493 mRequestTemplateCache[templateId].acquire(rawRequest);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494
Yin-Chia Yeh4c060992016-04-11 17:40:12 -07001495 *request = mRequestTemplateCache[templateId];
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001496 return OK;
1497}
1498
1499status_t Camera3Device::waitUntilDrained() {
1500 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001503
Zhijun He69a37482014-03-23 18:44:49 -07001504 return waitUntilDrainedLocked();
1505}
1506
1507status_t Camera3Device::waitUntilDrainedLocked() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 switch (mStatus) {
1509 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001510 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 ALOGV("%s: Already idle", __FUNCTION__);
1512 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 case STATUS_CONFIGURED:
1514 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 case STATUS_ERROR:
1516 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001517 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 break;
1519 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return INVALID_OPERATION;
1522 }
1523
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001524 ALOGV("%s: Camera %s: Waiting until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001526 if (res != OK) {
1527 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1528 res);
1529 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001530 return res;
1531}
1532
Ruben Brunk183f0562015-08-12 12:55:02 -07001533
1534void Camera3Device::internalUpdateStatusLocked(Status status) {
1535 mStatus = status;
1536 mRecentStatusUpdates.add(mStatus);
1537 mStatusChanged.broadcast();
1538}
1539
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540// Pause to reconfigure
1541status_t Camera3Device::internalPauseAndWaitLocked() {
1542 mRequestThread->setPaused(true);
1543 mPauseStateNotify = true;
1544
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001545 ALOGV("%s: Camera %s: Internal wait until idle", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1547 if (res != OK) {
1548 SET_ERR_L("Can't idle device in %f seconds!",
1549 kShutdownTimeout/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 }
1551
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 return res;
1553}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555// Resume after internalPauseAndWaitLocked
1556status_t Camera3Device::internalResumeLocked() {
1557 status_t res;
1558
1559 mRequestThread->setPaused(false);
1560
1561 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1562 if (res != OK) {
1563 SET_ERR_L("Can't transition to active in %f seconds!",
1564 kActiveTimeout/1e9);
1565 }
1566 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568}
1569
Ruben Brunk183f0562015-08-12 12:55:02 -07001570status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001572
1573 size_t startIndex = 0;
1574 if (mStatusWaiters == 0) {
1575 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1576 // this status list
1577 mRecentStatusUpdates.clear();
1578 } else {
1579 // If other threads are waiting on updates to this status list, set the position of the
1580 // first element that this list will check rather than clearing the list.
1581 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 }
1583
Ruben Brunk183f0562015-08-12 12:55:02 -07001584 mStatusWaiters++;
1585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 bool stateSeen = false;
1587 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001588 if (active == (mStatus == STATUS_ACTIVE)) {
1589 // Desired state is current
1590 break;
1591 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592
1593 res = mStatusChanged.waitRelative(mLock, timeout);
1594 if (res != OK) break;
1595
Ruben Brunk183f0562015-08-12 12:55:02 -07001596 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1597 // transitions.
1598 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1599 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1600 __FUNCTION__);
1601
1602 // Encountered desired state since we began waiting
1603 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1605 stateSeen = true;
1606 break;
1607 }
1608 }
1609 } while (!stateSeen);
1610
Ruben Brunk183f0562015-08-12 12:55:02 -07001611 mStatusWaiters--;
1612
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 return res;
1614}
1615
1616
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001617status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001619 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001620
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001621 if (listener != NULL && mListener != NULL) {
1622 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1623 }
1624 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001625 mRequestThread->setNotificationListener(listener);
1626 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001627
1628 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001629}
1630
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001631bool Camera3Device::willNotify3A() {
1632 return false;
1633}
1634
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001635status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001636 status_t res;
1637 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001638
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001639 while (mResultQueue.empty()) {
1640 res = mResultSignal.waitRelative(mOutputLock, timeout);
1641 if (res == TIMED_OUT) {
1642 return res;
1643 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001644 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1645 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001646 return res;
1647 }
1648 }
1649 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001650}
1651
Jianing Weicb0652e2014-03-12 18:29:36 -07001652status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001654 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001655
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001656 if (mResultQueue.empty()) {
1657 return NOT_ENOUGH_DATA;
1658 }
1659
Jianing Weicb0652e2014-03-12 18:29:36 -07001660 if (frame == NULL) {
1661 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1662 return BAD_VALUE;
1663 }
1664
1665 CaptureResult &result = *(mResultQueue.begin());
1666 frame->mResultExtras = result.mResultExtras;
1667 frame->mMetadata.acquire(result.mMetadata);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001668 mResultQueue.erase(mResultQueue.begin());
1669
1670 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001671}
1672
1673status_t Camera3Device::triggerAutofocus(uint32_t id) {
1674 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001677 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1678 // Mix-in this trigger into the next request and only the next request.
1679 RequestTrigger trigger[] = {
1680 {
1681 ANDROID_CONTROL_AF_TRIGGER,
1682 ANDROID_CONTROL_AF_TRIGGER_START
1683 },
1684 {
1685 ANDROID_CONTROL_AF_TRIGGER_ID,
1686 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001687 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001688 };
1689
1690 return mRequestThread->queueTrigger(trigger,
1691 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692}
1693
1694status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1695 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001696 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001698 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1699 // Mix-in this trigger into the next request and only the next request.
1700 RequestTrigger trigger[] = {
1701 {
1702 ANDROID_CONTROL_AF_TRIGGER,
1703 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1704 },
1705 {
1706 ANDROID_CONTROL_AF_TRIGGER_ID,
1707 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001708 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001709 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001711 return mRequestThread->queueTrigger(trigger,
1712 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713}
1714
1715status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1716 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001717 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001719 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1720 // Mix-in this trigger into the next request and only the next request.
1721 RequestTrigger trigger[] = {
1722 {
1723 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1724 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1725 },
1726 {
1727 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1728 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001729 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001730 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001731
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001732 return mRequestThread->queueTrigger(trigger,
1733 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734}
1735
Jianing Weicb0652e2014-03-12 18:29:36 -07001736status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001737 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001738 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001739 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001740
Zhijun He7ef20392014-04-21 16:04:17 -07001741 {
1742 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001743 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07001744 }
1745
Emilian Peev08dd2452017-04-06 16:55:14 +01001746 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001747}
1748
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001749status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001750 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1751}
1752
1753status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001754 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001755 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001756 Mutex::Autolock il(mInterfaceLock);
1757 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001758
1759 sp<Camera3StreamInterface> stream;
1760 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1761 if (outputStreamIdx == NAME_NOT_FOUND) {
1762 CLOGE("Stream %d does not exist", streamId);
1763 return BAD_VALUE;
1764 }
1765
1766 stream = mOutputStreams.editValueAt(outputStreamIdx);
1767
1768 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001769 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001770 return BAD_VALUE;
1771 }
1772
1773 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001774 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001775 return BAD_VALUE;
1776 }
1777
Ruben Brunkc78ac262015-08-13 17:58:46 -07001778 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001779}
1780
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001781status_t Camera3Device::tearDown(int streamId) {
1782 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001783 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001784 Mutex::Autolock il(mInterfaceLock);
1785 Mutex::Autolock l(mLock);
1786
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001787 sp<Camera3StreamInterface> stream;
1788 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1789 if (outputStreamIdx == NAME_NOT_FOUND) {
1790 CLOGE("Stream %d does not exist", streamId);
1791 return BAD_VALUE;
1792 }
1793
1794 stream = mOutputStreams.editValueAt(outputStreamIdx);
1795
1796 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1797 CLOGE("Stream %d is a target of a in-progress request", streamId);
1798 return BAD_VALUE;
1799 }
1800
1801 return stream->tearDown();
1802}
1803
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001804status_t Camera3Device::addBufferListenerForStream(int streamId,
1805 wp<Camera3StreamBufferListener> listener) {
1806 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001807 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001808 Mutex::Autolock il(mInterfaceLock);
1809 Mutex::Autolock l(mLock);
1810
1811 sp<Camera3StreamInterface> stream;
1812 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
1813 if (outputStreamIdx == NAME_NOT_FOUND) {
1814 CLOGE("Stream %d does not exist", streamId);
1815 return BAD_VALUE;
1816 }
1817
1818 stream = mOutputStreams.editValueAt(outputStreamIdx);
1819 stream->addBufferListener(listener);
1820
1821 return OK;
1822}
1823
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 * Methods called by subclasses
1826 */
1827
1828void Camera3Device::notifyStatus(bool idle) {
1829 {
1830 // Need mLock to safely update state and synchronize to current
1831 // state of methods in flight.
1832 Mutex::Autolock l(mLock);
1833 // We can get various system-idle notices from the status tracker
1834 // while starting up. Only care about them if we've actually sent
1835 // in some requests recently.
1836 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1837 return;
1838 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001839 ALOGV("%s: Camera %s: Now %s", __FUNCTION__, mId.string(),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001840 idle ? "idle" : "active");
Ruben Brunk183f0562015-08-12 12:55:02 -07001841 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842
1843 // Skip notifying listener if we're doing some user-transparent
1844 // state changes
1845 if (mPauseStateNotify) return;
1846 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001847
1848 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849 {
1850 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001851 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852 }
1853 if (idle && listener != NULL) {
1854 listener->notifyIdle();
1855 }
1856}
1857
Shuzhen Wang758c2152017-01-10 18:26:18 -08001858status_t Camera3Device::setConsumerSurfaces(int streamId,
1859 const std::vector<sp<Surface>>& consumers) {
Zhijun He5d677d12016-05-29 16:52:39 -07001860 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001861 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1862 __FUNCTION__, mId.string(), streamId);
Zhijun He5d677d12016-05-29 16:52:39 -07001863 Mutex::Autolock il(mInterfaceLock);
1864 Mutex::Autolock l(mLock);
1865
Shuzhen Wang758c2152017-01-10 18:26:18 -08001866 if (consumers.size() == 0) {
1867 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001868 return BAD_VALUE;
1869 }
1870
1871 ssize_t idx = mOutputStreams.indexOfKey(streamId);
1872 if (idx == NAME_NOT_FOUND) {
1873 CLOGE("Stream %d is unknown", streamId);
1874 return idx;
1875 }
1876 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08001877 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001878 if (res != OK) {
1879 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1880 return res;
1881 }
1882
Shuzhen Wang0129d522016-10-30 22:43:41 -07001883 if (stream->isConsumerConfigurationDeferred()) {
1884 if (!stream->isConfiguring()) {
1885 CLOGE("Stream %d was already fully configured.", streamId);
1886 return INVALID_OPERATION;
1887 }
Zhijun He5d677d12016-05-29 16:52:39 -07001888
Shuzhen Wang0129d522016-10-30 22:43:41 -07001889 res = stream->finishConfiguration();
1890 if (res != OK) {
1891 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1892 stream->getId(), strerror(-res), res);
1893 return res;
1894 }
Zhijun He5d677d12016-05-29 16:52:39 -07001895 }
1896
1897 return OK;
1898}
1899
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001900/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901 * Camera3Device private methods
1902 */
1903
1904sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Shuzhen Wang0129d522016-10-30 22:43:41 -07001905 const CameraMetadata &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001906 ATRACE_CALL();
1907 status_t res;
1908
1909 sp<CaptureRequest> newRequest = new CaptureRequest;
1910 newRequest->mSettings = request;
1911
1912 camera_metadata_entry_t inputStreams =
1913 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1914 if (inputStreams.count > 0) {
1915 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001916 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001917 CLOGE("Request references unknown input stream %d",
1918 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919 return NULL;
1920 }
1921 // Lazy completion of stream configuration (allocation/registration)
1922 // on first use
1923 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001924 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001925 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001926 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001928 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001929 return NULL;
1930 }
1931 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001932 // Check if stream is being prepared
1933 if (mInputStream->isPreparing()) {
1934 CLOGE("Request references an input stream that's being prepared!");
1935 return NULL;
1936 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001937
1938 newRequest->mInputStream = mInputStream;
1939 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1940 }
1941
1942 camera_metadata_entry_t streams =
1943 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1944 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001945 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001946 return NULL;
1947 }
1948
1949 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07001950 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001951 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001952 CLOGE("Request references unknown stream %d",
1953 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001954 return NULL;
1955 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07001956 sp<Camera3OutputStreamInterface> stream =
1957 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001958
Zhijun He5d677d12016-05-29 16:52:39 -07001959 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07001960 auto iter = surfaceMap.find(streams.data.i32[i]);
1961 if (iter != surfaceMap.end()) {
1962 const std::vector<size_t>& surfaces = iter->second;
1963 for (const auto& surface : surfaces) {
1964 if (stream->isConsumerConfigurationDeferred(surface)) {
1965 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
1966 "due to deferred consumer", stream->getId(), surface);
1967 return NULL;
1968 }
1969 }
1970 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07001971 }
1972
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001973 // Lazy completion of stream configuration (allocation/registration)
1974 // on first use
1975 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001976 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001977 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001978 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
1979 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980 return NULL;
1981 }
1982 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001983 // Check if stream is being prepared
1984 if (stream->isPreparing()) {
1985 CLOGE("Request references an output stream that's being prepared!");
1986 return NULL;
1987 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988
1989 newRequest->mOutputStreams.push(stream);
1990 }
1991 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001992 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993
1994 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001995}
1996
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001997bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
1998 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
1999 Size size = mSupportedOpaqueInputSizes[i];
2000 if (size.width == width && size.height == height) {
2001 return true;
2002 }
2003 }
2004
2005 return false;
2006}
2007
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002008void Camera3Device::cancelStreamsConfigurationLocked() {
2009 int res = OK;
2010 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2011 res = mInputStream->cancelConfiguration();
2012 if (res != OK) {
2013 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2014 mInputStream->getId(), strerror(-res), res);
2015 }
2016 }
2017
2018 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2019 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2020 if (outputStream->isConfiguring()) {
2021 res = outputStream->cancelConfiguration();
2022 if (res != OK) {
2023 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2024 outputStream->getId(), strerror(-res), res);
2025 }
2026 }
2027 }
2028
2029 // Return state to that at start of call, so that future configures
2030 // properly clean things up
2031 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2032 mNeedConfig = true;
2033}
2034
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002035status_t Camera3Device::configureStreamsLocked(int operatingMode) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002036 ATRACE_CALL();
2037 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002038
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002039 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002040 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041 return INVALID_OPERATION;
2042 }
2043
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002044 if (operatingMode < 0) {
2045 CLOGE("Invalid operating mode: %d", operatingMode);
2046 return BAD_VALUE;
2047 }
2048
2049 bool isConstrainedHighSpeed =
2050 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2051 operatingMode;
2052
2053 if (mOperatingMode != operatingMode) {
2054 mNeedConfig = true;
2055 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2056 mOperatingMode = operatingMode;
2057 }
2058
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002059 if (!mNeedConfig) {
2060 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2061 return OK;
2062 }
2063
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002064 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2065 // adding a dummy stream instead.
2066 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2067 if (mOutputStreams.size() == 0) {
2068 addDummyStreamLocked();
2069 } else {
2070 tryRemoveDummyStreamLocked();
2071 }
2072
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002074 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075
2076 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002077 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2079
2080 Vector<camera3_stream_t*> streams;
2081 streams.setCapacity(config.num_streams);
2082
2083 if (mInputStream != NULL) {
2084 camera3_stream_t *inputStream;
2085 inputStream = mInputStream->startConfiguration();
2086 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002087 CLOGE("Can't start input stream configuration");
2088 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002089 return INVALID_OPERATION;
2090 }
2091 streams.add(inputStream);
2092 }
2093
2094 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002095
2096 // Don't configure bidi streams twice, nor add them twice to the list
2097 if (mOutputStreams[i].get() ==
2098 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2099
2100 config.num_streams--;
2101 continue;
2102 }
2103
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 camera3_stream_t *outputStream;
2105 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2106 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002107 CLOGE("Can't start output stream configuration");
2108 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 return INVALID_OPERATION;
2110 }
2111 streams.add(outputStream);
2112 }
2113
2114 config.streams = streams.editArray();
2115
2116 // Do the HAL configuration; will potentially touch stream
2117 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002118
2119 res = mInterface->configureStreams(&config);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002121 if (res == BAD_VALUE) {
2122 // HAL rejected this set of streams as unsupported, clean up config
2123 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002124 CLOGE("Set of requested inputs/outputs not supported by HAL");
2125 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002126 return BAD_VALUE;
2127 } else if (res != OK) {
2128 // Some other kind of error from configure_streams - this is not
2129 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002130 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2131 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 return res;
2133 }
2134
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002135 // Finish all stream configuration immediately.
2136 // TODO: Try to relax this later back to lazy completion, which should be
2137 // faster
2138
Igor Murashkin073f8572013-05-02 14:59:28 -07002139 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002140 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002141 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002142 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002143 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002144 cancelStreamsConfigurationLocked();
2145 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002146 }
2147 }
2148
2149 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002150 sp<Camera3OutputStreamInterface> outputStream =
2151 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002152 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002153 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002154 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002155 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002156 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002157 cancelStreamsConfigurationLocked();
2158 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002159 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002160 }
2161 }
2162
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002163 // Request thread needs to know to avoid using repeat-last-settings protocol
2164 // across configure_streams() calls
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002165 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166
Zhijun He90f7c372016-08-16 16:19:43 -07002167 char value[PROPERTY_VALUE_MAX];
2168 property_get("camera.fifo.disable", value, "0");
2169 int32_t disableFifo = atoi(value);
2170 if (disableFifo != 1) {
2171 // Boost priority of request thread to SCHED_FIFO.
2172 pid_t requestThreadTid = mRequestThread->getTid();
2173 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002174 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002175 if (res != OK) {
2176 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2177 strerror(-res), res);
2178 } else {
2179 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2180 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002181 }
2182
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183 // Update device state
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002184
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002185 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002186
Ruben Brunk183f0562015-08-12 12:55:02 -07002187 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2188 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002190 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002191
Zhijun He0a210512014-07-24 13:45:15 -07002192 // tear down the deleted streams after configure streams.
2193 mDeletedStreams.clear();
2194
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002196}
2197
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002198status_t Camera3Device::addDummyStreamLocked() {
2199 ATRACE_CALL();
2200 status_t res;
2201
2202 if (mDummyStreamId != NO_STREAM) {
2203 // Should never be adding a second dummy stream when one is already
2204 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002205 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2206 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002207 return INVALID_OPERATION;
2208 }
2209
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002210 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002211
2212 sp<Camera3OutputStreamInterface> dummyStream =
2213 new Camera3DummyStream(mNextStreamId);
2214
2215 res = mOutputStreams.add(mNextStreamId, dummyStream);
2216 if (res < 0) {
2217 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2218 return res;
2219 }
2220
2221 mDummyStreamId = mNextStreamId;
2222 mNextStreamId++;
2223
2224 return OK;
2225}
2226
2227status_t Camera3Device::tryRemoveDummyStreamLocked() {
2228 ATRACE_CALL();
2229 status_t res;
2230
2231 if (mDummyStreamId == NO_STREAM) return OK;
2232 if (mOutputStreams.size() == 1) return OK;
2233
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002234 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002235
2236 // Ok, have a dummy stream and there's at least one other output stream,
2237 // so remove the dummy
2238
2239 sp<Camera3StreamInterface> deletedStream;
2240 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2241 if (outputStreamIdx == NAME_NOT_FOUND) {
2242 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2243 return INVALID_OPERATION;
2244 }
2245
2246 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2247 mOutputStreams.removeItemsAt(outputStreamIdx);
2248
2249 // Free up the stream endpoint so that it can be used by some other stream
2250 res = deletedStream->disconnect();
2251 if (res != OK) {
2252 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2253 // fall through since we want to still list the stream as deleted.
2254 }
2255 mDeletedStreams.add(deletedStream);
2256 mDummyStreamId = NO_STREAM;
2257
2258 return res;
2259}
2260
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002261void Camera3Device::setErrorState(const char *fmt, ...) {
2262 Mutex::Autolock l(mLock);
2263 va_list args;
2264 va_start(args, fmt);
2265
2266 setErrorStateLockedV(fmt, args);
2267
2268 va_end(args);
2269}
2270
2271void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2272 Mutex::Autolock l(mLock);
2273 setErrorStateLockedV(fmt, args);
2274}
2275
2276void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2277 va_list args;
2278 va_start(args, fmt);
2279
2280 setErrorStateLockedV(fmt, args);
2281
2282 va_end(args);
2283}
2284
2285void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002286 // Print out all error messages to log
2287 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002288 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002289
2290 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002291 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002292
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002293 mErrorCause = errorCause;
2294
2295 mRequestThread->setPaused(true);
Ruben Brunk183f0562015-08-12 12:55:02 -07002296 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002297
2298 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002299 sp<NotificationListener> listener = mListener.promote();
2300 if (listener != NULL) {
2301 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002302 CaptureResultExtras());
2303 }
2304
2305 // Save stack trace. View by dumping it later.
2306 CameraTraces::saveTrace();
2307 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002308}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002309
2310/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002311 * In-flight request management
2312 */
2313
Jianing Weicb0652e2014-03-12 18:29:36 -07002314status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002315 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002316 bool hasAppCallback) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002317 ATRACE_CALL();
2318 Mutex::Autolock l(mInFlightLock);
2319
2320 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002321 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002322 hasAppCallback));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002323 if (res < 0) return res;
2324
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002325 if (mInFlightMap.size() == 1) {
2326 mStatusTracker->markComponentActive(mInFlightStatusId);
2327 }
2328
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002329 return OK;
2330}
2331
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002332void Camera3Device::returnOutputBuffers(
2333 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2334 nsecs_t timestamp) {
2335 for (size_t i = 0; i < numBuffers; i++)
2336 {
2337 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2338 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2339 // Note: stream may be deallocated at this point, if this buffer was
2340 // the last reference to it.
2341 if (res != OK) {
2342 ALOGE("Can't return buffer to its stream: %s (%d)",
2343 strerror(-res), res);
2344 }
2345 }
2346}
2347
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002348void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2349 mInFlightMap.removeItemsAt(idx, 1);
2350
2351 // Indicate idle inFlightMap to the status tracker
2352 if (mInFlightMap.size() == 0) {
2353 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2354 }
2355}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002356
2357void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2358
2359 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2360 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2361
2362 nsecs_t sensorTimestamp = request.sensorTimestamp;
2363 nsecs_t shutterTimestamp = request.shutterTimestamp;
2364
2365 // Check if it's okay to remove the request from InFlightMap:
2366 // In the case of a successful request:
2367 // all input and output buffers, all result metadata, shutter callback
2368 // arrived.
2369 // In the case of a unsuccessful request:
2370 // all input and output buffers arrived.
2371 if (request.numBuffersLeft == 0 &&
2372 (request.requestStatus != OK ||
2373 (request.haveResultMetadata && shutterTimestamp != 0))) {
2374 ATRACE_ASYNC_END("frame capture", frameNumber);
2375
Shuzhen Wang403044a2017-02-26 23:29:04 -08002376 // Sanity check - if sensor timestamp matches shutter timestamp in the
2377 // case of request having callback.
2378 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002379 sensorTimestamp != shutterTimestamp) {
2380 SET_ERR("sensor timestamp (%" PRId64
2381 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2382 sensorTimestamp, frameNumber, shutterTimestamp);
2383 }
2384
2385 // for an unsuccessful request, it may have pending output buffers to
2386 // return.
2387 assert(request.requestStatus != OK ||
2388 request.pendingOutputBuffers.size() == 0);
2389 returnOutputBuffers(request.pendingOutputBuffers.array(),
2390 request.pendingOutputBuffers.size(), 0);
2391
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002392 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002393 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2394 }
2395
2396 // Sanity check - if we have too many in-flight frames, something has
2397 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002398 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002399 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002400 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2401 kInFlightWarnLimitHighSpeed) {
2402 CLOGE("In-flight list too large for high speed configuration: %zu",
2403 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002404 }
2405}
2406
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002407void Camera3Device::insertResultLocked(CaptureResult *result,
2408 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002409 if (result == nullptr) return;
2410
Emilian Peev71c73a22017-03-21 16:35:51 +00002411 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2412 result->mMetadata.getAndLock());
2413 set_camera_metadata_vendor_id(meta, mVendorTagId);
2414 result->mMetadata.unlock(meta);
2415
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002416 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2417 (int32_t*)&frameNumber, 1) != OK) {
2418 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2419 return;
2420 }
2421
2422 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2423 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2424 return;
2425 }
2426
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002427 // Valid result, insert into queue
2428 List<CaptureResult>::iterator queuedResult =
2429 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2430 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2431 ", burstId = %" PRId32, __FUNCTION__,
2432 queuedResult->mResultExtras.requestId,
2433 queuedResult->mResultExtras.frameNumber,
2434 queuedResult->mResultExtras.burstId);
2435
2436 mResultSignal.signal();
2437}
2438
2439
2440void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002441 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002442 Mutex::Autolock l(mOutputLock);
2443
2444 CaptureResult captureResult;
2445 captureResult.mResultExtras = resultExtras;
2446 captureResult.mMetadata = partialResult;
2447
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002448 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002449}
2450
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002451
2452void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2453 CaptureResultExtras &resultExtras,
2454 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002455 uint32_t frameNumber,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002456 bool reprocess) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002457 if (pendingMetadata.isEmpty())
2458 return;
2459
2460 Mutex::Autolock l(mOutputLock);
2461
2462 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002463 if (reprocess) {
2464 if (frameNumber < mNextReprocessResultFrameNumber) {
2465 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002466 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002467 frameNumber, mNextReprocessResultFrameNumber);
2468 return;
2469 }
2470 mNextReprocessResultFrameNumber = frameNumber + 1;
2471 } else {
2472 if (frameNumber < mNextResultFrameNumber) {
2473 SET_ERR("Out-of-order capture result metadata submitted! "
2474 "(got frame number %d, expecting %d)",
2475 frameNumber, mNextResultFrameNumber);
2476 return;
2477 }
2478 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002479 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002480
2481 CaptureResult captureResult;
2482 captureResult.mResultExtras = resultExtras;
2483 captureResult.mMetadata = pendingMetadata;
2484
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002485 // Append any previous partials to form a complete result
2486 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2487 captureResult.mMetadata.append(collectedPartialResult);
2488 }
2489
2490 captureResult.mMetadata.sort();
2491
2492 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002493 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2494 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002495 SET_ERR("No timestamp provided by HAL for frame %d!",
2496 frameNumber);
2497 return;
2498 }
2499
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002500 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
2501 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
2502
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002503 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002504}
2505
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002506/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002507 * Camera HAL device callback methods
2508 */
2509
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002510void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002511 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002512
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002513 status_t res;
2514
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002515 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07002516 if (result->result == NULL && result->num_output_buffers == 0 &&
2517 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002518 SET_ERR("No result data provided by HAL for frame %d",
2519 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002520 return;
2521 }
Zhijun He204e3292014-07-14 17:09:23 -07002522
Zhijun He204e3292014-07-14 17:09:23 -07002523 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07002524 result->result != NULL &&
2525 result->partial_result != 1) {
2526 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
2527 " if partial result is not supported",
2528 frameNumber, result->partial_result);
2529 return;
2530 }
2531
2532 bool isPartialResult = false;
2533 CameraMetadata collectedPartialResult;
Jianing Weicb0652e2014-03-12 18:29:36 -07002534 CaptureResultExtras resultExtras;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002535 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002536
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002537 // Get shutter timestamp and resultExtras from list of in-flight requests,
2538 // where it was added by the shutter notification for this frame. If the
2539 // shutter timestamp isn't received yet, append the output buffers to the
2540 // in-flight request and they will be returned when the shutter timestamp
2541 // arrives. Update the in-flight status and remove the in-flight entry if
2542 // all result data and shutter timestamp have been received.
2543 nsecs_t shutterTimestamp = 0;
2544
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002545 {
2546 Mutex::Autolock l(mInFlightLock);
2547 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
2548 if (idx == NAME_NOT_FOUND) {
2549 SET_ERR("Unknown frame number for capture result: %d",
2550 frameNumber);
2551 return;
2552 }
2553 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002554 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
2555 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08002556 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002557 __FUNCTION__, request.resultExtras.requestId,
2558 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08002559 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002560 // Always update the partial count to the latest one if it's not 0
2561 // (buffers only). When framework aggregates adjacent partial results
2562 // into one, the latest partial count will be used.
2563 if (result->partial_result != 0)
2564 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002565
2566 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07002567 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01002568 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
2569 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
2570 " the range of [1, %d] when metadata is included in the result",
2571 frameNumber, result->partial_result, mNumPartialResults);
2572 return;
2573 }
2574 isPartialResult = (result->partial_result < mNumPartialResults);
2575 if (isPartialResult) {
2576 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07002577 }
2578
Shuzhen Wang4a472662017-02-26 23:29:04 -08002579 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002580 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002581 sendPartialCaptureResult(result->result, request.resultExtras,
2582 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002583 }
2584 }
2585
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002586 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002587 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07002588
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002589 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07002590 if (result->result != NULL && !isPartialResult) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002591 if (request.haveResultMetadata) {
2592 SET_ERR("Called multiple times with metadata for frame %d",
2593 frameNumber);
2594 return;
2595 }
Zhijun He204e3292014-07-14 17:09:23 -07002596 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002597 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07002598 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002599 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002600 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002601 request.haveResultMetadata = true;
2602 }
2603
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002604 uint32_t numBuffersReturned = result->num_output_buffers;
2605 if (result->input_buffer != NULL) {
2606 if (hasInputBufferInRequest) {
2607 numBuffersReturned += 1;
2608 } else {
2609 ALOGW("%s: Input buffer should be NULL if there is no input"
2610 " buffer sent in the request",
2611 __FUNCTION__);
2612 }
2613 }
2614 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002615 if (request.numBuffersLeft < 0) {
2616 SET_ERR("Too many buffers returned for frame %d",
2617 frameNumber);
2618 return;
2619 }
2620
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002621 camera_metadata_ro_entry_t entry;
2622 res = find_camera_metadata_ro_entry(result->result,
2623 ANDROID_SENSOR_TIMESTAMP, &entry);
2624 if (res == OK && entry.count == 1) {
2625 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002626 }
2627
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002628 // If shutter event isn't received yet, append the output buffers to
2629 // the in-flight request. Otherwise, return the output buffers to
2630 // streams.
2631 if (shutterTimestamp == 0) {
2632 request.pendingOutputBuffers.appendArray(result->output_buffers,
2633 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07002634 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002635 returnOutputBuffers(result->output_buffers,
2636 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07002637 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002638
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002639 if (result->result != NULL && !isPartialResult) {
2640 if (shutterTimestamp == 0) {
2641 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002642 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang4a472662017-02-26 23:29:04 -08002643 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002644 CameraMetadata metadata;
2645 metadata = result->result;
2646 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002647 collectedPartialResult, frameNumber,
2648 hasInputBufferInRequest);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002649 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07002650 }
2651
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002652 removeInFlightRequestIfReadyLocked(idx);
2653 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002654
Zhijun Hef0d962a2014-06-30 10:24:11 -07002655 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07002656 if (hasInputBufferInRequest) {
2657 Camera3Stream *stream =
2658 Camera3Stream::cast(result->input_buffer->stream);
2659 res = stream->returnInputBuffer(*(result->input_buffer));
2660 // Note: stream may be deallocated at this point, if this buffer was the
2661 // last reference to it.
2662 if (res != OK) {
2663 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2664 " its stream:%s (%d)", __FUNCTION__,
2665 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07002666 }
2667 } else {
2668 ALOGW("%s: Input buffer should be NULL if there is no input"
2669 " buffer sent in the request, skipping input buffer return.",
2670 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07002671 }
2672 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002673}
2674
2675void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07002676 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002677 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002678 {
2679 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002680 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002681 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002682
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002683 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002684 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002685 return;
2686 }
2687
2688 switch (msg->type) {
2689 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002690 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002691 break;
2692 }
2693 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002694 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002695 break;
2696 }
2697 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002698 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002699 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002700 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002701}
2702
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002703void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002704 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002705
2706 // Map camera HAL error codes to ICameraDeviceCallback error codes
2707 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002708 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002709 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002710 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002711 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002712 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002713 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002714 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002715 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002716 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002717 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002718 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002719 };
2720
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002721 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002722 ((msg.error_code >= 0) &&
2723 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2724 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002725 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002726
2727 int streamId = 0;
2728 if (msg.error_stream != NULL) {
2729 Camera3Stream *stream =
2730 Camera3Stream::cast(msg.error_stream);
2731 streamId = stream->getId();
2732 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002733 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
2734 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002735 streamId, msg.error_code);
2736
2737 CaptureResultExtras resultExtras;
2738 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002739 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002740 // SET_ERR calls notifyError
2741 SET_ERR("Camera HAL reported serious device error");
2742 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002743 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2744 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2745 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002746 {
2747 Mutex::Autolock l(mInFlightLock);
2748 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2749 if (idx >= 0) {
2750 InFlightRequest &r = mInFlightMap.editValueAt(idx);
2751 r.requestStatus = msg.error_code;
2752 resultExtras = r.resultExtras;
Emilian Peevba0fac32017-03-30 09:05:34 +01002753 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
2754 errorCode) {
2755 // In case of missing result check whether the buffers
2756 // returned. If they returned, then remove inflight
2757 // request.
2758 removeInFlightRequestIfReadyLocked(idx);
2759 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002760 } else {
2761 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002762 ALOGE("Camera %s: %s: cannot find in-flight request on "
2763 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002764 resultExtras.frameNumber);
2765 }
2766 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08002767 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002768 if (listener != NULL) {
2769 listener->notifyError(errorCode, resultExtras);
2770 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002771 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002772 }
2773 break;
2774 default:
2775 // SET_ERR calls notifyError
2776 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2777 break;
2778 }
2779}
2780
2781void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002782 sp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002783 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002784
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002785 // Set timestamp for the request in the in-flight tracking
2786 // and get the request ID to send upstream
2787 {
2788 Mutex::Autolock l(mInFlightLock);
2789 idx = mInFlightMap.indexOfKey(msg.frame_number);
2790 if (idx >= 0) {
2791 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002792
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07002793 // Verify ordering of shutter notifications
2794 {
2795 Mutex::Autolock l(mOutputLock);
2796 // TODO: need to track errors for tighter bounds on expected frame number.
2797 if (r.hasInputBuffer) {
2798 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
2799 SET_ERR("Shutter notification out-of-order. Expected "
2800 "notification for frame %d, got frame %d",
2801 mNextReprocessShutterFrameNumber, msg.frame_number);
2802 return;
2803 }
2804 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
2805 } else {
2806 if (msg.frame_number < mNextShutterFrameNumber) {
2807 SET_ERR("Shutter notification out-of-order. Expected "
2808 "notification for frame %d, got frame %d",
2809 mNextShutterFrameNumber, msg.frame_number);
2810 return;
2811 }
2812 mNextShutterFrameNumber = msg.frame_number + 1;
2813 }
2814 }
2815
Shuzhen Wang4a472662017-02-26 23:29:04 -08002816 r.shutterTimestamp = msg.timestamp;
2817 if (r.hasCallback) {
2818 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002819 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002820 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08002821 // Call listener, if any
2822 if (listener != NULL) {
2823 listener->notifyShutter(r.resultExtras, msg.timestamp);
2824 }
2825 // send pending result and buffers
2826 sendCaptureResult(r.pendingMetadata, r.resultExtras,
2827 r.collectedPartialResult, msg.frame_number,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002828 r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002829 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002830 returnOutputBuffers(r.pendingOutputBuffers.array(),
2831 r.pendingOutputBuffers.size(), r.shutterTimestamp);
2832 r.pendingOutputBuffers.clear();
2833
2834 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835 }
2836 }
2837 if (idx < 0) {
2838 SET_ERR("Shutter notification for non-existent frame number %d",
2839 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 }
2841}
2842
2843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002844CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002845 ALOGV("%s", __FUNCTION__);
2846
Igor Murashkin1e479c02013-09-06 16:55:14 -07002847 CameraMetadata retVal;
2848
2849 if (mRequestThread != NULL) {
2850 retVal = mRequestThread->getLatestRequest();
2851 }
2852
Igor Murashkin1e479c02013-09-06 16:55:14 -07002853 return retVal;
2854}
2855
Jianing Weicb0652e2014-03-12 18:29:36 -07002856
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002857void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2858 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
2859 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
2860}
2861
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002862/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002863 * HalInterface inner class methods
2864 */
2865
Yifan Hongf79b5542017-04-11 14:44:25 -07002866Camera3Device::HalInterface::HalInterface(
2867 sp<ICameraDeviceSession> &session,
2868 std::shared_ptr<RequestMetadataQueue> queue) :
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002869 mHal3Device(nullptr),
Yifan Hongf79b5542017-04-11 14:44:25 -07002870 mHidlSession(session),
2871 mRequestMetadataQueue(queue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002872
2873Camera3Device::HalInterface::HalInterface() :
2874 mHal3Device(nullptr) {}
2875
2876Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002877 mHal3Device(other.mHal3Device),
Yifan Hongf79b5542017-04-11 14:44:25 -07002878 mHidlSession(other.mHidlSession),
2879 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002880
2881bool Camera3Device::HalInterface::valid() {
2882 return (mHal3Device != nullptr) || (mHidlSession != nullptr);
2883}
2884
2885void Camera3Device::HalInterface::clear() {
2886 mHal3Device = nullptr;
2887 mHidlSession.clear();
2888}
2889
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08002890bool Camera3Device::HalInterface::supportBatchRequest() {
2891 return mHidlSession != nullptr;
2892}
2893
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002894status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2895 camera3_request_template_t templateId,
2896 /*out*/ camera_metadata_t **requestTemplate) {
2897 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2898 if (!valid()) return INVALID_OPERATION;
2899 status_t res = OK;
2900
2901 if (mHal3Device != nullptr) {
2902 const camera_metadata *r;
2903 r = mHal3Device->ops->construct_default_request_settings(
2904 mHal3Device, templateId);
2905 if (r == nullptr) return BAD_VALUE;
2906 *requestTemplate = clone_camera_metadata(r);
2907 if (requestTemplate == nullptr) {
2908 ALOGE("%s: Unable to clone camera metadata received from HAL",
2909 __FUNCTION__);
2910 return INVALID_OPERATION;
2911 }
2912 } else {
2913 common::V1_0::Status status;
2914 RequestTemplate id;
2915 switch (templateId) {
2916 case CAMERA3_TEMPLATE_PREVIEW:
2917 id = RequestTemplate::PREVIEW;
2918 break;
2919 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2920 id = RequestTemplate::STILL_CAPTURE;
2921 break;
2922 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2923 id = RequestTemplate::VIDEO_RECORD;
2924 break;
2925 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2926 id = RequestTemplate::VIDEO_SNAPSHOT;
2927 break;
2928 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2929 id = RequestTemplate::ZERO_SHUTTER_LAG;
2930 break;
2931 case CAMERA3_TEMPLATE_MANUAL:
2932 id = RequestTemplate::MANUAL;
2933 break;
2934 default:
2935 // Unknown template ID
2936 return BAD_VALUE;
2937 }
2938 mHidlSession->constructDefaultRequestSettings(id,
2939 [&status, &requestTemplate]
2940 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
2941 status = s;
2942 if (status == common::V1_0::Status::OK) {
2943 const camera_metadata *r =
2944 reinterpret_cast<const camera_metadata_t*>(request.data());
2945 size_t expectedSize = request.size();
2946 int ret = validate_camera_metadata_structure(r, &expectedSize);
Yin-Chia Yeh238ef5f2017-04-18 15:01:15 -07002947 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948 *requestTemplate = clone_camera_metadata(r);
2949 if (*requestTemplate == nullptr) {
2950 ALOGE("%s: Unable to clone camera metadata received from HAL",
2951 __FUNCTION__);
2952 status = common::V1_0::Status::INTERNAL_ERROR;
2953 }
2954 } else {
2955 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2956 status = common::V1_0::Status::INTERNAL_ERROR;
2957 }
2958 }
2959 });
2960 res = CameraProviderManager::mapToStatusT(status);
2961 }
2962 return res;
2963}
2964
2965status_t Camera3Device::HalInterface::configureStreams(camera3_stream_configuration *config) {
2966 ATRACE_NAME("CameraHal::configureStreams");
2967 if (!valid()) return INVALID_OPERATION;
2968 status_t res = OK;
2969
2970 if (mHal3Device != nullptr) {
2971 res = mHal3Device->ops->configure_streams(mHal3Device, config);
2972 } else {
2973 // Convert stream config to HIDL
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002974 std::set<int> activeStreams;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002975 StreamConfiguration requestedConfiguration;
2976 requestedConfiguration.streams.resize(config->num_streams);
2977 for (size_t i = 0; i < config->num_streams; i++) {
2978 Stream &dst = requestedConfiguration.streams[i];
2979 camera3_stream_t *src = config->streams[i];
2980
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002981 Camera3Stream* cam3stream = Camera3Stream::cast(src);
2982 cam3stream->setBufferFreedListener(this);
2983 int streamId = cam3stream->getId();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002984 StreamType streamType;
2985 switch (src->stream_type) {
2986 case CAMERA3_STREAM_OUTPUT:
2987 streamType = StreamType::OUTPUT;
2988 break;
2989 case CAMERA3_STREAM_INPUT:
2990 streamType = StreamType::INPUT;
2991 break;
2992 default:
2993 ALOGE("%s: Stream %d: Unsupported stream type %d",
2994 __FUNCTION__, streamId, config->streams[i]->stream_type);
2995 return BAD_VALUE;
2996 }
2997 dst.id = streamId;
2998 dst.streamType = streamType;
2999 dst.width = src->width;
3000 dst.height = src->height;
3001 dst.format = mapToPixelFormat(src->format);
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003002 dst.usage = mapToConsumerUsage(src->usage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003003 dst.dataSpace = mapToHidlDataspace(src->data_space);
3004 dst.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003005
3006 activeStreams.insert(streamId);
3007 // Create Buffer ID map if necessary
3008 if (mBufferIdMaps.count(streamId) == 0) {
3009 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3010 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003011 }
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003012 // remove BufferIdMap for deleted streams
3013 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3014 int streamId = it->first;
3015 bool active = activeStreams.count(streamId) > 0;
3016 if (!active) {
3017 it = mBufferIdMaps.erase(it);
3018 } else {
3019 ++it;
3020 }
3021 }
3022
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08003023 res = mapToStreamConfigurationMode(
3024 (camera3_stream_configuration_mode_t) config->operation_mode,
3025 /*out*/ &requestedConfiguration.operationMode);
3026 if (res != OK) {
3027 return res;
3028 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003029
3030 // Invoke configureStreams
3031
3032 HalStreamConfiguration finalConfiguration;
3033 common::V1_0::Status status;
3034 mHidlSession->configureStreams(requestedConfiguration,
3035 [&status, &finalConfiguration]
3036 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3037 finalConfiguration = halConfiguration;
3038 status = s;
3039 });
3040 if (status != common::V1_0::Status::OK ) {
3041 return CameraProviderManager::mapToStatusT(status);
3042 }
3043
3044 // And convert output stream configuration from HIDL
3045
3046 for (size_t i = 0; i < config->num_streams; i++) {
3047 camera3_stream_t *dst = config->streams[i];
3048 int streamId = Camera3Stream::cast(dst)->getId();
3049
3050 // Start scan at i, with the assumption that the stream order matches
3051 size_t realIdx = i;
3052 bool found = false;
3053 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
3054 if (finalConfiguration.streams[realIdx].id == streamId) {
3055 found = true;
3056 break;
3057 }
3058 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3059 }
3060 if (!found) {
3061 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3062 __FUNCTION__, streamId);
3063 return INVALID_OPERATION;
3064 }
3065 HalStream &src = finalConfiguration.streams[realIdx];
3066
3067 int overrideFormat = mapToFrameworkFormat(src.overrideFormat);
3068 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3069 if (dst->format != overrideFormat) {
3070 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3071 streamId, dst->format);
3072 }
3073 } else {
3074 // Override allowed with IMPLEMENTATION_DEFINED
3075 dst->format = overrideFormat;
3076 }
3077
3078 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
3079 if (src.producerUsage != 0) {
3080 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
3081 __FUNCTION__, streamId);
3082 return INVALID_OPERATION;
3083 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003084 dst->usage = mapConsumerToFrameworkUsage(src.consumerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003085 } else {
3086 // OUTPUT
3087 if (src.consumerUsage != 0) {
3088 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3089 __FUNCTION__, streamId);
3090 return INVALID_OPERATION;
3091 }
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07003092 dst->usage = mapProducerToFrameworkUsage(src.producerUsage);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003093 }
3094 dst->max_buffers = src.maxBuffers;
3095 }
3096 }
3097 return res;
3098}
3099
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003100void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3101 /*out*/device::V3_2::CaptureRequest* captureRequest,
3102 /*out*/std::vector<native_handle_t*>* handlesCreated) {
3103
3104 if (captureRequest == nullptr || handlesCreated == nullptr) {
3105 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3106 __FUNCTION__, captureRequest, handlesCreated);
3107 return;
3108 }
3109
3110 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003111
3112 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003113
3114 {
3115 std::lock_guard<std::mutex> lock(mInflightLock);
3116 if (request->input_buffer != nullptr) {
3117 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3118 buffer_handle_t buf = *(request->input_buffer->buffer);
3119 auto pair = getBufferId(buf, streamId);
3120 bool isNewBuffer = pair.first;
3121 uint64_t bufferId = pair.second;
3122 captureRequest->inputBuffer.streamId = streamId;
3123 captureRequest->inputBuffer.bufferId = bufferId;
3124 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3125 captureRequest->inputBuffer.status = BufferStatus::OK;
3126 native_handle_t *acquireFence = nullptr;
3127 if (request->input_buffer->acquire_fence != -1) {
3128 acquireFence = native_handle_create(1,0);
3129 acquireFence->data[0] = request->input_buffer->acquire_fence;
3130 handlesCreated->push_back(acquireFence);
3131 }
3132 captureRequest->inputBuffer.acquireFence = acquireFence;
3133 captureRequest->inputBuffer.releaseFence = nullptr;
3134
3135 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3136 request->input_buffer->buffer,
3137 request->input_buffer->acquire_fence);
3138 } else {
3139 captureRequest->inputBuffer.streamId = -1;
3140 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3141 }
3142
3143 captureRequest->outputBuffers.resize(request->num_output_buffers);
3144 for (size_t i = 0; i < request->num_output_buffers; i++) {
3145 const camera3_stream_buffer_t *src = request->output_buffers + i;
3146 StreamBuffer &dst = captureRequest->outputBuffers[i];
3147 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3148 buffer_handle_t buf = *(src->buffer);
3149 auto pair = getBufferId(buf, streamId);
3150 bool isNewBuffer = pair.first;
3151 dst.streamId = streamId;
3152 dst.bufferId = pair.second;
3153 dst.buffer = isNewBuffer ? buf : nullptr;
3154 dst.status = BufferStatus::OK;
3155 native_handle_t *acquireFence = nullptr;
3156 if (src->acquire_fence != -1) {
3157 acquireFence = native_handle_create(1,0);
3158 acquireFence->data[0] = src->acquire_fence;
3159 handlesCreated->push_back(acquireFence);
3160 }
3161 dst.acquireFence = acquireFence;
3162 dst.releaseFence = nullptr;
3163
3164 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3165 src->buffer, src->acquire_fence);
3166 }
3167 }
3168}
3169
3170status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3171 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3172 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3173 if (!valid()) return INVALID_OPERATION;
3174
3175 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
3176 size_t batchSize = requests.size();
3177 captureRequests.resize(batchSize);
3178 std::vector<native_handle_t*> handlesCreated;
3179
3180 for (size_t i = 0; i < batchSize; i++) {
3181 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3182 }
3183
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003184 std::vector<device::V3_2::BufferCache> cachesToRemove;
3185 {
3186 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3187 for (auto& pair : mFreedBuffers) {
3188 // The stream might have been removed since onBufferFreed
3189 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3190 cachesToRemove.push_back({pair.first, pair.second});
3191 }
3192 }
3193 mFreedBuffers.clear();
3194 }
3195
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003196 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3197 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003198
3199 // Write metadata to FMQ.
3200 for (size_t i = 0; i < batchSize; i++) {
3201 camera3_capture_request_t* request = requests[i];
3202 device::V3_2::CaptureRequest* captureRequest = &captureRequests[i];
3203
3204 if (request->settings != nullptr) {
3205 size_t settingsSize = get_camera_metadata_size(request->settings);
3206 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3207 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3208 captureRequest->settings.resize(0);
3209 captureRequest->fmqSettingsSize = settingsSize;
3210 } else {
3211 if (mRequestMetadataQueue != nullptr) {
3212 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3213 }
3214 captureRequest->settings.setToExternal(
3215 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3216 get_camera_metadata_size(request->settings));
3217 captureRequest->fmqSettingsSize = 0u;
3218 }
3219 } else {
3220 // A null request settings maps to a size-0 CameraMetadata
3221 captureRequest->settings.resize(0);
3222 captureRequest->fmqSettingsSize = 0u;
3223 }
3224 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003225 mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003226 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3227 status = s;
3228 *numRequestProcessed = n;
3229 });
3230
3231 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3232 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3233 __FUNCTION__, *numRequestProcessed, batchSize);
3234 status = common::V1_0::Status::INTERNAL_ERROR;
3235 }
3236
3237 for (auto& handle : handlesCreated) {
3238 native_handle_delete(handle);
3239 }
3240 return CameraProviderManager::mapToStatusT(status);
3241}
3242
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003243status_t Camera3Device::HalInterface::processCaptureRequest(
3244 camera3_capture_request_t *request) {
3245 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003246 if (!valid()) return INVALID_OPERATION;
3247 status_t res = OK;
3248
3249 if (mHal3Device != nullptr) {
3250 res = mHal3Device->ops->process_capture_request(mHal3Device, request);
3251 } else {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003252 uint32_t numRequestProcessed = 0;
3253 std::vector<camera3_capture_request_t*> requests(1);
3254 requests[0] = request;
3255 res = processBatchCaptureRequests(requests, &numRequestProcessed);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003256 }
3257 return res;
3258}
3259
3260status_t Camera3Device::HalInterface::flush() {
3261 ATRACE_NAME("CameraHal::flush");
3262 if (!valid()) return INVALID_OPERATION;
3263 status_t res = OK;
3264
3265 if (mHal3Device != nullptr) {
3266 res = mHal3Device->ops->flush(mHal3Device);
3267 } else {
3268 res = CameraProviderManager::mapToStatusT(mHidlSession->flush());
3269 }
3270 return res;
3271}
3272
3273status_t Camera3Device::HalInterface::dump(int fd) {
3274 ATRACE_NAME("CameraHal::dump");
3275 if (!valid()) return INVALID_OPERATION;
3276 status_t res = OK;
3277
3278 if (mHal3Device != nullptr) {
3279 mHal3Device->ops->dump(mHal3Device, fd);
3280 } else {
3281 // Handled by CameraProviderManager::dump
3282 }
3283 return res;
3284}
3285
3286status_t Camera3Device::HalInterface::close() {
3287 ATRACE_NAME("CameraHal::close()");
3288 if (!valid()) return INVALID_OPERATION;
3289 status_t res = OK;
3290
3291 if (mHal3Device != nullptr) {
3292 mHal3Device->common.close(&mHal3Device->common);
3293 } else {
3294 mHidlSession->close();
3295 }
3296 return res;
3297}
3298
3299status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003300 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003301 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003302 auto pair = std::make_pair(buffer, acquireFence);
3303 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003304 return OK;
3305}
3306
3307status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003308 int32_t frameNumber, int32_t streamId,
3309 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003310 std::lock_guard<std::mutex> lock(mInflightLock);
3311
3312 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
3313 auto it = mInflightBufferMap.find(key);
3314 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003315 auto pair = it->second;
3316 *buffer = pair.first;
3317 int acquireFence = pair.second;
3318 if (acquireFence > 0) {
3319 ::close(acquireFence);
3320 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003321 mInflightBufferMap.erase(it);
3322 return OK;
3323}
3324
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003325std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3326 const buffer_handle_t& buf, int streamId) {
3327 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3328
3329 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
3330 auto it = bIdMap.find(buf);
3331 if (it == bIdMap.end()) {
3332 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003333 ALOGV("stream %d now have %zu buffer caches, buf %p",
3334 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003335 return std::make_pair(true, mNextBufferId - 1);
3336 } else {
3337 return std::make_pair(false, it->second);
3338 }
3339}
3340
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003341void Camera3Device::HalInterface::onBufferFreed(
3342 int streamId, const native_handle_t* handle) {
3343 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3344 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
3345 auto mapIt = mBufferIdMaps.find(streamId);
3346 if (mapIt == mBufferIdMaps.end()) {
3347 // streamId might be from a deleted stream here
3348 ALOGI("%s: stream %d has been removed",
3349 __FUNCTION__, streamId);
3350 return;
3351 }
3352 BufferIdMap& bIdMap = mapIt->second;
3353 auto it = bIdMap.find(handle);
3354 if (it == bIdMap.end()) {
3355 ALOGW("%s: cannot find buffer %p in stream %d",
3356 __FUNCTION__, handle, streamId);
3357 return;
3358 } else {
3359 bufferId = it->second;
3360 bIdMap.erase(it);
3361 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
3362 __FUNCTION__, streamId, bIdMap.size(), handle);
3363 }
3364 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3365}
3366
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003367/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003368 * RequestThread inner class methods
3369 */
3370
3371Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003372 sp<StatusTracker> statusTracker,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003373 HalInterface* interface) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003374 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003375 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003376 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003377 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003378 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003379 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003380 mReconfigured(false),
3381 mDoPause(false),
3382 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003383 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003384 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003385 mCurrentAfTriggerId(0),
3386 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003387 mRepeatingLastFrameNumber(
3388 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003389 mPrepareVideoStream(false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003390 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003391}
3392
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003393Camera3Device::RequestThread::~RequestThread() {}
3394
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003395void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003396 wp<NotificationListener> listener) {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003397 Mutex::Autolock l(mRequestLock);
3398 mListener = listener;
3399}
3400
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003401void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003402 Mutex::Autolock l(mRequestLock);
3403 mReconfigured = true;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003404 // Prepare video stream for high speed recording.
3405 mPrepareVideoStream = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003406}
3407
Jianing Wei90e59c92014-03-12 18:29:36 -07003408status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003409 List<sp<CaptureRequest> > &requests,
3410 /*out*/
3411 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07003412 Mutex::Autolock l(mRequestLock);
3413 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3414 ++it) {
3415 mRequestQueue.push_back(*it);
3416 }
3417
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003418 if (lastFrameNumber != NULL) {
3419 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3420 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3421 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3422 *lastFrameNumber);
3423 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003424
Jianing Wei90e59c92014-03-12 18:29:36 -07003425 unpauseForNewRequests();
3426
3427 return OK;
3428}
3429
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003430
3431status_t Camera3Device::RequestThread::queueTrigger(
3432 RequestTrigger trigger[],
3433 size_t count) {
3434
3435 Mutex::Autolock l(mTriggerMutex);
3436 status_t ret;
3437
3438 for (size_t i = 0; i < count; ++i) {
3439 ret = queueTriggerLocked(trigger[i]);
3440
3441 if (ret != OK) {
3442 return ret;
3443 }
3444 }
3445
3446 return OK;
3447}
3448
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003449const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3450 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003451 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003452 if (d != nullptr) return d->mId;
3453 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003454}
3455
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003456status_t Camera3Device::RequestThread::queueTriggerLocked(
3457 RequestTrigger trigger) {
3458
3459 uint32_t tag = trigger.metadataTag;
3460 ssize_t index = mTriggerMap.indexOfKey(tag);
3461
3462 switch (trigger.getTagType()) {
3463 case TYPE_BYTE:
3464 // fall-through
3465 case TYPE_INT32:
3466 break;
3467 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003468 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3469 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003470 return INVALID_OPERATION;
3471 }
3472
3473 /**
3474 * Collect only the latest trigger, since we only have 1 field
3475 * in the request settings per trigger tag, and can't send more than 1
3476 * trigger per request.
3477 */
3478 if (index != NAME_NOT_FOUND) {
3479 mTriggerMap.editValueAt(index) = trigger;
3480 } else {
3481 mTriggerMap.add(tag, trigger);
3482 }
3483
3484 return OK;
3485}
3486
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003487status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003488 const RequestList &requests,
3489 /*out*/
3490 int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003491 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003492 if (lastFrameNumber != NULL) {
3493 *lastFrameNumber = mRepeatingLastFrameNumber;
3494 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003495 mRepeatingRequests.clear();
3496 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3497 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003498
3499 unpauseForNewRequests();
3500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003501 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003502 return OK;
3503}
3504
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003505bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003506 if (mRepeatingRequests.empty()) {
3507 return false;
3508 }
3509 int32_t requestId = requestIn->mResultExtras.requestId;
3510 const RequestList &repeatRequests = mRepeatingRequests;
3511 // All repeating requests are guaranteed to have same id so only check first quest
3512 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3513 return (firstRequest->mResultExtras.requestId == requestId);
3514}
3515
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003516status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003517 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003518 return clearRepeatingRequestsLocked(lastFrameNumber);
3519
3520}
3521
3522status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003523 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003524 if (lastFrameNumber != NULL) {
3525 *lastFrameNumber = mRepeatingLastFrameNumber;
3526 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003527 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003528 return OK;
3529}
3530
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003531status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003532 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003533 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003534 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003535
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003536 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003537
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003538 // Send errors for all requests pending in the request queue, including
3539 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003540 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003541 if (listener != NULL) {
3542 for (RequestList::iterator it = mRequestQueue.begin();
3543 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003544 // Abort the input buffers for reprocess requests.
3545 if ((*it)->mInputStream != NULL) {
3546 camera3_stream_buffer_t inputBuffer;
3547 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer);
3548 if (res != OK) {
3549 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3550 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3551 } else {
3552 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3553 if (res != OK) {
3554 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3555 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3556 }
3557 }
3558 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003559 // Set the frame number this request would have had, if it
3560 // had been submitted; this frame number will not be reused.
3561 // The requestId and burstId fields were set when the request was
3562 // submitted originally (in convertMetadataListToRequestListLocked)
3563 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003564 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003565 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003566 }
3567 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003568 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003569
3570 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003571 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003572 if (lastFrameNumber != NULL) {
3573 *lastFrameNumber = mRepeatingLastFrameNumber;
3574 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003575 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003576 return OK;
3577}
3578
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003579status_t Camera3Device::RequestThread::flush() {
3580 ATRACE_CALL();
3581 Mutex::Autolock l(mFlushLock);
3582
Emilian Peev08dd2452017-04-06 16:55:14 +01003583 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003584}
3585
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003586void Camera3Device::RequestThread::setPaused(bool paused) {
3587 Mutex::Autolock l(mPauseLock);
3588 mDoPause = paused;
3589 mDoPauseSignal.signal();
3590}
3591
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003592status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3593 int32_t requestId, nsecs_t timeout) {
3594 Mutex::Autolock l(mLatestRequestMutex);
3595 status_t res;
3596 while (mLatestRequestId != requestId) {
3597 nsecs_t startTime = systemTime();
3598
3599 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3600 if (res != OK) return res;
3601
3602 timeout -= (systemTime() - startTime);
3603 }
3604
3605 return OK;
3606}
3607
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003608void Camera3Device::RequestThread::requestExit() {
3609 // Call parent to set up shutdown
3610 Thread::requestExit();
3611 // The exit from any possible waits
3612 mDoPauseSignal.signal();
3613 mRequestSignal.signal();
3614}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003615
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003616void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003617 bool surfaceAbandoned = false;
3618 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003619 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003620 {
3621 Mutex::Autolock l(mRequestLock);
3622 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3623 // repeating requests.
3624 for (const auto& request : mRepeatingRequests) {
3625 for (const auto& s : request->mOutputStreams) {
3626 if (s->isAbandoned()) {
3627 surfaceAbandoned = true;
3628 clearRepeatingRequestsLocked(&lastFrameNumber);
3629 break;
3630 }
3631 }
3632 if (surfaceAbandoned) {
3633 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003634 }
3635 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003636 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003637 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003638
3639 if (listener != NULL && surfaceAbandoned) {
3640 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003641 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003642}
3643
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003644bool Camera3Device::RequestThread::sendRequestsBatch() {
3645 status_t res;
3646 size_t batchSize = mNextRequests.size();
3647 std::vector<camera3_capture_request_t*> requests(batchSize);
3648 uint32_t numRequestProcessed = 0;
3649 for (size_t i = 0; i < batchSize; i++) {
3650 requests[i] = &mNextRequests.editItemAt(i).halRequest;
3651 }
3652
3653 ATRACE_ASYNC_BEGIN("batch frame capture", mNextRequests[0].halRequest.frame_number);
3654 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3655
3656 bool triggerRemoveFailed = false;
3657 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3658 for (size_t i = 0; i < numRequestProcessed; i++) {
3659 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3660 nextRequest.submitted = true;
3661
3662
3663 // Update the latest request sent to HAL
3664 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3665 Mutex::Autolock al(mLatestRequestMutex);
3666
3667 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3668 mLatestRequest.acquire(cloned);
3669
3670 sp<Camera3Device> parent = mParent.promote();
3671 if (parent != NULL) {
3672 parent->monitorMetadata(TagMonitor::REQUEST,
3673 nextRequest.halRequest.frame_number,
3674 0, mLatestRequest);
3675 }
3676 }
3677
3678 if (nextRequest.halRequest.settings != NULL) {
3679 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3680 }
3681
3682 if (!triggerRemoveFailed) {
3683 // Remove any previously queued triggers (after unlock)
3684 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3685 if (removeTriggerRes != OK) {
3686 triggerRemoveFailed = true;
3687 triggerFailedRequest = nextRequest;
3688 }
3689 }
3690 }
3691
3692 if (triggerRemoveFailed) {
3693 SET_ERR("RequestThread: Unable to remove triggers "
3694 "(capture request %d, HAL device: %s (%d)",
3695 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3696 cleanUpFailedRequests(/*sendRequestError*/ false);
3697 return false;
3698 }
3699
3700 if (res != OK) {
3701 // Should only get a failure here for malformed requests or device-level
3702 // errors, so consider all errors fatal. Bad metadata failures should
3703 // come through notify.
3704 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3705 mNextRequests[numRequestProcessed].halRequest.frame_number,
3706 strerror(-res), res);
3707 cleanUpFailedRequests(/*sendRequestError*/ false);
3708 return false;
3709 }
3710 return true;
3711}
3712
3713bool Camera3Device::RequestThread::sendRequestsOneByOne() {
3714 status_t res;
3715
3716 for (auto& nextRequest : mNextRequests) {
3717 // Submit request and block until ready for next one
3718 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
3719 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
3720
3721 if (res != OK) {
3722 // Should only get a failure here for malformed requests or device-level
3723 // errors, so consider all errors fatal. Bad metadata failures should
3724 // come through notify.
3725 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
3726 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
3727 res);
3728 cleanUpFailedRequests(/*sendRequestError*/ false);
3729 return false;
3730 }
3731
3732 // Mark that the request has be submitted successfully.
3733 nextRequest.submitted = true;
3734
3735 // Update the latest request sent to HAL
3736 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
3737 Mutex::Autolock al(mLatestRequestMutex);
3738
3739 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
3740 mLatestRequest.acquire(cloned);
3741
3742 sp<Camera3Device> parent = mParent.promote();
3743 if (parent != NULL) {
3744 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
3745 0, mLatestRequest);
3746 }
3747 }
3748
3749 if (nextRequest.halRequest.settings != NULL) {
3750 nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
3751 }
3752
3753 // Remove any previously queued triggers (after unlock)
3754 res = removeTriggers(mPrevRequest);
3755 if (res != OK) {
3756 SET_ERR("RequestThread: Unable to remove triggers "
3757 "(capture request %d, HAL device: %s (%d)",
3758 nextRequest.halRequest.frame_number, strerror(-res), res);
3759 cleanUpFailedRequests(/*sendRequestError*/ false);
3760 return false;
3761 }
3762 }
3763 return true;
3764}
3765
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003766bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003767 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003768 status_t res;
3769
3770 // Handle paused state.
3771 if (waitIfPaused()) {
3772 return true;
3773 }
3774
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003775 // Wait for the next batch of requests.
3776 waitForNextRequestBatch();
3777 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003778 return true;
3779 }
3780
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003781 // Get the latest request ID, if any
3782 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003783 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003784 captureRequest->mSettings.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003785 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003786 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003787 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003788 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3789 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003790 }
3791
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003792 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003793 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003794 if (res == TIMED_OUT) {
3795 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003796 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003797 // Check if any stream is abandoned.
3798 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003799 return true;
3800 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003801 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003802 return false;
3803 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003804
Zhijun Hecc27e112013-10-03 16:12:43 -07003805 // Inform waitUntilRequestProcessed thread of a new request ID
3806 {
3807 Mutex::Autolock al(mLatestRequestMutex);
3808
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003809 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003810 mLatestRequestSignal.signal();
3811 }
3812
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003813 // Submit a batch of requests to HAL.
3814 // Use flush lock only when submitting multilple requests in a batch.
3815 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3816 // which may take a long time to finish so synchronizing flush() and
3817 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3818 // For now, only synchronize for high speed recording and we should figure something out for
3819 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003820 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003821
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003822 if (useFlushLock) {
3823 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003824 }
3825
Zhijun Hef0645c12016-08-02 00:58:11 -07003826 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003827 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003828
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003829 bool submitRequestSuccess = false;
3830 if (mInterface->supportBatchRequest()) {
3831 submitRequestSuccess = sendRequestsBatch();
3832 } else {
3833 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003834 }
3835
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003836 if (useFlushLock) {
3837 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003838 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003839
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003840 // Unset as current request
3841 {
3842 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003843 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003844 }
3845
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003846 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003847}
3848
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003849status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003850 ATRACE_CALL();
3851
Shuzhen Wang4a472662017-02-26 23:29:04 -08003852 for (size_t i = 0; i < mNextRequests.size(); i++) {
3853 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003854 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3855 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
3856 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3857
3858 // Prepare a request to HAL
3859 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3860
3861 // Insert any queued triggers (before metadata is locked)
3862 status_t res = insertTriggers(captureRequest);
3863
3864 if (res < 0) {
3865 SET_ERR("RequestThread: Unable to insert triggers "
3866 "(capture request %d, HAL device: %s (%d)",
3867 halRequest->frame_number, strerror(-res), res);
3868 return INVALID_OPERATION;
3869 }
3870 int triggerCount = res;
3871 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3872 mPrevTriggers = triggerCount;
3873
3874 // If the request is the same as last, or we had triggers last time
3875 if (mPrevRequest != captureRequest || triggersMixedIn) {
3876 /**
3877 * HAL workaround:
3878 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
3879 */
3880 res = addDummyTriggerIds(captureRequest);
3881 if (res != OK) {
3882 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
3883 "(capture request %d, HAL device: %s (%d)",
3884 halRequest->frame_number, strerror(-res), res);
3885 return INVALID_OPERATION;
3886 }
3887
3888 /**
3889 * The request should be presorted so accesses in HAL
3890 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3891 */
3892 captureRequest->mSettings.sort();
3893 halRequest->settings = captureRequest->mSettings.getAndLock();
3894 mPrevRequest = captureRequest;
3895 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3896
3897 IF_ALOGV() {
3898 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3899 find_camera_metadata_ro_entry(
3900 halRequest->settings,
3901 ANDROID_CONTROL_AF_TRIGGER,
3902 &e
3903 );
3904 if (e.count > 0) {
3905 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3906 __FUNCTION__,
3907 halRequest->frame_number,
3908 e.data.u8[0]);
3909 }
3910 }
3911 } else {
3912 // leave request.settings NULL to indicate 'reuse latest given'
3913 ALOGVV("%s: Request settings are REUSED",
3914 __FUNCTION__);
3915 }
3916
3917 uint32_t totalNumBuffers = 0;
3918
3919 // Fill in buffers
3920 if (captureRequest->mInputStream != NULL) {
3921 halRequest->input_buffer = &captureRequest->mInputBuffer;
3922 totalNumBuffers += 1;
3923 } else {
3924 halRequest->input_buffer = NULL;
3925 }
3926
3927 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
3928 captureRequest->mOutputStreams.size());
3929 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang4a472662017-02-26 23:29:04 -08003930 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
3931 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003932
3933 // Prepare video buffers for high speed recording on the first video request.
3934 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3935 // Only try to prepare video stream on the first video request.
3936 mPrepareVideoStream = false;
3937
3938 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
3939 while (res == NOT_ENOUGH_DATA) {
3940 res = outputStream->prepareNextBuffer();
3941 }
3942 if (res != OK) {
3943 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3944 __FUNCTION__, strerror(-res), res);
3945 outputStream->cancelPrepare();
3946 }
3947 }
3948
Shuzhen Wang4a472662017-02-26 23:29:04 -08003949 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3950 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003951 if (res != OK) {
3952 // Can't get output buffer from gralloc queue - this could be due to
3953 // abandoned queue or other consumer misbehavior, so not a fatal
3954 // error
3955 ALOGE("RequestThread: Can't get output buffer, skipping request:"
3956 " %s (%d)", strerror(-res), res);
3957
3958 return TIMED_OUT;
3959 }
3960 halRequest->num_output_buffers++;
Shuzhen Wang0129d522016-10-30 22:43:41 -07003961
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003962 }
3963 totalNumBuffers += halRequest->num_output_buffers;
3964
3965 // Log request in the in-flight queue
3966 sp<Camera3Device> parent = mParent.promote();
3967 if (parent == NULL) {
3968 // Should not happen, and nowhere to send errors to, so just log it
3969 CLOGE("RequestThread: Parent is gone");
3970 return INVALID_OPERATION;
3971 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08003972
3973 // If this request list is for constrained high speed recording (not
3974 // preview), and the current request is not the last one in the batch,
3975 // do not send callback to the app.
3976 bool hasCallback = true;
3977 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
3978 hasCallback = false;
3979 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003980 res = parent->registerInFlight(halRequest->frame_number,
3981 totalNumBuffers, captureRequest->mResultExtras,
3982 /*hasInput*/halRequest->input_buffer != NULL,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003983 hasCallback);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003984 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3985 ", burstId = %" PRId32 ".",
3986 __FUNCTION__,
3987 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3988 captureRequest->mResultExtras.burstId);
3989 if (res != OK) {
3990 SET_ERR("RequestThread: Unable to register new in-flight request:"
3991 " %s (%d)", strerror(-res), res);
3992 return INVALID_OPERATION;
3993 }
3994 }
3995
3996 return OK;
3997}
3998
Igor Murashkin1e479c02013-09-06 16:55:14 -07003999CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4000 Mutex::Autolock al(mLatestRequestMutex);
4001
4002 ALOGV("RequestThread::%s", __FUNCTION__);
4003
4004 return mLatestRequest;
4005}
4006
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004007bool Camera3Device::RequestThread::isStreamPending(
4008 sp<Camera3StreamInterface>& stream) {
4009 Mutex::Autolock l(mRequestLock);
4010
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004011 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004012 if (!nextRequest.submitted) {
4013 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4014 if (stream == s) return true;
4015 }
4016 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004017 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004018 }
4019
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004020 for (const auto& request : mRequestQueue) {
4021 for (const auto& s : request->mOutputStreams) {
4022 if (stream == s) return true;
4023 }
4024 if (stream == request->mInputStream) return true;
4025 }
4026
4027 for (const auto& request : mRepeatingRequests) {
4028 for (const auto& s : request->mOutputStreams) {
4029 if (stream == s) return true;
4030 }
4031 if (stream == request->mInputStream) return true;
4032 }
4033
4034 return false;
4035}
Jianing Weicb0652e2014-03-12 18:29:36 -07004036
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004037void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4038 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004039 return;
4040 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004041
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004042 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004043 // Skip the ones that have been submitted successfully.
4044 if (nextRequest.submitted) {
4045 continue;
4046 }
4047
4048 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4049 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4050 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4051
4052 if (halRequest->settings != NULL) {
4053 captureRequest->mSettings.unlock(halRequest->settings);
4054 }
4055
4056 if (captureRequest->mInputStream != NULL) {
4057 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4058 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4059 }
4060
4061 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4062 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4063 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
4064 }
4065
4066 if (sendRequestError) {
4067 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004068 sp<NotificationListener> listener = mListener.promote();
4069 if (listener != NULL) {
4070 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004071 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072 captureRequest->mResultExtras);
4073 }
4074 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004075
4076 // Remove yet-to-be submitted inflight request from inflightMap
4077 {
4078 sp<Camera3Device> parent = mParent.promote();
4079 if (parent != NULL) {
4080 Mutex::Autolock l(parent->mInFlightLock);
4081 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4082 if (idx >= 0) {
4083 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4084 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4085 parent->removeInFlightMapEntryLocked(idx);
4086 }
4087 }
4088 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004089 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004090
4091 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004092 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004093}
4094
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004095void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004096 // Optimized a bit for the simple steady-state case (single repeating
4097 // request), to avoid putting that request in the queue temporarily.
4098 Mutex::Autolock l(mRequestLock);
4099
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 assert(mNextRequests.empty());
4101
4102 NextRequest nextRequest;
4103 nextRequest.captureRequest = waitForNextRequestLocked();
4104 if (nextRequest.captureRequest == nullptr) {
4105 return;
4106 }
4107
4108 nextRequest.halRequest = camera3_capture_request_t();
4109 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004110 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004111
4112 // Wait for additional requests
4113 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4114
4115 for (size_t i = 1; i < batchSize; i++) {
4116 NextRequest additionalRequest;
4117 additionalRequest.captureRequest = waitForNextRequestLocked();
4118 if (additionalRequest.captureRequest == nullptr) {
4119 break;
4120 }
4121
4122 additionalRequest.halRequest = camera3_capture_request_t();
4123 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004124 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004125 }
4126
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004127 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004128 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004129 mNextRequests.size(), batchSize);
4130 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131 }
4132
4133 return;
4134}
4135
4136sp<Camera3Device::CaptureRequest>
4137 Camera3Device::RequestThread::waitForNextRequestLocked() {
4138 status_t res;
4139 sp<CaptureRequest> nextRequest;
4140
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004141 while (mRequestQueue.empty()) {
4142 if (!mRepeatingRequests.empty()) {
4143 // Always atomically enqueue all requests in a repeating request
4144 // list. Guarantees a complete in-sequence set of captures to
4145 // application.
4146 const RequestList &requests = mRepeatingRequests;
4147 RequestList::const_iterator firstRequest =
4148 requests.begin();
4149 nextRequest = *firstRequest;
4150 mRequestQueue.insert(mRequestQueue.end(),
4151 ++firstRequest,
4152 requests.end());
4153 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004154
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004155 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004156
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 break;
4158 }
4159
4160 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4161
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004162 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4163 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 Mutex::Autolock pl(mPauseLock);
4165 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004166 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004167 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004168 // Let the tracker know
4169 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4170 if (statusTracker != 0) {
4171 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4172 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004173 }
4174 // Stop waiting for now and let thread management happen
4175 return NULL;
4176 }
4177 }
4178
4179 if (nextRequest == NULL) {
4180 // Don't have a repeating request already in hand, so queue
4181 // must have an entry now.
4182 RequestList::iterator firstRequest =
4183 mRequestQueue.begin();
4184 nextRequest = *firstRequest;
4185 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004186 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4187 sp<NotificationListener> listener = mListener.promote();
4188 if (listener != NULL) {
4189 listener->notifyRequestQueueEmpty();
4190 }
4191 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004192 }
4193
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004194 // In case we've been unpaused by setPaused clearing mDoPause, need to
4195 // update internal pause state (capture/setRepeatingRequest unpause
4196 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004198 if (mPaused) {
4199 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4200 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4201 if (statusTracker != 0) {
4202 statusTracker->markComponentActive(mStatusId);
4203 }
4204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 mPaused = false;
4206
4207 // Check if we've reconfigured since last time, and reset the preview
4208 // request if so. Can't use 'NULL request == repeat' across configure calls.
4209 if (mReconfigured) {
4210 mPrevRequest.clear();
4211 mReconfigured = false;
4212 }
4213
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004214 if (nextRequest != NULL) {
4215 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004216 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4217 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004218
4219 // Since RequestThread::clear() removes buffers from the input stream,
4220 // get the right buffer here before unlocking mRequestLock
4221 if (nextRequest->mInputStream != NULL) {
4222 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
4223 if (res != OK) {
4224 // Can't get input buffer from gralloc queue - this could be due to
4225 // disconnected queue or other producer misbehavior, so not a fatal
4226 // error
4227 ALOGE("%s: Can't get input buffer, skipping request:"
4228 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004229
4230 sp<NotificationListener> listener = mListener.promote();
4231 if (listener != NULL) {
4232 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004233 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004234 nextRequest->mResultExtras);
4235 }
4236 return NULL;
4237 }
4238 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004239 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004240
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004241 return nextRequest;
4242}
4243
4244bool Camera3Device::RequestThread::waitIfPaused() {
4245 status_t res;
4246 Mutex::Autolock l(mPauseLock);
4247 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248 if (mPaused == false) {
4249 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004250 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4251 // Let the tracker know
4252 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4253 if (statusTracker != 0) {
4254 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4255 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004257
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004259 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 return true;
4261 }
4262 }
4263 // We don't set mPaused to false here, because waitForNextRequest needs
4264 // to further manage the paused state in case of starvation.
4265 return false;
4266}
4267
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004268void Camera3Device::RequestThread::unpauseForNewRequests() {
4269 // With work to do, mark thread as unpaused.
4270 // If paused by request (setPaused), don't resume, to avoid
4271 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004272 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004273 Mutex::Autolock p(mPauseLock);
4274 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004275 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4276 if (mPaused) {
4277 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4278 if (statusTracker != 0) {
4279 statusTracker->markComponentActive(mStatusId);
4280 }
4281 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004282 mPaused = false;
4283 }
4284}
4285
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004286void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4287 sp<Camera3Device> parent = mParent.promote();
4288 if (parent != NULL) {
4289 va_list args;
4290 va_start(args, fmt);
4291
4292 parent->setErrorStateV(fmt, args);
4293
4294 va_end(args);
4295 }
4296}
4297
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004298status_t Camera3Device::RequestThread::insertTriggers(
4299 const sp<CaptureRequest> &request) {
4300
4301 Mutex::Autolock al(mTriggerMutex);
4302
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004303 sp<Camera3Device> parent = mParent.promote();
4304 if (parent == NULL) {
4305 CLOGE("RequestThread: Parent is gone");
4306 return DEAD_OBJECT;
4307 }
4308
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004309 CameraMetadata &metadata = request->mSettings;
4310 size_t count = mTriggerMap.size();
4311
4312 for (size_t i = 0; i < count; ++i) {
4313 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004314 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004315
4316 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4317 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4318 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004319 if (isAeTrigger) {
4320 request->mResultExtras.precaptureTriggerId = triggerId;
4321 mCurrentPreCaptureTriggerId = triggerId;
4322 } else {
4323 request->mResultExtras.afTriggerId = triggerId;
4324 mCurrentAfTriggerId = triggerId;
4325 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004326 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004327 }
4328
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004329 camera_metadata_entry entry = metadata.find(tag);
4330
4331 if (entry.count > 0) {
4332 /**
4333 * Already has an entry for this trigger in the request.
4334 * Rewrite it with our requested trigger value.
4335 */
4336 RequestTrigger oldTrigger = trigger;
4337
4338 oldTrigger.entryValue = entry.data.u8[0];
4339
4340 mTriggerReplacedMap.add(tag, oldTrigger);
4341 } else {
4342 /**
4343 * More typical, no trigger entry, so we just add it
4344 */
4345 mTriggerRemovedMap.add(tag, trigger);
4346 }
4347
4348 status_t res;
4349
4350 switch (trigger.getTagType()) {
4351 case TYPE_BYTE: {
4352 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4353 res = metadata.update(tag,
4354 &entryValue,
4355 /*count*/1);
4356 break;
4357 }
4358 case TYPE_INT32:
4359 res = metadata.update(tag,
4360 &trigger.entryValue,
4361 /*count*/1);
4362 break;
4363 default:
4364 ALOGE("%s: Type not supported: 0x%x",
4365 __FUNCTION__,
4366 trigger.getTagType());
4367 return INVALID_OPERATION;
4368 }
4369
4370 if (res != OK) {
4371 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4372 ", value %d", __FUNCTION__, trigger.getTagName(),
4373 trigger.entryValue);
4374 return res;
4375 }
4376
4377 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4378 trigger.getTagName(),
4379 trigger.entryValue);
4380 }
4381
4382 mTriggerMap.clear();
4383
4384 return count;
4385}
4386
4387status_t Camera3Device::RequestThread::removeTriggers(
4388 const sp<CaptureRequest> &request) {
4389 Mutex::Autolock al(mTriggerMutex);
4390
4391 CameraMetadata &metadata = request->mSettings;
4392
4393 /**
4394 * Replace all old entries with their old values.
4395 */
4396 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4397 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4398
4399 status_t res;
4400
4401 uint32_t tag = trigger.metadataTag;
4402 switch (trigger.getTagType()) {
4403 case TYPE_BYTE: {
4404 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4405 res = metadata.update(tag,
4406 &entryValue,
4407 /*count*/1);
4408 break;
4409 }
4410 case TYPE_INT32:
4411 res = metadata.update(tag,
4412 &trigger.entryValue,
4413 /*count*/1);
4414 break;
4415 default:
4416 ALOGE("%s: Type not supported: 0x%x",
4417 __FUNCTION__,
4418 trigger.getTagType());
4419 return INVALID_OPERATION;
4420 }
4421
4422 if (res != OK) {
4423 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4424 ", trigger value %d", __FUNCTION__,
4425 trigger.getTagName(), trigger.entryValue);
4426 return res;
4427 }
4428 }
4429 mTriggerReplacedMap.clear();
4430
4431 /**
4432 * Remove all new entries.
4433 */
4434 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4435 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4436 status_t res = metadata.erase(trigger.metadataTag);
4437
4438 if (res != OK) {
4439 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4440 ", trigger value %d", __FUNCTION__,
4441 trigger.getTagName(), trigger.entryValue);
4442 return res;
4443 }
4444 }
4445 mTriggerRemovedMap.clear();
4446
4447 return OK;
4448}
4449
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004450status_t Camera3Device::RequestThread::addDummyTriggerIds(
4451 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004452 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004453 static const int32_t dummyTriggerId = 1;
4454 status_t res;
4455
4456 CameraMetadata &metadata = request->mSettings;
4457
4458 // If AF trigger is active, insert a dummy AF trigger ID if none already
4459 // exists
4460 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4461 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4462 if (afTrigger.count > 0 &&
4463 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4464 afId.count == 0) {
4465 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
4466 if (res != OK) return res;
4467 }
4468
4469 // If AE precapture trigger is active, insert a dummy precapture trigger ID
4470 // if none already exists
4471 camera_metadata_entry pcTrigger =
4472 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4473 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4474 if (pcTrigger.count > 0 &&
4475 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4476 pcId.count == 0) {
4477 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4478 &dummyTriggerId, 1);
4479 if (res != OK) return res;
4480 }
4481
4482 return OK;
4483}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004484
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004485/**
4486 * PreparerThread inner class methods
4487 */
4488
4489Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004490 Thread(/*canCallJava*/false), mListener(nullptr),
4491 mActive(false), mCancelNow(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004492}
4493
4494Camera3Device::PreparerThread::~PreparerThread() {
4495 Thread::requestExitAndWait();
4496 if (mCurrentStream != nullptr) {
4497 mCurrentStream->cancelPrepare();
4498 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4499 mCurrentStream.clear();
4500 }
4501 clear();
4502}
4503
Ruben Brunkc78ac262015-08-13 17:58:46 -07004504status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004505 status_t res;
4506
4507 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004508 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004509
Ruben Brunkc78ac262015-08-13 17:58:46 -07004510 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004511 if (res == OK) {
4512 // No preparation needed, fire listener right off
4513 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004514 if (listener != NULL) {
4515 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004516 }
4517 return OK;
4518 } else if (res != NOT_ENOUGH_DATA) {
4519 return res;
4520 }
4521
4522 // Need to prepare, start up thread if necessary
4523 if (!mActive) {
4524 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4525 // isn't running
4526 Thread::requestExitAndWait();
4527 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4528 if (res != OK) {
4529 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004530 if (listener != NULL) {
4531 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004532 }
4533 return res;
4534 }
4535 mCancelNow = false;
4536 mActive = true;
4537 ALOGV("%s: Preparer stream started", __FUNCTION__);
4538 }
4539
4540 // queue up the work
4541 mPendingStreams.push_back(stream);
4542 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4543
4544 return OK;
4545}
4546
4547status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004548 Mutex::Autolock l(mLock);
4549
4550 for (const auto& stream : mPendingStreams) {
4551 stream->cancelPrepare();
4552 }
4553 mPendingStreams.clear();
4554 mCancelNow = true;
4555
4556 return OK;
4557}
4558
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004559void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004560 Mutex::Autolock l(mLock);
4561 mListener = listener;
4562}
4563
4564bool Camera3Device::PreparerThread::threadLoop() {
4565 status_t res;
4566 {
4567 Mutex::Autolock l(mLock);
4568 if (mCurrentStream == nullptr) {
4569 // End thread if done with work
4570 if (mPendingStreams.empty()) {
4571 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4572 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4573 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4574 mActive = false;
4575 return false;
4576 }
4577
4578 // Get next stream to prepare
4579 auto it = mPendingStreams.begin();
4580 mCurrentStream = *it;
4581 mPendingStreams.erase(it);
4582 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4583 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4584 } else if (mCancelNow) {
4585 mCurrentStream->cancelPrepare();
4586 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4587 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4588 mCurrentStream.clear();
4589 mCancelNow = false;
4590 return true;
4591 }
4592 }
4593
4594 res = mCurrentStream->prepareNextBuffer();
4595 if (res == NOT_ENOUGH_DATA) return true;
4596 if (res != OK) {
4597 // Something bad happened; try to recover by cancelling prepare and
4598 // signalling listener anyway
4599 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4600 mCurrentStream->getId(), res, strerror(-res));
4601 mCurrentStream->cancelPrepare();
4602 }
4603
4604 // This stream has finished, notify listener
4605 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004606 sp<NotificationListener> listener = mListener.promote();
4607 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004608 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4609 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004610 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004611 }
4612
4613 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4614 mCurrentStream.clear();
4615
4616 return true;
4617}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004618
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004619/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004620 * Static callback forwarding methods from HAL to instance
4621 */
4622
4623void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
4624 const camera3_capture_result *result) {
4625 Camera3Device *d =
4626 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07004627
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004628 d->processCaptureResult(result);
4629}
4630
4631void Camera3Device::sNotify(const camera3_callback_ops *cb,
4632 const camera3_notify_msg *msg) {
4633 Camera3Device *d =
4634 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
4635 d->notify(msg);
4636}
4637
4638}; // namespace android