Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 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 "ExtCamDevSsn" |
| 18 | // #define LOG_NDEBUG 0 |
| 19 | #include <log/log.h> |
| 20 | |
| 21 | #include "ExternalCameraDeviceSession.h" |
| 22 | |
| 23 | #include <Exif.h> |
| 24 | #include <ExternalCameraOfflineSession.h> |
| 25 | #include <aidl/android/hardware/camera/device/CameraBlob.h> |
| 26 | #include <aidl/android/hardware/camera/device/CameraBlobId.h> |
| 27 | #include <aidl/android/hardware/camera/device/ErrorMsg.h> |
| 28 | #include <aidl/android/hardware/camera/device/ShutterMsg.h> |
| 29 | #include <aidl/android/hardware/camera/device/StreamBufferRet.h> |
| 30 | #include <aidl/android/hardware/camera/device/StreamBuffersVal.h> |
| 31 | #include <aidl/android/hardware/camera/device/StreamConfigurationMode.h> |
| 32 | #include <aidl/android/hardware/camera/device/StreamRotation.h> |
| 33 | #include <aidl/android/hardware/camera/device/StreamType.h> |
| 34 | #include <aidl/android/hardware/graphics/common/Dataspace.h> |
| 35 | #include <aidlcommonsupport/NativeHandle.h> |
| 36 | #include <convert.h> |
| 37 | #include <linux/videodev2.h> |
| 38 | #include <sync/sync.h> |
| 39 | #include <utils/Trace.h> |
| 40 | #include <deque> |
| 41 | |
| 42 | #define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs |
| 43 | #include <libyuv.h> |
| 44 | #include <libyuv/convert.h> |
| 45 | |
| 46 | namespace android { |
| 47 | namespace hardware { |
| 48 | namespace camera { |
| 49 | namespace device { |
| 50 | namespace implementation { |
| 51 | |
| 52 | namespace { |
| 53 | |
| 54 | // Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer. |
| 55 | static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */; |
| 56 | |
| 57 | const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial |
| 58 | // bad frames. TODO: develop a better bad frame detection |
| 59 | // method |
| 60 | constexpr int MAX_RETRY = 15; // Allow retry some ioctl failures a few times to account for some |
| 61 | // webcam showing temporarily ioctl failures. |
| 62 | constexpr int IOCTL_RETRY_SLEEP_US = 33000; // 33ms * MAX_RETRY = 0.5 seconds |
| 63 | |
| 64 | // Constants for tryLock during dumpstate |
| 65 | static constexpr int kDumpLockRetries = 50; |
| 66 | static constexpr int kDumpLockSleep = 60000; |
| 67 | |
| 68 | bool tryLock(Mutex& mutex) { |
| 69 | bool locked = false; |
| 70 | for (int i = 0; i < kDumpLockRetries; ++i) { |
| 71 | if (mutex.tryLock() == NO_ERROR) { |
| 72 | locked = true; |
| 73 | break; |
| 74 | } |
| 75 | usleep(kDumpLockSleep); |
| 76 | } |
| 77 | return locked; |
| 78 | } |
| 79 | |
| 80 | bool tryLock(std::mutex& mutex) { |
| 81 | bool locked = false; |
| 82 | for (int i = 0; i < kDumpLockRetries; ++i) { |
| 83 | if (mutex.try_lock()) { |
| 84 | locked = true; |
| 85 | break; |
| 86 | } |
| 87 | usleep(kDumpLockSleep); |
| 88 | } |
| 89 | return locked; |
| 90 | } |
| 91 | |
| 92 | } // anonymous namespace |
| 93 | |
| 94 | using ::aidl::android::hardware::camera::device::BufferRequestStatus; |
| 95 | using ::aidl::android::hardware::camera::device::CameraBlob; |
| 96 | using ::aidl::android::hardware::camera::device::CameraBlobId; |
| 97 | using ::aidl::android::hardware::camera::device::ErrorMsg; |
| 98 | using ::aidl::android::hardware::camera::device::ShutterMsg; |
| 99 | using ::aidl::android::hardware::camera::device::StreamBuffer; |
| 100 | using ::aidl::android::hardware::camera::device::StreamBufferRet; |
| 101 | using ::aidl::android::hardware::camera::device::StreamBuffersVal; |
| 102 | using ::aidl::android::hardware::camera::device::StreamConfigurationMode; |
| 103 | using ::aidl::android::hardware::camera::device::StreamRotation; |
| 104 | using ::aidl::android::hardware::camera::device::StreamType; |
| 105 | using ::aidl::android::hardware::graphics::common::Dataspace; |
| 106 | using ::android::hardware::camera::common::V1_0::helper::ExifUtils; |
| 107 | |
| 108 | // Static instances |
| 109 | const int ExternalCameraDeviceSession::kMaxProcessedStream; |
| 110 | const int ExternalCameraDeviceSession::kMaxStallStream; |
| 111 | HandleImporter ExternalCameraDeviceSession::sHandleImporter; |
| 112 | |
| 113 | ExternalCameraDeviceSession::ExternalCameraDeviceSession( |
| 114 | const std::shared_ptr<ICameraDeviceCallback>& callback, const ExternalCameraConfig& cfg, |
| 115 | const std::vector<SupportedV4L2Format>& sortedFormats, const CroppingType& croppingType, |
| 116 | const common::V1_0::helper::CameraMetadata& chars, const std::string& cameraId, |
| 117 | unique_fd v4l2Fd) |
| 118 | : mCallback(callback), |
| 119 | mCfg(cfg), |
| 120 | mCameraCharacteristics(chars), |
| 121 | mSupportedFormats(sortedFormats), |
| 122 | mCroppingType(croppingType), |
| 123 | mCameraId(cameraId), |
| 124 | mV4l2Fd(std::move(v4l2Fd)), |
| 125 | mMaxThumbResolution(getMaxThumbResolution()), |
| 126 | mMaxJpegResolution(getMaxJpegResolution()) {} |
| 127 | |
| 128 | Size ExternalCameraDeviceSession::getMaxThumbResolution() const { |
| 129 | return getMaxThumbnailResolution(mCameraCharacteristics); |
| 130 | } |
| 131 | |
| 132 | Size ExternalCameraDeviceSession::getMaxJpegResolution() const { |
| 133 | Size ret{0, 0}; |
| 134 | for (auto& fmt : mSupportedFormats) { |
| 135 | if (fmt.width * fmt.height > ret.width * ret.height) { |
| 136 | ret = Size{fmt.width, fmt.height}; |
| 137 | } |
| 138 | } |
| 139 | return ret; |
| 140 | } |
| 141 | |
| 142 | bool ExternalCameraDeviceSession::initialize() { |
| 143 | if (mV4l2Fd.get() < 0) { |
| 144 | ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get()); |
| 145 | return true; |
| 146 | } |
| 147 | |
| 148 | struct v4l2_capability capability; |
| 149 | int ret = ioctl(mV4l2Fd.get(), VIDIOC_QUERYCAP, &capability); |
| 150 | std::string make, model; |
| 151 | if (ret < 0) { |
| 152 | ALOGW("%s v4l2 QUERYCAP failed", __FUNCTION__); |
| 153 | mExifMake = "Generic UVC webcam"; |
| 154 | mExifModel = "Generic UVC webcam"; |
| 155 | } else { |
| 156 | // capability.card is UTF-8 encoded |
| 157 | char card[32]; |
| 158 | int j = 0; |
| 159 | for (int i = 0; i < 32; i++) { |
| 160 | if (capability.card[i] < 128) { |
| 161 | card[j++] = capability.card[i]; |
| 162 | } |
| 163 | if (capability.card[i] == '\0') { |
| 164 | break; |
| 165 | } |
| 166 | } |
| 167 | if (j == 0 || card[j - 1] != '\0') { |
| 168 | mExifMake = "Generic UVC webcam"; |
| 169 | mExifModel = "Generic UVC webcam"; |
| 170 | } else { |
| 171 | mExifMake = card; |
| 172 | mExifModel = card; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | initOutputThread(); |
| 177 | if (mOutputThread == nullptr) { |
| 178 | ALOGE("%s: init OutputThread failed!", __FUNCTION__); |
| 179 | return true; |
| 180 | } |
| 181 | mOutputThread->setExifMakeModel(mExifMake, mExifModel); |
| 182 | |
| 183 | status_t status = initDefaultRequests(); |
| 184 | if (status != OK) { |
| 185 | ALOGE("%s: init default requests failed!", __FUNCTION__); |
| 186 | return true; |
| 187 | } |
| 188 | |
| 189 | mRequestMetadataQueue = |
| 190 | std::make_unique<RequestMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */); |
| 191 | if (!mRequestMetadataQueue->isValid()) { |
| 192 | ALOGE("%s: invalid request fmq", __FUNCTION__); |
| 193 | return true; |
| 194 | } |
| 195 | |
| 196 | mResultMetadataQueue = |
| 197 | std::make_shared<ResultMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */); |
| 198 | if (!mResultMetadataQueue->isValid()) { |
| 199 | ALOGE("%s: invalid result fmq", __FUNCTION__); |
| 200 | return true; |
| 201 | } |
| 202 | |
| 203 | mOutputThread->run(); |
| 204 | return false; |
| 205 | } |
| 206 | |
| 207 | bool ExternalCameraDeviceSession::isInitFailed() { |
| 208 | Mutex::Autolock _l(mLock); |
| 209 | if (!mInitialized) { |
| 210 | mInitFail = initialize(); |
| 211 | mInitialized = true; |
| 212 | } |
| 213 | return mInitFail; |
| 214 | } |
| 215 | |
| 216 | void ExternalCameraDeviceSession::initOutputThread() { |
| 217 | // Grab a shared_ptr to 'this' from ndk::SharedRefBase::ref() |
| 218 | std::shared_ptr<ExternalCameraDeviceSession> thiz = ref<ExternalCameraDeviceSession>(); |
| 219 | |
Avichal Rakesh | 740c256 | 2022-12-13 13:25:24 -0800 | [diff] [blame] | 220 | mBufferRequestThread = std::make_shared<BufferRequestThread>(/*parent=*/thiz, mCallback); |
| 221 | mBufferRequestThread->run(); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 222 | mOutputThread = std::make_shared<OutputThread>(/*parent=*/thiz, mCroppingType, |
| 223 | mCameraCharacteristics, mBufferRequestThread); |
| 224 | } |
| 225 | |
| 226 | void ExternalCameraDeviceSession::closeOutputThread() { |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 227 | if (mOutputThread != nullptr) { |
| 228 | mOutputThread->flush(); |
| 229 | mOutputThread->requestExitAndWait(); |
| 230 | mOutputThread.reset(); |
| 231 | } |
| 232 | } |
| 233 | |
Tang Lee | 65382f6 | 2023-08-01 18:23:07 +0800 | [diff] [blame] | 234 | void ExternalCameraDeviceSession::closeBufferRequestThread() { |
| 235 | if (mBufferRequestThread != nullptr) { |
| 236 | mBufferRequestThread->requestExitAndWait(); |
| 237 | mBufferRequestThread.reset(); |
| 238 | } |
| 239 | } |
| 240 | |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 241 | Status ExternalCameraDeviceSession::initStatus() const { |
| 242 | Mutex::Autolock _l(mLock); |
| 243 | Status status = Status::OK; |
| 244 | if (mInitFail || mClosed) { |
| 245 | ALOGI("%s: session initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed); |
| 246 | status = Status::INTERNAL_ERROR; |
| 247 | } |
| 248 | return status; |
| 249 | } |
| 250 | |
| 251 | ExternalCameraDeviceSession::~ExternalCameraDeviceSession() { |
| 252 | if (!isClosed()) { |
| 253 | ALOGE("ExternalCameraDeviceSession deleted before close!"); |
Tang Lee | 65382f6 | 2023-08-01 18:23:07 +0800 | [diff] [blame] | 254 | closeImpl(); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 255 | } |
| 256 | } |
| 257 | |
| 258 | ScopedAStatus ExternalCameraDeviceSession::constructDefaultRequestSettings( |
| 259 | RequestTemplate in_type, CameraMetadata* _aidl_return) { |
| 260 | CameraMetadata emptyMetadata; |
| 261 | Status status = initStatus(); |
| 262 | if (status != Status::OK) { |
| 263 | return fromStatus(status); |
| 264 | } |
| 265 | switch (in_type) { |
| 266 | case RequestTemplate::PREVIEW: |
| 267 | case RequestTemplate::STILL_CAPTURE: |
| 268 | case RequestTemplate::VIDEO_RECORD: |
| 269 | case RequestTemplate::VIDEO_SNAPSHOT: { |
| 270 | *_aidl_return = mDefaultRequests[in_type]; |
| 271 | break; |
| 272 | } |
| 273 | case RequestTemplate::MANUAL: |
| 274 | case RequestTemplate::ZERO_SHUTTER_LAG: |
| 275 | // Don't support MANUAL, ZSL templates |
| 276 | status = Status::ILLEGAL_ARGUMENT; |
| 277 | break; |
| 278 | default: |
| 279 | ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(in_type)); |
| 280 | status = Status::ILLEGAL_ARGUMENT; |
| 281 | break; |
| 282 | } |
| 283 | return fromStatus(status); |
| 284 | } |
| 285 | |
| 286 | ScopedAStatus ExternalCameraDeviceSession::configureStreams( |
| 287 | const StreamConfiguration& in_requestedConfiguration, |
| 288 | std::vector<HalStream>* _aidl_return) { |
| 289 | uint32_t blobBufferSize = 0; |
| 290 | _aidl_return->clear(); |
| 291 | Mutex::Autolock _il(mInterfaceLock); |
| 292 | |
| 293 | Status status = |
| 294 | isStreamCombinationSupported(in_requestedConfiguration, mSupportedFormats, mCfg); |
| 295 | if (status != Status::OK) { |
| 296 | return fromStatus(status); |
| 297 | } |
| 298 | |
| 299 | status = initStatus(); |
| 300 | if (status != Status::OK) { |
| 301 | return fromStatus(status); |
| 302 | } |
| 303 | |
| 304 | { |
| 305 | std::lock_guard<std::mutex> lk(mInflightFramesLock); |
| 306 | if (!mInflightFrames.empty()) { |
| 307 | ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!", |
| 308 | __FUNCTION__, mInflightFrames.size()); |
| 309 | return fromStatus(Status::INTERNAL_ERROR); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | Mutex::Autolock _l(mLock); |
| 314 | { |
| 315 | Mutex::Autolock _cl(mCbsLock); |
| 316 | // Add new streams |
| 317 | for (const auto& stream : in_requestedConfiguration.streams) { |
| 318 | if (mStreamMap.count(stream.id) == 0) { |
| 319 | mStreamMap[stream.id] = stream; |
| 320 | mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{}); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | // Cleanup removed streams |
| 325 | for (auto it = mStreamMap.begin(); it != mStreamMap.end();) { |
| 326 | int id = it->first; |
| 327 | bool found = false; |
| 328 | for (const auto& stream : in_requestedConfiguration.streams) { |
| 329 | if (id == stream.id) { |
| 330 | found = true; |
| 331 | break; |
| 332 | } |
| 333 | } |
| 334 | if (!found) { |
| 335 | // Unmap all buffers of deleted stream |
| 336 | cleanupBuffersLocked(id); |
| 337 | it = mStreamMap.erase(it); |
| 338 | } else { |
| 339 | ++it; |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // Now select a V4L2 format to produce all output streams |
| 345 | float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio; |
| 346 | uint32_t maxDim = 0; |
| 347 | for (const auto& stream : in_requestedConfiguration.streams) { |
| 348 | float aspectRatio = ASPECT_RATIO(stream); |
| 349 | ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height); |
| 350 | if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) || |
| 351 | (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) { |
| 352 | desiredAr = aspectRatio; |
| 353 | } |
| 354 | |
| 355 | // The dimension that's not cropped |
| 356 | uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height; |
| 357 | if (dim > maxDim) { |
| 358 | maxDim = dim; |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // Find the smallest format that matches the desired aspect ratio and is wide/high enough |
| 363 | SupportedV4L2Format v4l2Fmt{.width = 0, .height = 0}; |
| 364 | for (const auto& fmt : mSupportedFormats) { |
| 365 | uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height; |
| 366 | if (dim >= maxDim) { |
| 367 | float aspectRatio = ASPECT_RATIO(fmt); |
| 368 | if (isAspectRatioClose(aspectRatio, desiredAr)) { |
| 369 | v4l2Fmt = fmt; |
| 370 | // since mSupportedFormats is sorted by width then height, the first matching fmt |
| 371 | // will be the smallest one with matching aspect ratio |
| 372 | break; |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | if (v4l2Fmt.width == 0) { |
| 378 | // Cannot find exact good aspect ratio candidate, try to find a close one |
| 379 | for (const auto& fmt : mSupportedFormats) { |
| 380 | uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height; |
| 381 | if (dim >= maxDim) { |
| 382 | float aspectRatio = ASPECT_RATIO(fmt); |
| 383 | if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) || |
| 384 | (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) { |
| 385 | v4l2Fmt = fmt; |
| 386 | break; |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | if (v4l2Fmt.width == 0) { |
| 393 | ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)", |
| 394 | __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height", maxDim, desiredAr); |
| 395 | return fromStatus(Status::ILLEGAL_ARGUMENT); |
| 396 | } |
| 397 | |
| 398 | if (configureV4l2StreamLocked(v4l2Fmt) != 0) { |
| 399 | ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d", v4l2Fmt.fourcc & 0xFF, |
| 400 | (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF, |
| 401 | (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height); |
| 402 | return fromStatus(Status::INTERNAL_ERROR); |
| 403 | } |
| 404 | |
| 405 | Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height}; |
| 406 | Size thumbSize{0, 0}; |
| 407 | camera_metadata_ro_entry entry = |
| 408 | mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES); |
| 409 | for (uint32_t i = 0; i < entry.count; i += 2) { |
| 410 | Size sz{entry.data.i32[i], entry.data.i32[i + 1]}; |
| 411 | if (sz.width * sz.height > thumbSize.width * thumbSize.height) { |
| 412 | thumbSize = sz; |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | if (thumbSize.width * thumbSize.height == 0) { |
| 417 | ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__); |
| 418 | return fromStatus(Status::INTERNAL_ERROR); |
| 419 | } |
| 420 | |
| 421 | mBlobBufferSize = blobBufferSize; |
| 422 | status = mOutputThread->allocateIntermediateBuffers( |
| 423 | v4lSize, mMaxThumbResolution, in_requestedConfiguration.streams, blobBufferSize); |
| 424 | if (status != Status::OK) { |
| 425 | ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__); |
| 426 | return fromStatus(status); |
| 427 | } |
| 428 | |
| 429 | std::vector<HalStream>& out = *_aidl_return; |
| 430 | out.resize(in_requestedConfiguration.streams.size()); |
| 431 | for (size_t i = 0; i < in_requestedConfiguration.streams.size(); i++) { |
| 432 | out[i].overrideDataSpace = in_requestedConfiguration.streams[i].dataSpace; |
| 433 | out[i].id = in_requestedConfiguration.streams[i].id; |
| 434 | // TODO: double check should we add those CAMERA flags |
| 435 | mStreamMap[in_requestedConfiguration.streams[i].id].usage = out[i].producerUsage = |
| 436 | static_cast<BufferUsage>(((int64_t)in_requestedConfiguration.streams[i].usage) | |
| 437 | ((int64_t)BufferUsage::CPU_WRITE_OFTEN) | |
| 438 | ((int64_t)BufferUsage::CAMERA_OUTPUT)); |
| 439 | out[i].consumerUsage = static_cast<BufferUsage>(0); |
| 440 | out[i].maxBuffers = static_cast<int32_t>(mV4L2BufferCount); |
| 441 | |
| 442 | switch (in_requestedConfiguration.streams[i].format) { |
| 443 | case PixelFormat::BLOB: |
| 444 | case PixelFormat::YCBCR_420_888: |
| 445 | case PixelFormat::YV12: // Used by SurfaceTexture |
| 446 | case PixelFormat::Y16: |
| 447 | // No override |
| 448 | out[i].overrideFormat = in_requestedConfiguration.streams[i].format; |
| 449 | break; |
| 450 | case PixelFormat::IMPLEMENTATION_DEFINED: |
| 451 | // Implementation Defined |
| 452 | // This should look at the Stream's dataspace flag to determine the format or leave |
| 453 | // it as is if the rest of the system knows how to handle a private format. To keep |
| 454 | // this HAL generic, this is being overridden to YUV420 |
| 455 | out[i].overrideFormat = PixelFormat::YCBCR_420_888; |
| 456 | // Save overridden format in mStreamMap |
| 457 | mStreamMap[in_requestedConfiguration.streams[i].id].format = out[i].overrideFormat; |
| 458 | break; |
| 459 | default: |
| 460 | ALOGE("%s: unsupported format 0x%x", __FUNCTION__, |
| 461 | in_requestedConfiguration.streams[i].format); |
| 462 | return fromStatus(Status::ILLEGAL_ARGUMENT); |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | mFirstRequest = true; |
| 467 | mLastStreamConfigCounter = in_requestedConfiguration.streamConfigCounter; |
| 468 | return fromStatus(Status::OK); |
| 469 | } |
| 470 | |
| 471 | ScopedAStatus ExternalCameraDeviceSession::flush() { |
| 472 | ATRACE_CALL(); |
| 473 | Mutex::Autolock _il(mInterfaceLock); |
| 474 | Status status = initStatus(); |
| 475 | if (status != Status::OK) { |
| 476 | return fromStatus(status); |
| 477 | } |
| 478 | mOutputThread->flush(); |
| 479 | return fromStatus(Status::OK); |
| 480 | } |
| 481 | |
| 482 | ScopedAStatus ExternalCameraDeviceSession::getCaptureRequestMetadataQueue( |
| 483 | MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) { |
| 484 | Mutex::Autolock _il(mInterfaceLock); |
| 485 | *_aidl_return = mRequestMetadataQueue->dupeDesc(); |
| 486 | return fromStatus(Status::OK); |
| 487 | } |
| 488 | |
| 489 | ScopedAStatus ExternalCameraDeviceSession::getCaptureResultMetadataQueue( |
| 490 | MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) { |
| 491 | Mutex::Autolock _il(mInterfaceLock); |
| 492 | *_aidl_return = mResultMetadataQueue->dupeDesc(); |
| 493 | return fromStatus(Status::OK); |
| 494 | } |
| 495 | |
| 496 | ScopedAStatus ExternalCameraDeviceSession::isReconfigurationRequired( |
| 497 | const CameraMetadata& in_oldSessionParams, const CameraMetadata& in_newSessionParams, |
| 498 | bool* _aidl_return) { |
| 499 | // reconfiguration required if there is any change in the session params |
| 500 | *_aidl_return = in_oldSessionParams != in_newSessionParams; |
| 501 | return fromStatus(Status::OK); |
| 502 | } |
| 503 | |
| 504 | ScopedAStatus ExternalCameraDeviceSession::processCaptureRequest( |
| 505 | const std::vector<CaptureRequest>& in_requests, |
| 506 | const std::vector<BufferCache>& in_cachesToRemove, int32_t* _aidl_return) { |
| 507 | Mutex::Autolock _il(mInterfaceLock); |
| 508 | updateBufferCaches(in_cachesToRemove); |
| 509 | |
| 510 | int32_t& numRequestProcessed = *_aidl_return; |
| 511 | numRequestProcessed = 0; |
| 512 | Status s = Status::OK; |
| 513 | for (size_t i = 0; i < in_requests.size(); i++, numRequestProcessed++) { |
| 514 | s = processOneCaptureRequest(in_requests[i]); |
| 515 | if (s != Status::OK) { |
| 516 | break; |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | return fromStatus(s); |
| 521 | } |
| 522 | |
| 523 | Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) { |
| 524 | ATRACE_CALL(); |
| 525 | Status status = initStatus(); |
| 526 | if (status != Status::OK) { |
| 527 | return status; |
| 528 | } |
| 529 | |
| 530 | if (request.inputBuffer.streamId != -1) { |
| 531 | ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__); |
| 532 | return Status::ILLEGAL_ARGUMENT; |
| 533 | } |
| 534 | |
| 535 | Mutex::Autolock _l(mLock); |
| 536 | if (!mV4l2Streaming) { |
| 537 | ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__); |
| 538 | return Status::INTERNAL_ERROR; |
| 539 | } |
| 540 | |
| 541 | const camera_metadata_t* rawSettings = nullptr; |
| 542 | bool converted; |
| 543 | CameraMetadata settingsFmq; // settings from FMQ |
| 544 | |
| 545 | if (request.fmqSettingsSize > 0) { |
| 546 | // non-blocking read; client must write metadata before calling |
| 547 | // processOneCaptureRequest |
| 548 | settingsFmq.metadata.resize(request.fmqSettingsSize); |
| 549 | bool read = mRequestMetadataQueue->read( |
| 550 | reinterpret_cast<int8_t*>(settingsFmq.metadata.data()), request.fmqSettingsSize); |
| 551 | if (read) { |
| 552 | converted = convertFromAidl(settingsFmq, &rawSettings); |
| 553 | } else { |
| 554 | ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__); |
| 555 | converted = false; |
| 556 | } |
| 557 | } else { |
| 558 | converted = convertFromAidl(request.settings, &rawSettings); |
| 559 | } |
| 560 | |
| 561 | if (converted && rawSettings != nullptr) { |
| 562 | mLatestReqSetting = rawSettings; |
| 563 | } |
| 564 | |
| 565 | if (!converted) { |
| 566 | ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__); |
| 567 | return Status::ILLEGAL_ARGUMENT; |
| 568 | } |
| 569 | |
| 570 | if (mFirstRequest && rawSettings == nullptr) { |
| 571 | ALOGE("%s: capture request settings must not be null for first request!", __FUNCTION__); |
| 572 | return Status::ILLEGAL_ARGUMENT; |
| 573 | } |
| 574 | |
| 575 | std::vector<buffer_handle_t*> allBufPtrs; |
| 576 | std::vector<int> allFences; |
| 577 | size_t numOutputBufs = request.outputBuffers.size(); |
| 578 | |
| 579 | if (numOutputBufs == 0) { |
| 580 | ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__); |
| 581 | return Status::ILLEGAL_ARGUMENT; |
| 582 | } |
| 583 | |
| 584 | camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE); |
| 585 | if (fpsRange.count == 2) { |
| 586 | double requestFpsMax = fpsRange.data.i32[1]; |
| 587 | double closestFps = 0.0; |
| 588 | double fpsError = 1000.0; |
| 589 | bool fpsSupported = false; |
| 590 | for (const auto& fr : mV4l2StreamingFmt.frameRates) { |
| 591 | double f = fr.getFramesPerSecond(); |
| 592 | if (std::fabs(requestFpsMax - f) < 1.0) { |
| 593 | fpsSupported = true; |
| 594 | break; |
| 595 | } |
| 596 | if (std::fabs(requestFpsMax - f) < fpsError) { |
| 597 | fpsError = std::fabs(requestFpsMax - f); |
| 598 | closestFps = f; |
| 599 | } |
| 600 | } |
| 601 | if (!fpsSupported) { |
| 602 | /* This can happen in a few scenarios: |
| 603 | * 1. The application is sending an FPS range not supported by the configured outputs. |
| 604 | * 2. The application is sending a valid FPS range for all configured outputs, but |
| 605 | * the selected V4L2 size can only run at slower speed. This should be very rare |
| 606 | * though: for this to happen a sensor needs to support at least 3 different aspect |
| 607 | * ratio outputs, and when (at least) two outputs are both not the main aspect ratio |
| 608 | * of the webcam, a third size that's larger might be picked and runs into this |
| 609 | * issue. |
| 610 | */ |
| 611 | ALOGW("%s: cannot reach fps %d! Will do %f instead", __FUNCTION__, fpsRange.data.i32[1], |
| 612 | closestFps); |
| 613 | requestFpsMax = closestFps; |
| 614 | } |
| 615 | |
| 616 | if (requestFpsMax != mV4l2StreamingFps) { |
| 617 | { |
| 618 | std::unique_lock<std::mutex> lk(mV4l2BufferLock); |
| 619 | while (mNumDequeuedV4l2Buffers != 0) { |
| 620 | // Wait until pipeline is idle before reconfigure stream |
| 621 | int waitRet = waitForV4L2BufferReturnLocked(lk); |
| 622 | if (waitRet != 0) { |
| 623 | ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__); |
| 624 | return Status::INTERNAL_ERROR; |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax); |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | status = importRequestLocked(request, allBufPtrs, allFences); |
| 633 | if (status != Status::OK) { |
| 634 | return status; |
| 635 | } |
| 636 | |
| 637 | nsecs_t shutterTs = 0; |
| 638 | std::unique_ptr<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs); |
| 639 | if (frameIn == nullptr) { |
| 640 | ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__); |
| 641 | return Status::INTERNAL_ERROR; |
| 642 | } |
| 643 | |
| 644 | std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>(); |
| 645 | halReq->frameNumber = request.frameNumber; |
| 646 | halReq->setting = mLatestReqSetting; |
| 647 | halReq->frameIn = std::move(frameIn); |
| 648 | halReq->shutterTs = shutterTs; |
| 649 | halReq->buffers.resize(numOutputBufs); |
| 650 | for (size_t i = 0; i < numOutputBufs; i++) { |
| 651 | HalStreamBuffer& halBuf = halReq->buffers[i]; |
| 652 | int streamId = halBuf.streamId = request.outputBuffers[i].streamId; |
| 653 | halBuf.bufferId = request.outputBuffers[i].bufferId; |
| 654 | const Stream& stream = mStreamMap[streamId]; |
| 655 | halBuf.width = stream.width; |
| 656 | halBuf.height = stream.height; |
| 657 | halBuf.format = stream.format; |
| 658 | halBuf.usage = stream.usage; |
| 659 | halBuf.bufPtr = allBufPtrs[i]; |
| 660 | halBuf.acquireFence = allFences[i]; |
| 661 | halBuf.fenceTimeout = false; |
| 662 | } |
| 663 | { |
| 664 | std::lock_guard<std::mutex> lk(mInflightFramesLock); |
| 665 | mInflightFrames.insert(halReq->frameNumber); |
| 666 | } |
| 667 | // Send request to OutputThread for the rest of processing |
| 668 | mOutputThread->submitRequest(halReq); |
| 669 | mFirstRequest = false; |
| 670 | return Status::OK; |
| 671 | } |
| 672 | |
| 673 | ScopedAStatus ExternalCameraDeviceSession::signalStreamFlush( |
| 674 | const std::vector<int32_t>& /*in_streamIds*/, int32_t in_streamConfigCounter) { |
| 675 | { |
| 676 | Mutex::Autolock _l(mLock); |
| 677 | if (in_streamConfigCounter < mLastStreamConfigCounter) { |
| 678 | // stale call. new streams have been configured since this call was issued. |
| 679 | // Do nothing. |
| 680 | return fromStatus(Status::OK); |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | // TODO: implement if needed. |
| 685 | return fromStatus(Status::OK); |
| 686 | } |
| 687 | |
| 688 | ScopedAStatus ExternalCameraDeviceSession::switchToOffline( |
| 689 | const std::vector<int32_t>& in_streamsToKeep, |
| 690 | CameraOfflineSessionInfo* out_offlineSessionInfo, |
| 691 | std::shared_ptr<ICameraOfflineSession>* _aidl_return) { |
| 692 | std::vector<NotifyMsg> msgs; |
| 693 | std::vector<CaptureResult> results; |
| 694 | CameraOfflineSessionInfo info; |
| 695 | std::shared_ptr<ICameraOfflineSession> session; |
| 696 | Status st = switchToOffline(in_streamsToKeep, &msgs, &results, &info, &session); |
| 697 | |
| 698 | mCallback->notify(msgs); |
| 699 | invokeProcessCaptureResultCallback(results, /* tryWriteFmq= */ true); |
| 700 | freeReleaseFences(results); |
| 701 | |
| 702 | // setup return values |
| 703 | *out_offlineSessionInfo = info; |
| 704 | *_aidl_return = session; |
| 705 | return fromStatus(st); |
| 706 | } |
| 707 | |
| 708 | Status ExternalCameraDeviceSession::switchToOffline( |
| 709 | const std::vector<int32_t>& offlineStreams, std::vector<NotifyMsg>* msgs, |
| 710 | std::vector<CaptureResult>* results, CameraOfflineSessionInfo* info, |
| 711 | std::shared_ptr<ICameraOfflineSession>* session) { |
| 712 | ATRACE_CALL(); |
| 713 | if (offlineStreams.size() > 1) { |
| 714 | ALOGE("%s: more than one offline stream is not supported", __FUNCTION__); |
| 715 | return Status::ILLEGAL_ARGUMENT; |
| 716 | } |
| 717 | |
Greg Kaiser | 9b77fd1 | 2022-12-05 17:06:02 -0800 | [diff] [blame] | 718 | if (msgs == nullptr || results == nullptr || info == nullptr || session == nullptr) { |
| 719 | ALOGE("%s, output arguments (%p, %p, %p, %p) must not be null", __FUNCTION__, msgs, results, |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 720 | info, session); |
| 721 | } |
| 722 | |
| 723 | Mutex::Autolock _il(mInterfaceLock); |
| 724 | Status status = initStatus(); |
| 725 | if (status != Status::OK) { |
| 726 | return status; |
| 727 | } |
| 728 | |
| 729 | Mutex::Autolock _l(mLock); |
| 730 | for (auto streamId : offlineStreams) { |
| 731 | if (!supportOfflineLocked(streamId)) { |
| 732 | return Status::ILLEGAL_ARGUMENT; |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | // pause output thread and get all remaining inflight requests |
| 737 | auto remainingReqs = mOutputThread->switchToOffline(); |
| 738 | std::vector<std::shared_ptr<HalRequest>> halReqs; |
| 739 | |
| 740 | // Send out buffer/request error for remaining requests and filter requests |
| 741 | // to be handled in offline mode |
| 742 | for (auto& halReq : remainingReqs) { |
| 743 | bool dropReq = canDropRequest(offlineStreams, halReq); |
| 744 | if (dropReq) { |
| 745 | // Request is dropped completely. Just send request error and |
| 746 | // there is no need to send the request to offline session |
| 747 | processCaptureRequestError(halReq, msgs, results); |
| 748 | continue; |
| 749 | } |
| 750 | |
| 751 | // All requests reach here must have at least one offline stream output |
| 752 | NotifyMsg shutter; |
| 753 | aidl::android::hardware::camera::device::ShutterMsg shutterMsg = { |
| 754 | .frameNumber = static_cast<int32_t>(halReq->frameNumber), |
| 755 | .timestamp = halReq->shutterTs}; |
| 756 | shutter.set<NotifyMsg::Tag::shutter>(shutterMsg); |
| 757 | msgs->push_back(shutter); |
| 758 | |
| 759 | std::vector<HalStreamBuffer> offlineBuffers; |
| 760 | for (const auto& buffer : halReq->buffers) { |
| 761 | bool dropBuffer = true; |
| 762 | for (auto offlineStreamId : offlineStreams) { |
| 763 | if (buffer.streamId == offlineStreamId) { |
| 764 | dropBuffer = false; |
| 765 | break; |
| 766 | } |
| 767 | } |
| 768 | if (dropBuffer) { |
| 769 | aidl::android::hardware::camera::device::ErrorMsg errorMsg = { |
| 770 | .frameNumber = static_cast<int32_t>(halReq->frameNumber), |
| 771 | .errorStreamId = buffer.streamId, |
| 772 | .errorCode = ErrorCode::ERROR_BUFFER}; |
| 773 | |
| 774 | NotifyMsg error; |
| 775 | error.set<NotifyMsg::Tag::error>(errorMsg); |
| 776 | msgs->push_back(error); |
| 777 | |
| 778 | results->push_back({ |
| 779 | .frameNumber = static_cast<int32_t>(halReq->frameNumber), |
| 780 | .outputBuffers = {}, |
| 781 | .inputBuffer = {.streamId = -1}, |
| 782 | .partialResult = 0, // buffer only result |
| 783 | }); |
| 784 | |
| 785 | CaptureResult& result = results->back(); |
| 786 | result.outputBuffers.resize(1); |
| 787 | StreamBuffer& outputBuffer = result.outputBuffers[0]; |
| 788 | outputBuffer.streamId = buffer.streamId; |
| 789 | outputBuffer.bufferId = buffer.bufferId; |
| 790 | outputBuffer.status = BufferStatus::ERROR; |
| 791 | if (buffer.acquireFence >= 0) { |
Avichal Rakesh | 1fa4142 | 2023-11-03 15:33:36 -0700 | [diff] [blame] | 792 | outputBuffer.releaseFence.fds.resize(1); |
| 793 | outputBuffer.releaseFence.fds.at(0).set(buffer.acquireFence); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 794 | } |
| 795 | } else { |
| 796 | offlineBuffers.push_back(buffer); |
| 797 | } |
| 798 | } |
| 799 | halReq->buffers = offlineBuffers; |
| 800 | halReqs.push_back(halReq); |
| 801 | } |
| 802 | |
| 803 | // convert hal requests to offline request |
| 804 | std::deque<std::shared_ptr<HalRequest>> offlineReqs(halReqs.size()); |
| 805 | size_t i = 0; |
| 806 | for (auto& v4lReq : halReqs) { |
| 807 | offlineReqs[i] = std::make_shared<HalRequest>(); |
| 808 | offlineReqs[i]->frameNumber = v4lReq->frameNumber; |
| 809 | offlineReqs[i]->setting = v4lReq->setting; |
| 810 | offlineReqs[i]->shutterTs = v4lReq->shutterTs; |
| 811 | offlineReqs[i]->buffers = v4lReq->buffers; |
| 812 | std::shared_ptr<V4L2Frame> v4l2Frame(static_cast<V4L2Frame*>(v4lReq->frameIn.get())); |
| 813 | offlineReqs[i]->frameIn = std::make_shared<AllocatedV4L2Frame>(v4l2Frame); |
| 814 | i++; |
| 815 | // enqueue V4L2 frame |
| 816 | enqueueV4l2Frame(v4l2Frame); |
| 817 | } |
| 818 | |
| 819 | // Collect buffer caches/streams |
| 820 | std::vector<Stream> streamInfos(offlineStreams.size()); |
| 821 | std::map<int, CirculatingBuffers> circulatingBuffers; |
| 822 | { |
| 823 | Mutex::Autolock _cbsl(mCbsLock); |
| 824 | for (auto streamId : offlineStreams) { |
| 825 | circulatingBuffers[streamId] = mCirculatingBuffers.at(streamId); |
| 826 | mCirculatingBuffers.erase(streamId); |
| 827 | streamInfos.push_back(mStreamMap.at(streamId)); |
| 828 | mStreamMap.erase(streamId); |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | fillOfflineSessionInfo(offlineStreams, offlineReqs, circulatingBuffers, info); |
| 833 | // create the offline session object |
| 834 | bool afTrigger; |
| 835 | { |
| 836 | std::lock_guard<std::mutex> _lk(mAfTriggerLock); |
| 837 | afTrigger = mAfTrigger; |
| 838 | } |
| 839 | |
| 840 | std::shared_ptr<ExternalCameraOfflineSession> sessionImpl = |
| 841 | ndk::SharedRefBase::make<ExternalCameraOfflineSession>( |
| 842 | mCroppingType, mCameraCharacteristics, mCameraId, mExifMake, mExifModel, |
| 843 | mBlobBufferSize, afTrigger, streamInfos, offlineReqs, circulatingBuffers); |
| 844 | |
| 845 | bool initFailed = sessionImpl->initialize(); |
| 846 | if (initFailed) { |
| 847 | ALOGE("%s: offline session initialize failed!", __FUNCTION__); |
| 848 | return Status::INTERNAL_ERROR; |
| 849 | } |
| 850 | |
| 851 | // cleanup stream and buffer caches |
| 852 | { |
| 853 | Mutex::Autolock _cbsl(mCbsLock); |
| 854 | for (auto pair : mStreamMap) { |
| 855 | cleanupBuffersLocked(/*Stream ID*/ pair.first); |
| 856 | } |
| 857 | mCirculatingBuffers.clear(); |
| 858 | } |
| 859 | mStreamMap.clear(); |
| 860 | |
| 861 | // update inflight records |
| 862 | { |
| 863 | std::lock_guard<std::mutex> _lk(mInflightFramesLock); |
| 864 | mInflightFrames.clear(); |
| 865 | } |
| 866 | |
| 867 | // stop v4l2 streaming |
| 868 | if (v4l2StreamOffLocked() != 0) { |
| 869 | ALOGE("%s: stop V4L2 streaming failed!", __FUNCTION__); |
| 870 | return Status::INTERNAL_ERROR; |
| 871 | } |
| 872 | |
| 873 | // No need to return session if there is no offline requests left |
| 874 | if (!offlineReqs.empty()) { |
| 875 | *session = sessionImpl; |
| 876 | } else { |
| 877 | *session = nullptr; |
| 878 | } |
| 879 | |
| 880 | return Status::OK; |
| 881 | } |
| 882 | |
| 883 | #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) |
| 884 | #define UPDATE(md, tag, data, size) \ |
| 885 | do { \ |
| 886 | if ((md).update((tag), (data), (size))) { \ |
| 887 | ALOGE("Update " #tag " failed!"); \ |
| 888 | return BAD_VALUE; \ |
| 889 | } \ |
| 890 | } while (0) |
| 891 | |
| 892 | status_t ExternalCameraDeviceSession::initDefaultRequests() { |
| 893 | common::V1_0::helper::CameraMetadata md; |
| 894 | |
| 895 | const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF; |
| 896 | UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1); |
| 897 | |
| 898 | const int32_t exposureCompensation = 0; |
| 899 | UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1); |
| 900 | |
| 901 | const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF; |
| 902 | UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1); |
| 903 | |
| 904 | const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO; |
| 905 | UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1); |
| 906 | |
| 907 | const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON; |
| 908 | UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1); |
| 909 | |
| 910 | const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE; |
| 911 | UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1); |
| 912 | |
| 913 | const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO; |
| 914 | UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1); |
| 915 | |
| 916 | const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE; |
| 917 | UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1); |
| 918 | |
| 919 | const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED; |
| 920 | UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1); |
| 921 | |
| 922 | const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF; |
| 923 | UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1); |
| 924 | |
| 925 | const uint8_t flashMode = ANDROID_FLASH_MODE_OFF; |
| 926 | UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1); |
| 927 | |
| 928 | const int32_t thumbnailSize[] = {240, 180}; |
| 929 | UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2); |
| 930 | |
| 931 | const uint8_t jpegQuality = 90; |
| 932 | UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1); |
| 933 | UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1); |
| 934 | |
| 935 | const int32_t jpegOrientation = 0; |
| 936 | UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1); |
| 937 | |
| 938 | const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF; |
| 939 | UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1); |
| 940 | |
| 941 | const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF; |
| 942 | UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1); |
| 943 | |
| 944 | const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF; |
| 945 | UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1); |
| 946 | |
| 947 | const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF; |
| 948 | UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1); |
| 949 | |
| 950 | const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF; |
| 951 | UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1); |
| 952 | |
| 953 | bool support30Fps = false; |
| 954 | int32_t maxFps = std::numeric_limits<int32_t>::min(); |
| 955 | for (const auto& supportedFormat : mSupportedFormats) { |
| 956 | for (const auto& fr : supportedFormat.frameRates) { |
| 957 | int32_t framerateInt = static_cast<int32_t>(fr.getFramesPerSecond()); |
| 958 | if (maxFps < framerateInt) { |
| 959 | maxFps = framerateInt; |
| 960 | } |
| 961 | if (framerateInt == 30) { |
| 962 | support30Fps = true; |
| 963 | break; |
| 964 | } |
| 965 | } |
| 966 | if (support30Fps) { |
| 967 | break; |
| 968 | } |
| 969 | } |
| 970 | |
| 971 | int32_t defaultFramerate = support30Fps ? 30 : maxFps; |
| 972 | int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate}; |
| 973 | UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange)); |
| 974 | |
| 975 | uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO; |
| 976 | UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1); |
| 977 | |
| 978 | const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO; |
| 979 | UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1); |
| 980 | |
| 981 | for (const auto& type : ndk::enum_range<RequestTemplate>()) { |
| 982 | common::V1_0::helper::CameraMetadata mdCopy = md; |
| 983 | uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW; |
| 984 | switch (type) { |
| 985 | case RequestTemplate::PREVIEW: |
| 986 | intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW; |
| 987 | break; |
| 988 | case RequestTemplate::STILL_CAPTURE: |
| 989 | intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE; |
| 990 | break; |
| 991 | case RequestTemplate::VIDEO_RECORD: |
| 992 | intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD; |
| 993 | break; |
| 994 | case RequestTemplate::VIDEO_SNAPSHOT: |
| 995 | intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT; |
| 996 | break; |
| 997 | default: |
| 998 | ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type); |
| 999 | continue; |
| 1000 | } |
| 1001 | UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1); |
| 1002 | camera_metadata_t* mdPtr = mdCopy.release(); |
| 1003 | uint8_t* rawMd = reinterpret_cast<uint8_t*>(mdPtr); |
| 1004 | CameraMetadata aidlMd; |
| 1005 | aidlMd.metadata.assign(rawMd, rawMd + get_camera_metadata_size(mdPtr)); |
| 1006 | mDefaultRequests[type] = aidlMd; |
| 1007 | free_camera_metadata(mdPtr); |
| 1008 | } |
| 1009 | return OK; |
| 1010 | } |
| 1011 | |
| 1012 | status_t ExternalCameraDeviceSession::fillCaptureResult(common::V1_0::helper::CameraMetadata& md, |
| 1013 | nsecs_t timestamp) { |
| 1014 | bool afTrigger = false; |
| 1015 | { |
| 1016 | std::lock_guard<std::mutex> lk(mAfTriggerLock); |
| 1017 | afTrigger = mAfTrigger; |
| 1018 | if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) { |
| 1019 | camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER); |
| 1020 | if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) { |
| 1021 | mAfTrigger = afTrigger = true; |
| 1022 | } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) { |
| 1023 | mAfTrigger = afTrigger = false; |
| 1024 | } |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | // For USB camera, the USB camera handles everything and we don't have control |
| 1029 | // over AF. We only simply fake the AF metadata based on the request |
| 1030 | // received here. |
| 1031 | uint8_t afState; |
| 1032 | if (afTrigger) { |
| 1033 | afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED; |
| 1034 | } else { |
| 1035 | afState = ANDROID_CONTROL_AF_STATE_INACTIVE; |
| 1036 | } |
| 1037 | UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1); |
| 1038 | |
| 1039 | camera_metadata_ro_entry activeArraySize = |
| 1040 | mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE); |
| 1041 | |
| 1042 | return fillCaptureResultCommon(md, timestamp, activeArraySize); |
| 1043 | } |
| 1044 | |
| 1045 | int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt, |
| 1046 | double requestFps) { |
| 1047 | ATRACE_CALL(); |
| 1048 | int ret = v4l2StreamOffLocked(); |
| 1049 | if (ret != OK) { |
| 1050 | ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret); |
| 1051 | return ret; |
| 1052 | } |
| 1053 | |
| 1054 | // VIDIOC_S_FMT w/h/fmt |
| 1055 | v4l2_format fmt; |
| 1056 | fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1057 | fmt.fmt.pix.width = v4l2Fmt.width; |
| 1058 | fmt.fmt.pix.height = v4l2Fmt.height; |
| 1059 | fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc; |
| 1060 | |
| 1061 | { |
| 1062 | int numAttempt = 0; |
| 1063 | do { |
| 1064 | ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt)); |
| 1065 | if (numAttempt == MAX_RETRY) { |
| 1066 | break; |
| 1067 | } |
| 1068 | numAttempt++; |
| 1069 | if (ret < 0) { |
| 1070 | ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__); |
| 1071 | usleep(IOCTL_RETRY_SLEEP_US); // sleep and try again |
| 1072 | } |
| 1073 | } while (ret < 0); |
| 1074 | if (ret < 0) { |
| 1075 | ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno)); |
| 1076 | return -errno; |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height || |
| 1081 | v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) { |
| 1082 | ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__, |
| 1083 | v4l2Fmt.fourcc & 0xFF, (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF, |
| 1084 | (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height, |
| 1085 | fmt.fmt.pix.pixelformat & 0xFF, (fmt.fmt.pix.pixelformat >> 8) & 0xFF, |
| 1086 | (fmt.fmt.pix.pixelformat >> 16) & 0xFF, (fmt.fmt.pix.pixelformat >> 24) & 0xFF, |
| 1087 | fmt.fmt.pix.width, fmt.fmt.pix.height); |
| 1088 | return -EINVAL; |
| 1089 | } |
| 1090 | |
| 1091 | uint32_t bufferSize = fmt.fmt.pix.sizeimage; |
| 1092 | ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize); |
| 1093 | uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height; |
| 1094 | if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) { |
| 1095 | ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__, |
| 1096 | bufferSize, expectedMaxBufferSize); |
| 1097 | return -EINVAL; |
| 1098 | } |
| 1099 | mMaxV4L2BufferSize = bufferSize; |
| 1100 | |
| 1101 | const double kDefaultFps = 30.0; |
| 1102 | double fps = std::numeric_limits<double>::max(); |
| 1103 | if (requestFps != 0.0) { |
| 1104 | fps = requestFps; |
| 1105 | } else { |
| 1106 | double maxFps = -1.0; |
| 1107 | // Try to pick the slowest fps that is at least 30 |
| 1108 | for (const auto& fr : v4l2Fmt.frameRates) { |
| 1109 | double f = fr.getFramesPerSecond(); |
| 1110 | if (maxFps < f) { |
| 1111 | maxFps = f; |
| 1112 | } |
| 1113 | if (f >= kDefaultFps && f < fps) { |
| 1114 | fps = f; |
| 1115 | } |
| 1116 | } |
| 1117 | // No fps > 30 found, use the highest fps available within supported formats. |
| 1118 | if (fps == std::numeric_limits<double>::max()) { |
| 1119 | fps = maxFps; |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | int fpsRet = setV4l2FpsLocked(fps); |
| 1124 | if (fpsRet != 0 && fpsRet != -EINVAL) { |
| 1125 | ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet)); |
| 1126 | return fpsRet; |
| 1127 | } |
| 1128 | |
| 1129 | uint32_t v4lBufferCount = (fps >= kDefaultFps) ? mCfg.numVideoBuffers : mCfg.numStillBuffers; |
| 1130 | |
| 1131 | // VIDIOC_REQBUFS: create buffers |
| 1132 | v4l2_requestbuffers req_buffers{}; |
| 1133 | req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1134 | req_buffers.memory = V4L2_MEMORY_MMAP; |
| 1135 | req_buffers.count = v4lBufferCount; |
| 1136 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) { |
| 1137 | ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno)); |
| 1138 | return -errno; |
| 1139 | } |
| 1140 | |
| 1141 | // Driver can indeed return more buffer if it needs more to operate |
| 1142 | if (req_buffers.count < v4lBufferCount) { |
| 1143 | ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead", __FUNCTION__, |
| 1144 | v4lBufferCount, req_buffers.count); |
| 1145 | return NO_MEMORY; |
| 1146 | } |
| 1147 | |
| 1148 | // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd |
| 1149 | // VIDIOC_QBUF: send buffer to driver |
| 1150 | mV4L2BufferCount = req_buffers.count; |
| 1151 | for (uint32_t i = 0; i < req_buffers.count; i++) { |
| 1152 | v4l2_buffer buffer = { |
| 1153 | .index = i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP}; |
| 1154 | |
| 1155 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) { |
| 1156 | ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno)); |
| 1157 | return -errno; |
| 1158 | } |
| 1159 | |
| 1160 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) { |
| 1161 | ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno)); |
| 1162 | return -errno; |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | { |
| 1167 | // VIDIOC_STREAMON: start streaming |
| 1168 | v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1169 | int numAttempt = 0; |
| 1170 | do { |
| 1171 | ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)); |
| 1172 | if (numAttempt == MAX_RETRY) { |
| 1173 | break; |
| 1174 | } |
| 1175 | if (ret < 0) { |
| 1176 | ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__); |
| 1177 | usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again |
| 1178 | } |
| 1179 | } while (ret < 0); |
| 1180 | |
| 1181 | if (ret < 0) { |
| 1182 | ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno)); |
| 1183 | return -errno; |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | // Swallow first few frames after streamOn to account for bad frames from some devices |
| 1188 | for (int i = 0; i < kBadFramesAfterStreamOn; i++) { |
| 1189 | v4l2_buffer buffer{}; |
| 1190 | buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1191 | buffer.memory = V4L2_MEMORY_MMAP; |
| 1192 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) { |
| 1193 | ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno)); |
| 1194 | return -errno; |
| 1195 | } |
| 1196 | |
| 1197 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) { |
| 1198 | ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno)); |
| 1199 | return -errno; |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | ALOGI("%s: start V4L2 streaming %dx%d@%ffps", __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps); |
| 1204 | mV4l2StreamingFmt = v4l2Fmt; |
| 1205 | mV4l2Streaming = true; |
| 1206 | return OK; |
| 1207 | } |
| 1208 | |
| 1209 | std::unique_ptr<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(nsecs_t* shutterTs) { |
| 1210 | ATRACE_CALL(); |
| 1211 | std::unique_ptr<V4L2Frame> ret = nullptr; |
| 1212 | if (shutterTs == nullptr) { |
| 1213 | ALOGE("%s: shutterTs must not be null!", __FUNCTION__); |
| 1214 | return ret; |
| 1215 | } |
| 1216 | |
| 1217 | { |
| 1218 | std::unique_lock<std::mutex> lk(mV4l2BufferLock); |
| 1219 | if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) { |
| 1220 | int waitRet = waitForV4L2BufferReturnLocked(lk); |
| 1221 | if (waitRet != 0) { |
| 1222 | return ret; |
| 1223 | } |
| 1224 | } |
| 1225 | } |
| 1226 | |
| 1227 | ATRACE_BEGIN("VIDIOC_DQBUF"); |
| 1228 | v4l2_buffer buffer{}; |
| 1229 | buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1230 | buffer.memory = V4L2_MEMORY_MMAP; |
| 1231 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) { |
| 1232 | ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno)); |
| 1233 | return ret; |
| 1234 | } |
| 1235 | ATRACE_END(); |
| 1236 | |
| 1237 | if (buffer.index >= mV4L2BufferCount) { |
| 1238 | ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index); |
| 1239 | return ret; |
| 1240 | } |
| 1241 | |
| 1242 | if (buffer.flags & V4L2_BUF_FLAG_ERROR) { |
| 1243 | ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags); |
| 1244 | // TODO: try to dequeue again |
| 1245 | } |
| 1246 | |
| 1247 | if (buffer.bytesused > mMaxV4L2BufferSize) { |
| 1248 | ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused, |
| 1249 | mMaxV4L2BufferSize); |
| 1250 | return ret; |
| 1251 | } |
| 1252 | |
| 1253 | if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) { |
| 1254 | // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but |
| 1255 | // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now |
| 1256 | *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec) * 1000000000LL + |
| 1257 | buffer.timestamp.tv_usec * 1000LL; |
| 1258 | } else { |
| 1259 | *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC); |
| 1260 | } |
| 1261 | |
| 1262 | { |
| 1263 | std::lock_guard<std::mutex> lk(mV4l2BufferLock); |
| 1264 | mNumDequeuedV4l2Buffers++; |
| 1265 | } |
| 1266 | |
| 1267 | return std::make_unique<V4L2Frame>(mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, |
| 1268 | mV4l2StreamingFmt.fourcc, buffer.index, mV4l2Fd.get(), |
| 1269 | buffer.bytesused, buffer.m.offset); |
| 1270 | } |
| 1271 | |
| 1272 | void ExternalCameraDeviceSession::enqueueV4l2Frame(const std::shared_ptr<V4L2Frame>& frame) { |
| 1273 | ATRACE_CALL(); |
| 1274 | frame->unmap(); |
| 1275 | ATRACE_BEGIN("VIDIOC_QBUF"); |
| 1276 | v4l2_buffer buffer{}; |
| 1277 | buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1278 | buffer.memory = V4L2_MEMORY_MMAP; |
| 1279 | buffer.index = frame->mBufferIndex; |
| 1280 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) { |
| 1281 | ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno)); |
| 1282 | return; |
| 1283 | } |
| 1284 | ATRACE_END(); |
| 1285 | |
| 1286 | { |
| 1287 | std::lock_guard<std::mutex> lk(mV4l2BufferLock); |
| 1288 | mNumDequeuedV4l2Buffers--; |
| 1289 | } |
| 1290 | mV4L2BufferReturned.notify_one(); |
| 1291 | } |
| 1292 | |
| 1293 | bool ExternalCameraDeviceSession::isSupported( |
| 1294 | const Stream& stream, const std::vector<SupportedV4L2Format>& supportedFormats, |
| 1295 | const ExternalCameraConfig& devCfg) { |
| 1296 | Dataspace ds = stream.dataSpace; |
| 1297 | PixelFormat fmt = stream.format; |
| 1298 | uint32_t width = stream.width; |
| 1299 | uint32_t height = stream.height; |
| 1300 | // TODO: check usage flags |
| 1301 | |
| 1302 | if (stream.streamType != StreamType::OUTPUT) { |
| 1303 | ALOGE("%s: does not support non-output stream type", __FUNCTION__); |
| 1304 | return false; |
| 1305 | } |
| 1306 | |
| 1307 | if (stream.rotation != StreamRotation::ROTATION_0) { |
| 1308 | ALOGE("%s: does not support stream rotation", __FUNCTION__); |
| 1309 | return false; |
| 1310 | } |
| 1311 | |
| 1312 | switch (fmt) { |
| 1313 | case PixelFormat::BLOB: |
| 1314 | if (ds != Dataspace::JFIF) { |
| 1315 | ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds); |
| 1316 | return false; |
| 1317 | } |
| 1318 | break; |
| 1319 | case PixelFormat::IMPLEMENTATION_DEFINED: |
| 1320 | case PixelFormat::YCBCR_420_888: |
| 1321 | case PixelFormat::YV12: |
| 1322 | // TODO: check what dataspace we can support here. |
| 1323 | // intentional no-ops. |
| 1324 | break; |
| 1325 | case PixelFormat::Y16: |
| 1326 | if (!devCfg.depthEnabled) { |
| 1327 | ALOGI("%s: Depth is not Enabled", __FUNCTION__); |
| 1328 | return false; |
| 1329 | } |
| 1330 | if (!(static_cast<int32_t>(ds) & static_cast<int32_t>(Dataspace::DEPTH))) { |
| 1331 | ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__); |
| 1332 | return false; |
| 1333 | } |
| 1334 | break; |
| 1335 | default: |
| 1336 | ALOGI("%s: does not support format %x", __FUNCTION__, fmt); |
| 1337 | return false; |
| 1338 | } |
| 1339 | |
| 1340 | // Assume we can convert any V4L2 format to any of supported output format for now, i.e. |
| 1341 | // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format |
| 1342 | // in the futrue. |
| 1343 | for (const auto& v4l2Fmt : supportedFormats) { |
| 1344 | if (width == v4l2Fmt.width && height == v4l2Fmt.height) { |
| 1345 | return true; |
| 1346 | } |
| 1347 | } |
| 1348 | ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height); |
| 1349 | return false; |
| 1350 | } |
| 1351 | |
| 1352 | Status ExternalCameraDeviceSession::importRequestLocked(const CaptureRequest& request, |
| 1353 | std::vector<buffer_handle_t*>& allBufPtrs, |
| 1354 | std::vector<int>& allFences) { |
| 1355 | return importRequestLockedImpl(request, allBufPtrs, allFences); |
| 1356 | } |
| 1357 | |
| 1358 | Status ExternalCameraDeviceSession::importRequestLockedImpl( |
| 1359 | const CaptureRequest& request, std::vector<buffer_handle_t*>& allBufPtrs, |
| 1360 | std::vector<int>& allFences) { |
| 1361 | size_t numOutputBufs = request.outputBuffers.size(); |
| 1362 | size_t numBufs = numOutputBufs; |
| 1363 | // Validate all I/O buffers |
| 1364 | std::vector<buffer_handle_t> allBufs; |
| 1365 | std::vector<uint64_t> allBufIds; |
| 1366 | allBufs.resize(numBufs); |
| 1367 | allBufIds.resize(numBufs); |
| 1368 | allBufPtrs.resize(numBufs); |
| 1369 | allFences.resize(numBufs); |
| 1370 | std::vector<int32_t> streamIds(numBufs); |
| 1371 | |
| 1372 | for (size_t i = 0; i < numOutputBufs; i++) { |
| 1373 | allBufs[i] = ::android::makeFromAidl(request.outputBuffers[i].buffer); |
| 1374 | allBufIds[i] = request.outputBuffers[i].bufferId; |
| 1375 | allBufPtrs[i] = &allBufs[i]; |
| 1376 | streamIds[i] = request.outputBuffers[i].streamId; |
| 1377 | } |
| 1378 | |
| 1379 | { |
| 1380 | Mutex::Autolock _l(mCbsLock); |
| 1381 | for (size_t i = 0; i < numBufs; i++) { |
| 1382 | Status st = importBufferLocked(streamIds[i], allBufIds[i], allBufs[i], &allBufPtrs[i]); |
| 1383 | if (st != Status::OK) { |
| 1384 | // Detailed error logs printed in importBuffer |
| 1385 | return st; |
| 1386 | } |
| 1387 | } |
| 1388 | } |
| 1389 | |
| 1390 | // All buffers are imported. Now validate output buffer acquire fences |
| 1391 | for (size_t i = 0; i < numOutputBufs; i++) { |
| 1392 | if (!sHandleImporter.importFence( |
| 1393 | ::android::makeFromAidl(request.outputBuffers[i].acquireFence), allFences[i])) { |
| 1394 | ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i); |
| 1395 | cleanupInflightFences(allFences, i); |
| 1396 | return Status::INTERNAL_ERROR; |
| 1397 | } |
| 1398 | } |
| 1399 | return Status::OK; |
| 1400 | } |
| 1401 | |
| 1402 | Status ExternalCameraDeviceSession::importBuffer(int32_t streamId, uint64_t bufId, |
| 1403 | buffer_handle_t buf, |
| 1404 | /*out*/ buffer_handle_t** outBufPtr) { |
| 1405 | Mutex::Autolock _l(mCbsLock); |
| 1406 | return importBufferLocked(streamId, bufId, buf, outBufPtr); |
| 1407 | } |
| 1408 | |
| 1409 | Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId, uint64_t bufId, |
| 1410 | buffer_handle_t buf, |
| 1411 | buffer_handle_t** outBufPtr) { |
| 1412 | return importBufferImpl(mCirculatingBuffers, sHandleImporter, streamId, bufId, buf, outBufPtr); |
| 1413 | } |
| 1414 | |
| 1415 | ScopedAStatus ExternalCameraDeviceSession::close() { |
Tang Lee | 65382f6 | 2023-08-01 18:23:07 +0800 | [diff] [blame] | 1416 | closeImpl(); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1417 | return fromStatus(Status::OK); |
| 1418 | } |
| 1419 | |
Tang Lee | 65382f6 | 2023-08-01 18:23:07 +0800 | [diff] [blame] | 1420 | void ExternalCameraDeviceSession::closeImpl() { |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1421 | Mutex::Autolock _il(mInterfaceLock); |
| 1422 | bool closed = isClosed(); |
| 1423 | if (!closed) { |
Tang Lee | 65382f6 | 2023-08-01 18:23:07 +0800 | [diff] [blame] | 1424 | closeOutputThread(); |
| 1425 | closeBufferRequestThread(); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1426 | |
| 1427 | Mutex::Autolock _l(mLock); |
| 1428 | // free all buffers |
| 1429 | { |
| 1430 | Mutex::Autolock _cbsl(mCbsLock); |
| 1431 | for (auto pair : mStreamMap) { |
| 1432 | cleanupBuffersLocked(/*Stream ID*/ pair.first); |
| 1433 | } |
| 1434 | } |
| 1435 | v4l2StreamOffLocked(); |
| 1436 | ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get()); |
| 1437 | mV4l2Fd.reset(); |
| 1438 | mClosed = true; |
| 1439 | } |
| 1440 | } |
| 1441 | |
| 1442 | bool ExternalCameraDeviceSession::isClosed() { |
| 1443 | Mutex::Autolock _l(mLock); |
| 1444 | return mClosed; |
| 1445 | } |
| 1446 | |
| 1447 | ScopedAStatus ExternalCameraDeviceSession::repeatingRequestEnd( |
| 1448 | int32_t /*in_frameNumber*/, const std::vector<int32_t>& /*in_streamIds*/) { |
| 1449 | // TODO: Figure this one out. |
| 1450 | return fromStatus(Status::OK); |
| 1451 | } |
| 1452 | |
| 1453 | int ExternalCameraDeviceSession::v4l2StreamOffLocked() { |
| 1454 | if (!mV4l2Streaming) { |
| 1455 | return OK; |
| 1456 | } |
| 1457 | |
| 1458 | { |
| 1459 | std::lock_guard<std::mutex> lk(mV4l2BufferLock); |
| 1460 | if (mNumDequeuedV4l2Buffers != 0) { |
| 1461 | ALOGE("%s: there are %zu inflight V4L buffers", __FUNCTION__, mNumDequeuedV4l2Buffers); |
| 1462 | return -1; |
| 1463 | } |
| 1464 | } |
| 1465 | mV4L2BufferCount = 0; |
| 1466 | |
| 1467 | // VIDIOC_STREAMOFF |
| 1468 | v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1469 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) { |
| 1470 | ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno)); |
| 1471 | return -errno; |
| 1472 | } |
| 1473 | |
| 1474 | // VIDIOC_REQBUFS: clear buffers |
| 1475 | v4l2_requestbuffers req_buffers{}; |
| 1476 | req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; |
| 1477 | req_buffers.memory = V4L2_MEMORY_MMAP; |
| 1478 | req_buffers.count = 0; |
| 1479 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) { |
| 1480 | ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno)); |
| 1481 | return -errno; |
| 1482 | } |
| 1483 | |
| 1484 | mV4l2Streaming = false; |
| 1485 | return OK; |
| 1486 | } |
| 1487 | |
| 1488 | int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) { |
| 1489 | // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps |
| 1490 | v4l2_streamparm streamparm = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE}; |
| 1491 | // The following line checks that the driver knows about framerate get/set. |
| 1492 | int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)); |
| 1493 | if (ret != 0) { |
| 1494 | if (errno == -EINVAL) { |
| 1495 | ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__); |
| 1496 | } |
| 1497 | return -errno; |
| 1498 | } |
| 1499 | // Now check if the device is able to accept a capture framerate set. |
| 1500 | if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) { |
| 1501 | ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__); |
| 1502 | return -EINVAL; |
| 1503 | } |
| 1504 | |
| 1505 | // fps is float, approximate by a fraction. |
| 1506 | const int kFrameRatePrecision = 10000; |
| 1507 | streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision; |
| 1508 | streamparm.parm.capture.timeperframe.denominator = (fps * kFrameRatePrecision); |
| 1509 | |
| 1510 | if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) { |
| 1511 | ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno)); |
| 1512 | return -1; |
| 1513 | } |
| 1514 | |
| 1515 | double retFps = streamparm.parm.capture.timeperframe.denominator / |
| 1516 | static_cast<double>(streamparm.parm.capture.timeperframe.numerator); |
| 1517 | if (std::fabs(fps - retFps) > 1.0) { |
| 1518 | ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps); |
| 1519 | return -1; |
| 1520 | } |
| 1521 | mV4l2StreamingFps = fps; |
| 1522 | return 0; |
| 1523 | } |
| 1524 | |
| 1525 | void ExternalCameraDeviceSession::cleanupInflightFences(std::vector<int>& allFences, |
| 1526 | size_t numFences) { |
| 1527 | for (size_t j = 0; j < numFences; j++) { |
| 1528 | sHandleImporter.closeFence(allFences[j]); |
| 1529 | } |
| 1530 | } |
| 1531 | |
| 1532 | void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) { |
| 1533 | for (auto& pair : mCirculatingBuffers.at(id)) { |
| 1534 | sHandleImporter.freeBuffer(pair.second); |
| 1535 | } |
| 1536 | mCirculatingBuffers[id].clear(); |
| 1537 | mCirculatingBuffers.erase(id); |
| 1538 | } |
| 1539 | |
| 1540 | void ExternalCameraDeviceSession::notifyShutter(int32_t frameNumber, nsecs_t shutterTs) { |
| 1541 | NotifyMsg msg; |
| 1542 | msg.set<NotifyMsg::Tag::shutter>(ShutterMsg{ |
| 1543 | .frameNumber = frameNumber, |
| 1544 | .timestamp = shutterTs, |
| 1545 | }); |
| 1546 | mCallback->notify({msg}); |
| 1547 | } |
| 1548 | void ExternalCameraDeviceSession::notifyError(int32_t frameNumber, int32_t streamId, ErrorCode ec) { |
| 1549 | NotifyMsg msg; |
| 1550 | msg.set<NotifyMsg::Tag::error>(ErrorMsg{ |
| 1551 | .frameNumber = frameNumber, |
| 1552 | .errorStreamId = streamId, |
| 1553 | .errorCode = ec, |
| 1554 | }); |
| 1555 | mCallback->notify({msg}); |
| 1556 | } |
| 1557 | |
| 1558 | void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback( |
| 1559 | std::vector<CaptureResult>& results, bool tryWriteFmq) { |
| 1560 | if (mProcessCaptureResultLock.tryLock() != OK) { |
| 1561 | const nsecs_t NS_TO_SECOND = 1000000000; |
| 1562 | ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__); |
| 1563 | if (mProcessCaptureResultLock.timedLock(/* 1s */ NS_TO_SECOND) != OK) { |
| 1564 | ALOGE("%s: cannot acquire lock in 1s, cannot proceed", __FUNCTION__); |
| 1565 | return; |
| 1566 | } |
| 1567 | } |
| 1568 | if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) { |
| 1569 | for (CaptureResult& result : results) { |
| 1570 | CameraMetadata& md = result.result; |
| 1571 | if (!md.metadata.empty()) { |
| 1572 | if (mResultMetadataQueue->write(reinterpret_cast<int8_t*>(md.metadata.data()), |
| 1573 | md.metadata.size())) { |
| 1574 | result.fmqResultSize = md.metadata.size(); |
| 1575 | md.metadata.resize(0); |
| 1576 | } else { |
| 1577 | ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__); |
| 1578 | result.fmqResultSize = 0; |
| 1579 | } |
| 1580 | } else { |
| 1581 | result.fmqResultSize = 0; |
| 1582 | } |
| 1583 | } |
| 1584 | } |
| 1585 | auto status = mCallback->processCaptureResult(results); |
| 1586 | if (!status.isOk()) { |
| 1587 | ALOGE("%s: processCaptureResult ERROR : %d:%d", __FUNCTION__, status.getExceptionCode(), |
| 1588 | status.getServiceSpecificError()); |
| 1589 | } |
| 1590 | |
| 1591 | mProcessCaptureResultLock.unlock(); |
| 1592 | } |
| 1593 | |
| 1594 | int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) { |
| 1595 | ATRACE_CALL(); |
| 1596 | auto timeout = std::chrono::seconds(kBufferWaitTimeoutSec); |
| 1597 | mLock.unlock(); |
| 1598 | auto st = mV4L2BufferReturned.wait_for(lk, timeout); |
| 1599 | // Here we introduce an order where mV4l2BufferLock is acquired before mLock, while |
| 1600 | // the normal lock acquisition order is reversed. This is fine because in most of |
| 1601 | // cases we are protected by mInterfaceLock. The only thread that can cause deadlock |
| 1602 | // is the OutputThread, where we do need to make sure we don't acquire mLock then |
| 1603 | // mV4l2BufferLock |
| 1604 | mLock.lock(); |
| 1605 | if (st == std::cv_status::timeout) { |
| 1606 | ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__); |
| 1607 | return -1; |
| 1608 | } |
| 1609 | return 0; |
| 1610 | } |
| 1611 | |
| 1612 | bool ExternalCameraDeviceSession::supportOfflineLocked(int32_t streamId) { |
| 1613 | const Stream& stream = mStreamMap[streamId]; |
| 1614 | if (stream.format == PixelFormat::BLOB && |
| 1615 | static_cast<int32_t>(stream.dataSpace) == static_cast<int32_t>(Dataspace::JFIF)) { |
| 1616 | return true; |
| 1617 | } |
| 1618 | // TODO: support YUV output stream? |
| 1619 | return false; |
| 1620 | } |
| 1621 | |
| 1622 | bool ExternalCameraDeviceSession::canDropRequest(const std::vector<int32_t>& offlineStreams, |
| 1623 | std::shared_ptr<HalRequest> halReq) { |
| 1624 | for (const auto& buffer : halReq->buffers) { |
| 1625 | for (auto offlineStreamId : offlineStreams) { |
| 1626 | if (buffer.streamId == offlineStreamId) { |
| 1627 | return false; |
| 1628 | } |
| 1629 | } |
| 1630 | } |
| 1631 | // Only drop a request completely if it has no offline output |
| 1632 | return true; |
| 1633 | } |
| 1634 | |
| 1635 | void ExternalCameraDeviceSession::fillOfflineSessionInfo( |
| 1636 | const std::vector<int32_t>& offlineStreams, |
| 1637 | std::deque<std::shared_ptr<HalRequest>>& offlineReqs, |
| 1638 | const std::map<int, CirculatingBuffers>& circulatingBuffers, |
| 1639 | CameraOfflineSessionInfo* info) { |
| 1640 | if (info == nullptr) { |
| 1641 | ALOGE("%s: output info must not be null!", __FUNCTION__); |
| 1642 | return; |
| 1643 | } |
| 1644 | |
| 1645 | info->offlineStreams.resize(offlineStreams.size()); |
| 1646 | info->offlineRequests.resize(offlineReqs.size()); |
| 1647 | |
| 1648 | // Fill in offline reqs and count outstanding buffers |
| 1649 | for (size_t i = 0; i < offlineReqs.size(); i++) { |
| 1650 | info->offlineRequests[i].frameNumber = offlineReqs[i]->frameNumber; |
| 1651 | info->offlineRequests[i].pendingStreams.resize(offlineReqs[i]->buffers.size()); |
| 1652 | for (size_t bIdx = 0; bIdx < offlineReqs[i]->buffers.size(); bIdx++) { |
| 1653 | int32_t streamId = offlineReqs[i]->buffers[bIdx].streamId; |
| 1654 | info->offlineRequests[i].pendingStreams[bIdx] = streamId; |
| 1655 | } |
| 1656 | } |
| 1657 | |
| 1658 | for (size_t i = 0; i < offlineStreams.size(); i++) { |
| 1659 | int32_t streamId = offlineStreams[i]; |
| 1660 | info->offlineStreams[i].id = streamId; |
| 1661 | // outstanding buffers are 0 since we are doing hal buffer management and |
| 1662 | // offline session will ask for those buffers later |
| 1663 | info->offlineStreams[i].numOutstandingBuffers = 0; |
| 1664 | const CirculatingBuffers& bufIdMap = circulatingBuffers.at(streamId); |
| 1665 | info->offlineStreams[i].circulatingBufferIds.resize(bufIdMap.size()); |
| 1666 | size_t bIdx = 0; |
| 1667 | for (const auto& pair : bufIdMap) { |
| 1668 | // Fill in bufferId |
| 1669 | info->offlineStreams[i].circulatingBufferIds[bIdx++] = pair.first; |
| 1670 | } |
| 1671 | } |
| 1672 | } |
| 1673 | |
| 1674 | Status ExternalCameraDeviceSession::isStreamCombinationSupported( |
| 1675 | const StreamConfiguration& config, const std::vector<SupportedV4L2Format>& supportedFormats, |
| 1676 | const ExternalCameraConfig& devCfg) { |
| 1677 | if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) { |
| 1678 | ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode); |
| 1679 | return Status::ILLEGAL_ARGUMENT; |
| 1680 | } |
| 1681 | |
| 1682 | if (config.streams.size() == 0) { |
| 1683 | ALOGE("%s: cannot configure zero stream", __FUNCTION__); |
| 1684 | return Status::ILLEGAL_ARGUMENT; |
| 1685 | } |
| 1686 | |
| 1687 | int numProcessedStream = 0; |
| 1688 | int numStallStream = 0; |
| 1689 | for (const auto& stream : config.streams) { |
| 1690 | // Check if the format/width/height combo is supported |
| 1691 | if (!isSupported(stream, supportedFormats, devCfg)) { |
| 1692 | return Status::ILLEGAL_ARGUMENT; |
| 1693 | } |
| 1694 | if (stream.format == PixelFormat::BLOB) { |
| 1695 | numStallStream++; |
| 1696 | } else { |
| 1697 | numProcessedStream++; |
| 1698 | } |
| 1699 | } |
| 1700 | |
| 1701 | if (numProcessedStream > kMaxProcessedStream) { |
| 1702 | ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__, |
| 1703 | kMaxProcessedStream, numProcessedStream); |
| 1704 | return Status::ILLEGAL_ARGUMENT; |
| 1705 | } |
| 1706 | |
| 1707 | if (numStallStream > kMaxStallStream) { |
| 1708 | ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__, kMaxStallStream, |
| 1709 | numStallStream); |
| 1710 | return Status::ILLEGAL_ARGUMENT; |
| 1711 | } |
| 1712 | |
| 1713 | return Status::OK; |
| 1714 | } |
| 1715 | void ExternalCameraDeviceSession::updateBufferCaches( |
| 1716 | const std::vector<BufferCache>& cachesToRemove) { |
| 1717 | Mutex::Autolock _l(mCbsLock); |
| 1718 | for (auto& cache : cachesToRemove) { |
| 1719 | auto cbsIt = mCirculatingBuffers.find(cache.streamId); |
| 1720 | if (cbsIt == mCirculatingBuffers.end()) { |
| 1721 | // The stream could have been removed |
| 1722 | continue; |
| 1723 | } |
| 1724 | CirculatingBuffers& cbs = cbsIt->second; |
| 1725 | auto it = cbs.find(cache.bufferId); |
| 1726 | if (it != cbs.end()) { |
| 1727 | sHandleImporter.freeBuffer(it->second); |
| 1728 | cbs.erase(it); |
| 1729 | } else { |
| 1730 | ALOGE("%s: stream %d buffer %" PRIu64 " is not cached", __FUNCTION__, cache.streamId, |
| 1731 | cache.bufferId); |
| 1732 | } |
| 1733 | } |
| 1734 | } |
| 1735 | |
| 1736 | Status ExternalCameraDeviceSession::processCaptureRequestError( |
| 1737 | const std::shared_ptr<HalRequest>& req, std::vector<NotifyMsg>* outMsgs, |
| 1738 | std::vector<CaptureResult>* outResults) { |
| 1739 | ATRACE_CALL(); |
| 1740 | // Return V4L2 buffer to V4L2 buffer queue |
| 1741 | std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn); |
| 1742 | enqueueV4l2Frame(v4l2Frame); |
| 1743 | |
| 1744 | if (outMsgs == nullptr) { |
| 1745 | notifyShutter(req->frameNumber, req->shutterTs); |
| 1746 | notifyError(/*frameNum*/ req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_REQUEST); |
| 1747 | } else { |
| 1748 | NotifyMsg shutter; |
| 1749 | shutter.set<NotifyMsg::Tag::shutter>( |
| 1750 | ShutterMsg{.frameNumber = req->frameNumber, .timestamp = req->shutterTs}); |
| 1751 | |
| 1752 | NotifyMsg error; |
| 1753 | error.set<NotifyMsg::Tag::error>(ErrorMsg{.frameNumber = req->frameNumber, |
| 1754 | .errorStreamId = -1, |
| 1755 | .errorCode = ErrorCode::ERROR_REQUEST}); |
| 1756 | outMsgs->push_back(shutter); |
| 1757 | outMsgs->push_back(error); |
| 1758 | } |
| 1759 | |
| 1760 | // Fill output buffers |
| 1761 | CaptureResult result; |
| 1762 | result.frameNumber = req->frameNumber; |
| 1763 | result.partialResult = 1; |
| 1764 | result.inputBuffer.streamId = -1; |
| 1765 | result.outputBuffers.resize(req->buffers.size()); |
| 1766 | for (size_t i = 0; i < req->buffers.size(); i++) { |
| 1767 | result.outputBuffers[i].streamId = req->buffers[i].streamId; |
| 1768 | result.outputBuffers[i].bufferId = req->buffers[i].bufferId; |
| 1769 | result.outputBuffers[i].status = BufferStatus::ERROR; |
| 1770 | if (req->buffers[i].acquireFence >= 0) { |
Avichal Rakesh | 1fa4142 | 2023-11-03 15:33:36 -0700 | [diff] [blame] | 1771 | result.outputBuffers[i].releaseFence.fds.resize(1); |
| 1772 | result.outputBuffers[i].releaseFence.fds.at(0).set(req->buffers[i].acquireFence); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1773 | } |
| 1774 | } |
| 1775 | |
| 1776 | // update inflight records |
| 1777 | { |
| 1778 | std::lock_guard<std::mutex> lk(mInflightFramesLock); |
| 1779 | mInflightFrames.erase(req->frameNumber); |
| 1780 | } |
| 1781 | |
| 1782 | if (outResults == nullptr) { |
| 1783 | // Callback into framework |
| 1784 | std::vector<CaptureResult> results(1); |
| 1785 | results[0] = std::move(result); |
| 1786 | invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true); |
| 1787 | freeReleaseFences(results); |
| 1788 | } else { |
| 1789 | outResults->push_back(std::move(result)); |
| 1790 | } |
| 1791 | return Status::OK; |
| 1792 | } |
| 1793 | |
| 1794 | Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) { |
| 1795 | ATRACE_CALL(); |
| 1796 | // Return V4L2 buffer to V4L2 buffer queue |
| 1797 | std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn); |
| 1798 | enqueueV4l2Frame(v4l2Frame); |
| 1799 | |
| 1800 | // NotifyShutter |
| 1801 | notifyShutter(req->frameNumber, req->shutterTs); |
| 1802 | |
| 1803 | // Fill output buffers; |
| 1804 | std::vector<CaptureResult> results(1); |
| 1805 | CaptureResult& result = results[0]; |
| 1806 | result.frameNumber = req->frameNumber; |
| 1807 | result.partialResult = 1; |
| 1808 | result.inputBuffer.streamId = -1; |
| 1809 | result.outputBuffers.resize(req->buffers.size()); |
| 1810 | for (size_t i = 0; i < req->buffers.size(); i++) { |
| 1811 | result.outputBuffers[i].streamId = req->buffers[i].streamId; |
| 1812 | result.outputBuffers[i].bufferId = req->buffers[i].bufferId; |
| 1813 | if (req->buffers[i].fenceTimeout) { |
| 1814 | result.outputBuffers[i].status = BufferStatus::ERROR; |
| 1815 | if (req->buffers[i].acquireFence >= 0) { |
Avichal Rakesh | 1fa4142 | 2023-11-03 15:33:36 -0700 | [diff] [blame] | 1816 | result.outputBuffers[i].releaseFence.fds.resize(1); |
| 1817 | result.outputBuffers[i].releaseFence.fds.at(0).set(req->buffers[i].acquireFence); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1818 | } |
| 1819 | notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER); |
| 1820 | } else { |
| 1821 | result.outputBuffers[i].status = BufferStatus::OK; |
| 1822 | // TODO: refactor |
| 1823 | if (req->buffers[i].acquireFence >= 0) { |
Avichal Rakesh | 1fa4142 | 2023-11-03 15:33:36 -0700 | [diff] [blame] | 1824 | result.outputBuffers[i].releaseFence.fds.resize(1); |
| 1825 | result.outputBuffers[i].releaseFence.fds.at(0).set(req->buffers[i].acquireFence); |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 1826 | } |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | // Fill capture result metadata |
| 1831 | fillCaptureResult(req->setting, req->shutterTs); |
| 1832 | const camera_metadata_t* rawResult = req->setting.getAndLock(); |
| 1833 | convertToAidl(rawResult, &result.result); |
| 1834 | req->setting.unlock(rawResult); |
| 1835 | |
| 1836 | // update inflight records |
| 1837 | { |
| 1838 | std::lock_guard<std::mutex> lk(mInflightFramesLock); |
| 1839 | mInflightFrames.erase(req->frameNumber); |
| 1840 | } |
| 1841 | |
| 1842 | // Callback into framework |
| 1843 | invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true); |
| 1844 | freeReleaseFences(results); |
| 1845 | return Status::OK; |
| 1846 | } |
| 1847 | |
| 1848 | ssize_t ExternalCameraDeviceSession::getJpegBufferSize(int32_t width, int32_t height) const { |
| 1849 | // Constant from camera3.h |
| 1850 | const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob); |
| 1851 | // Get max jpeg size (area-wise). |
| 1852 | if (mMaxJpegResolution.width == 0) { |
| 1853 | ALOGE("%s: No supported JPEG stream", __FUNCTION__); |
| 1854 | return BAD_VALUE; |
| 1855 | } |
| 1856 | |
| 1857 | // Get max jpeg buffer size |
| 1858 | ssize_t maxJpegBufferSize = 0; |
| 1859 | camera_metadata_ro_entry jpegBufMaxSize = mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE); |
| 1860 | if (jpegBufMaxSize.count == 0) { |
| 1861 | ALOGE("%s: Can't find maximum JPEG size in static metadata!", __FUNCTION__); |
| 1862 | return BAD_VALUE; |
| 1863 | } |
| 1864 | maxJpegBufferSize = jpegBufMaxSize.data.i32[0]; |
| 1865 | |
| 1866 | if (maxJpegBufferSize <= kMinJpegBufferSize) { |
| 1867 | ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)", __FUNCTION__, |
| 1868 | maxJpegBufferSize, kMinJpegBufferSize); |
| 1869 | return BAD_VALUE; |
| 1870 | } |
| 1871 | |
| 1872 | // Calculate final jpeg buffer size for the given resolution. |
| 1873 | float scaleFactor = |
| 1874 | ((float)(width * height)) / (mMaxJpegResolution.width * mMaxJpegResolution.height); |
| 1875 | ssize_t jpegBufferSize = |
| 1876 | scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) + kMinJpegBufferSize; |
| 1877 | if (jpegBufferSize > maxJpegBufferSize) { |
| 1878 | jpegBufferSize = maxJpegBufferSize; |
| 1879 | } |
| 1880 | |
| 1881 | return jpegBufferSize; |
| 1882 | } |
| 1883 | binder_status_t ExternalCameraDeviceSession::dump(int fd, const char** /*args*/, |
| 1884 | uint32_t /*numArgs*/) { |
| 1885 | bool intfLocked = tryLock(mInterfaceLock); |
| 1886 | if (!intfLocked) { |
| 1887 | dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n"); |
| 1888 | } |
| 1889 | |
| 1890 | if (isClosed()) { |
| 1891 | dprintf(fd, "External camera %s is closed\n", mCameraId.c_str()); |
| 1892 | return STATUS_OK; |
| 1893 | } |
| 1894 | |
| 1895 | bool streaming = false; |
| 1896 | size_t v4L2BufferCount = 0; |
| 1897 | SupportedV4L2Format streamingFmt; |
| 1898 | { |
| 1899 | bool sessionLocked = tryLock(mLock); |
| 1900 | if (!sessionLocked) { |
| 1901 | dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n"); |
| 1902 | } |
| 1903 | streaming = mV4l2Streaming; |
| 1904 | streamingFmt = mV4l2StreamingFmt; |
| 1905 | v4L2BufferCount = mV4L2BufferCount; |
| 1906 | |
| 1907 | if (sessionLocked) { |
| 1908 | mLock.unlock(); |
| 1909 | } |
| 1910 | } |
| 1911 | |
| 1912 | std::unordered_set<uint32_t> inflightFrames; |
| 1913 | { |
| 1914 | bool iffLocked = tryLock(mInflightFramesLock); |
| 1915 | if (!iffLocked) { |
| 1916 | dprintf(fd, |
| 1917 | "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n"); |
| 1918 | } |
| 1919 | inflightFrames = mInflightFrames; |
| 1920 | if (iffLocked) { |
| 1921 | mInflightFramesLock.unlock(); |
| 1922 | } |
| 1923 | } |
| 1924 | |
| 1925 | dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n", mCameraId.c_str(), |
| 1926 | mV4l2Fd.get(), (mCroppingType == VERTICAL) ? "vertical" : "horizontal", |
| 1927 | streaming ? "streaming" : "not streaming"); |
| 1928 | |
| 1929 | if (streaming) { |
| 1930 | // TODO: dump fps later |
| 1931 | dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n", streamingFmt.fourcc & 0xFF, |
| 1932 | (streamingFmt.fourcc >> 8) & 0xFF, (streamingFmt.fourcc >> 16) & 0xFF, |
| 1933 | (streamingFmt.fourcc >> 24) & 0xFF, streamingFmt.width, streamingFmt.height, |
| 1934 | mV4l2StreamingFps); |
| 1935 | |
| 1936 | size_t numDequeuedV4l2Buffers = 0; |
| 1937 | { |
| 1938 | std::lock_guard<std::mutex> lk(mV4l2BufferLock); |
| 1939 | numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers; |
| 1940 | } |
| 1941 | dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n", v4L2BufferCount, |
| 1942 | numDequeuedV4l2Buffers); |
| 1943 | } |
| 1944 | |
| 1945 | dprintf(fd, "In-flight frames (not sorted):"); |
| 1946 | for (const auto& frameNumber : inflightFrames) { |
| 1947 | dprintf(fd, "%d, ", frameNumber); |
| 1948 | } |
| 1949 | dprintf(fd, "\n"); |
| 1950 | mOutputThread->dump(fd); |
| 1951 | dprintf(fd, "\n"); |
| 1952 | |
| 1953 | if (intfLocked) { |
| 1954 | mInterfaceLock.unlock(); |
| 1955 | } |
| 1956 | |
| 1957 | return STATUS_OK; |
| 1958 | } |
| 1959 | |
| 1960 | // Start ExternalCameraDeviceSession::BufferRequestThread functions |
| 1961 | ExternalCameraDeviceSession::BufferRequestThread::BufferRequestThread( |
| 1962 | std::weak_ptr<OutputThreadInterface> parent, |
| 1963 | std::shared_ptr<ICameraDeviceCallback> callbacks) |
| 1964 | : mParent(parent), mCallbacks(callbacks) {} |
| 1965 | |
| 1966 | int ExternalCameraDeviceSession::BufferRequestThread::requestBufferStart( |
| 1967 | const std::vector<HalStreamBuffer>& bufReqs) { |
| 1968 | if (bufReqs.empty()) { |
| 1969 | ALOGE("%s: bufReqs is empty!", __FUNCTION__); |
| 1970 | return -1; |
| 1971 | } |
| 1972 | |
| 1973 | { |
| 1974 | std::lock_guard<std::mutex> lk(mLock); |
| 1975 | if (mRequestingBuffer) { |
| 1976 | ALOGE("%s: BufferRequestThread does not support more than one concurrent request!", |
| 1977 | __FUNCTION__); |
| 1978 | return -1; |
| 1979 | } |
| 1980 | |
| 1981 | mBufferReqs = bufReqs; |
| 1982 | mRequestingBuffer = true; |
| 1983 | } |
| 1984 | mRequestCond.notify_one(); |
| 1985 | return 0; |
| 1986 | } |
| 1987 | |
| 1988 | int ExternalCameraDeviceSession::BufferRequestThread::waitForBufferRequestDone( |
| 1989 | std::vector<HalStreamBuffer>* outBufReqs) { |
| 1990 | std::unique_lock<std::mutex> lk(mLock); |
| 1991 | if (!mRequestingBuffer) { |
| 1992 | ALOGE("%s: no pending buffer request!", __FUNCTION__); |
| 1993 | return -1; |
| 1994 | } |
| 1995 | |
| 1996 | if (mPendingReturnBufferReqs.empty()) { |
| 1997 | std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqProcTimeoutMs); |
| 1998 | auto st = mRequestDoneCond.wait_for(lk, timeout); |
| 1999 | if (st == std::cv_status::timeout) { |
| 2000 | ALOGE("%s: wait for buffer request finish timeout!", __FUNCTION__); |
| 2001 | return -1; |
| 2002 | } |
| 2003 | } |
| 2004 | mRequestingBuffer = false; |
| 2005 | *outBufReqs = std::move(mPendingReturnBufferReqs); |
| 2006 | mPendingReturnBufferReqs.clear(); |
| 2007 | return 0; |
| 2008 | } |
| 2009 | |
| 2010 | void ExternalCameraDeviceSession::BufferRequestThread::waitForNextRequest() { |
| 2011 | ATRACE_CALL(); |
| 2012 | std::unique_lock<std::mutex> lk(mLock); |
| 2013 | int waitTimes = 0; |
| 2014 | while (mBufferReqs.empty()) { |
| 2015 | if (exitPending()) { |
| 2016 | return; |
| 2017 | } |
| 2018 | auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs); |
| 2019 | auto st = mRequestCond.wait_for(lk, timeout); |
| 2020 | if (st == std::cv_status::timeout) { |
| 2021 | waitTimes++; |
| 2022 | if (waitTimes == kReqWaitTimesWarn) { |
| 2023 | // BufferRequestThread just wait forever for new buffer request |
| 2024 | // But it will print some periodic warning indicating it's waiting |
| 2025 | ALOGV("%s: still waiting for new buffer request", __FUNCTION__); |
| 2026 | waitTimes = 0; |
| 2027 | } |
| 2028 | } |
| 2029 | } |
| 2030 | |
| 2031 | // Fill in BufferRequest |
| 2032 | mHalBufferReqs.resize(mBufferReqs.size()); |
| 2033 | for (size_t i = 0; i < mHalBufferReqs.size(); i++) { |
| 2034 | mHalBufferReqs[i].streamId = mBufferReqs[i].streamId; |
| 2035 | mHalBufferReqs[i].numBuffersRequested = 1; |
| 2036 | } |
| 2037 | } |
| 2038 | |
| 2039 | bool ExternalCameraDeviceSession::BufferRequestThread::threadLoop() { |
| 2040 | waitForNextRequest(); |
| 2041 | if (exitPending()) { |
| 2042 | return false; |
| 2043 | } |
| 2044 | |
| 2045 | ATRACE_BEGIN("AIDL requestStreamBuffers"); |
| 2046 | BufferRequestStatus status; |
| 2047 | std::vector<StreamBufferRet> bufRets; |
| 2048 | ScopedAStatus ret = mCallbacks->requestStreamBuffers(mHalBufferReqs, &bufRets, &status); |
| 2049 | if (!ret.isOk()) { |
| 2050 | ALOGE("%s: Transaction error: %d:%d", __FUNCTION__, ret.getExceptionCode(), |
| 2051 | ret.getServiceSpecificError()); |
| 2052 | return false; |
| 2053 | } |
| 2054 | |
| 2055 | std::unique_lock<std::mutex> lk(mLock); |
| 2056 | if (status == BufferRequestStatus::OK || status == BufferRequestStatus::FAILED_PARTIAL) { |
| 2057 | if (bufRets.size() != mHalBufferReqs.size()) { |
| 2058 | ALOGE("%s: expect %zu buffer requests returned, only got %zu", __FUNCTION__, |
| 2059 | mHalBufferReqs.size(), bufRets.size()); |
| 2060 | return false; |
| 2061 | } |
| 2062 | |
| 2063 | auto parent = mParent.lock(); |
| 2064 | if (parent == nullptr) { |
| 2065 | ALOGE("%s: session has been disconnected!", __FUNCTION__); |
| 2066 | return false; |
| 2067 | } |
| 2068 | |
| 2069 | std::vector<int> importedFences; |
| 2070 | importedFences.resize(bufRets.size()); |
| 2071 | for (size_t i = 0; i < bufRets.size(); i++) { |
| 2072 | int streamId = bufRets[i].streamId; |
| 2073 | switch (bufRets[i].val.getTag()) { |
| 2074 | case StreamBuffersVal::Tag::error: |
| 2075 | continue; |
| 2076 | case StreamBuffersVal::Tag::buffers: { |
| 2077 | const std::vector<StreamBuffer>& hBufs = |
| 2078 | bufRets[i].val.get<StreamBuffersVal::Tag::buffers>(); |
| 2079 | if (hBufs.size() != 1) { |
| 2080 | ALOGE("%s: expect 1 buffer returned, got %zu!", __FUNCTION__, hBufs.size()); |
| 2081 | return false; |
| 2082 | } |
| 2083 | const StreamBuffer& hBuf = hBufs[0]; |
| 2084 | |
| 2085 | mBufferReqs[i].bufferId = hBuf.bufferId; |
| 2086 | // TODO: create a batch import API so we don't need to lock/unlock mCbsLock |
| 2087 | // repeatedly? |
| 2088 | lk.unlock(); |
| 2089 | Status s = |
| 2090 | parent->importBuffer(streamId, hBuf.bufferId, makeFromAidl(hBuf.buffer), |
| 2091 | /*out*/ &mBufferReqs[i].bufPtr); |
| 2092 | lk.lock(); |
| 2093 | |
| 2094 | if (s != Status::OK) { |
| 2095 | ALOGE("%s: stream %d import buffer failed!", __FUNCTION__, streamId); |
| 2096 | cleanupInflightFences(importedFences, i - 1); |
| 2097 | return false; |
| 2098 | } |
| 2099 | if (!sHandleImporter.importFence(makeFromAidl(hBuf.acquireFence), |
| 2100 | mBufferReqs[i].acquireFence)) { |
| 2101 | ALOGE("%s: stream %d import fence failed!", __FUNCTION__, streamId); |
| 2102 | cleanupInflightFences(importedFences, i - 1); |
| 2103 | return false; |
| 2104 | } |
| 2105 | importedFences[i] = mBufferReqs[i].acquireFence; |
| 2106 | } break; |
| 2107 | default: |
| 2108 | ALOGE("%s: Unknown StreamBuffersVal!", __FUNCTION__); |
| 2109 | return false; |
| 2110 | } |
| 2111 | } |
| 2112 | } else { |
| 2113 | ALOGE("%s: requestStreamBuffers call failed!", __FUNCTION__); |
| 2114 | } |
| 2115 | |
| 2116 | mPendingReturnBufferReqs = std::move(mBufferReqs); |
| 2117 | mBufferReqs.clear(); |
| 2118 | |
| 2119 | lk.unlock(); |
| 2120 | mRequestDoneCond.notify_one(); |
| 2121 | return true; |
| 2122 | } |
| 2123 | |
| 2124 | // End ExternalCameraDeviceSession::BufferRequestThread functions |
| 2125 | |
| 2126 | // Start ExternalCameraDeviceSession::OutputThread functions |
| 2127 | |
| 2128 | ExternalCameraDeviceSession::OutputThread::OutputThread( |
| 2129 | std::weak_ptr<OutputThreadInterface> parent, CroppingType ct, |
| 2130 | const common::V1_0::helper::CameraMetadata& chars, |
| 2131 | std::shared_ptr<BufferRequestThread> bufReqThread) |
| 2132 | : mParent(parent), |
| 2133 | mCroppingType(ct), |
| 2134 | mCameraCharacteristics(chars), |
| 2135 | mBufferRequestThread(bufReqThread) {} |
| 2136 | |
| 2137 | ExternalCameraDeviceSession::OutputThread::~OutputThread() {} |
| 2138 | |
| 2139 | Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers( |
| 2140 | const Size& v4lSize, const Size& thumbSize, const std::vector<Stream>& streams, |
| 2141 | uint32_t blobBufferSize) { |
| 2142 | std::lock_guard<std::mutex> lk(mBufferLock); |
| 2143 | if (!mScaledYu12Frames.empty()) { |
| 2144 | ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)", __FUNCTION__, |
| 2145 | mScaledYu12Frames.size()); |
| 2146 | return Status::INTERNAL_ERROR; |
| 2147 | } |
| 2148 | |
| 2149 | // Allocating intermediate YU12 frame |
| 2150 | if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width || |
| 2151 | mYu12Frame->mHeight != v4lSize.height) { |
| 2152 | mYu12Frame.reset(); |
| 2153 | mYu12Frame = std::make_shared<AllocatedFrame>(v4lSize.width, v4lSize.height); |
| 2154 | int ret = mYu12Frame->allocate(&mYu12FrameLayout); |
| 2155 | if (ret != 0) { |
| 2156 | ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__); |
| 2157 | return Status::INTERNAL_ERROR; |
| 2158 | } |
| 2159 | } |
| 2160 | |
| 2161 | // Allocating intermediate YU12 thumbnail frame |
| 2162 | if (mYu12ThumbFrame == nullptr || mYu12ThumbFrame->mWidth != thumbSize.width || |
| 2163 | mYu12ThumbFrame->mHeight != thumbSize.height) { |
| 2164 | mYu12ThumbFrame.reset(); |
| 2165 | mYu12ThumbFrame = std::make_shared<AllocatedFrame>(thumbSize.width, thumbSize.height); |
| 2166 | int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout); |
| 2167 | if (ret != 0) { |
| 2168 | ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__); |
| 2169 | return Status::INTERNAL_ERROR; |
| 2170 | } |
| 2171 | } |
| 2172 | |
| 2173 | // Allocating scaled buffers |
| 2174 | for (const auto& stream : streams) { |
| 2175 | Size sz = {stream.width, stream.height}; |
| 2176 | if (sz == v4lSize) { |
| 2177 | continue; // Don't need an intermediate buffer same size as v4lBuffer |
| 2178 | } |
| 2179 | if (mIntermediateBuffers.count(sz) == 0) { |
| 2180 | // Create new intermediate buffer |
| 2181 | std::shared_ptr<AllocatedFrame> buf = |
| 2182 | std::make_shared<AllocatedFrame>(stream.width, stream.height); |
| 2183 | int ret = buf->allocate(); |
| 2184 | if (ret != 0) { |
| 2185 | ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!", __FUNCTION__, |
| 2186 | stream.width, stream.height); |
| 2187 | return Status::INTERNAL_ERROR; |
| 2188 | } |
| 2189 | mIntermediateBuffers[sz] = buf; |
| 2190 | } |
| 2191 | } |
| 2192 | |
| 2193 | // Remove unconfigured buffers |
| 2194 | auto it = mIntermediateBuffers.begin(); |
| 2195 | while (it != mIntermediateBuffers.end()) { |
| 2196 | bool configured = false; |
| 2197 | auto sz = it->first; |
| 2198 | for (const auto& stream : streams) { |
| 2199 | if (stream.width == sz.width && stream.height == sz.height) { |
| 2200 | configured = true; |
| 2201 | break; |
| 2202 | } |
| 2203 | } |
| 2204 | if (configured) { |
| 2205 | it++; |
| 2206 | } else { |
| 2207 | it = mIntermediateBuffers.erase(it); |
| 2208 | } |
| 2209 | } |
| 2210 | |
| 2211 | // Allocate mute test pattern frame |
| 2212 | mMuteTestPatternFrame.resize(mYu12Frame->mWidth * mYu12Frame->mHeight * 3); |
| 2213 | |
| 2214 | mBlobBufferSize = blobBufferSize; |
| 2215 | return Status::OK; |
| 2216 | } |
| 2217 | |
| 2218 | Status ExternalCameraDeviceSession::OutputThread::submitRequest( |
| 2219 | const std::shared_ptr<HalRequest>& req) { |
| 2220 | std::unique_lock<std::mutex> lk(mRequestListLock); |
| 2221 | mRequestList.push_back(req); |
| 2222 | lk.unlock(); |
| 2223 | mRequestCond.notify_one(); |
| 2224 | return Status::OK; |
| 2225 | } |
| 2226 | |
| 2227 | void ExternalCameraDeviceSession::OutputThread::flush() { |
| 2228 | ATRACE_CALL(); |
| 2229 | auto parent = mParent.lock(); |
| 2230 | if (parent == nullptr) { |
| 2231 | ALOGE("%s: session has been disconnected!", __FUNCTION__); |
| 2232 | return; |
| 2233 | } |
| 2234 | |
| 2235 | std::unique_lock<std::mutex> lk(mRequestListLock); |
| 2236 | std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList); |
| 2237 | mRequestList.clear(); |
| 2238 | if (mProcessingRequest) { |
| 2239 | auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec); |
| 2240 | auto st = mRequestDoneCond.wait_for(lk, timeout); |
| 2241 | if (st == std::cv_status::timeout) { |
| 2242 | ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__); |
| 2243 | } |
| 2244 | } |
| 2245 | |
| 2246 | ALOGV("%s: flushing inflight requests", __FUNCTION__); |
| 2247 | lk.unlock(); |
| 2248 | for (const auto& req : reqs) { |
| 2249 | parent->processCaptureRequestError(req); |
| 2250 | } |
| 2251 | } |
| 2252 | |
| 2253 | void ExternalCameraDeviceSession::OutputThread::dump(int fd) { |
| 2254 | std::lock_guard<std::mutex> lk(mRequestListLock); |
| 2255 | if (mProcessingRequest) { |
| 2256 | dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumber); |
| 2257 | } else { |
| 2258 | dprintf(fd, "OutputThread not processing any frames\n"); |
| 2259 | } |
| 2260 | dprintf(fd, "OutputThread request list contains frame: "); |
| 2261 | for (const auto& req : mRequestList) { |
| 2262 | dprintf(fd, "%d, ", req->frameNumber); |
| 2263 | } |
| 2264 | dprintf(fd, "\n"); |
| 2265 | } |
| 2266 | |
| 2267 | void ExternalCameraDeviceSession::OutputThread::setExifMakeModel(const std::string& make, |
| 2268 | const std::string& model) { |
| 2269 | mExifMake = make; |
| 2270 | mExifModel = model; |
| 2271 | } |
| 2272 | |
| 2273 | std::list<std::shared_ptr<HalRequest>> |
| 2274 | ExternalCameraDeviceSession::OutputThread::switchToOffline() { |
| 2275 | ATRACE_CALL(); |
| 2276 | auto parent = mParent.lock(); |
| 2277 | if (parent == nullptr) { |
| 2278 | ALOGE("%s: session has been disconnected!", __FUNCTION__); |
| 2279 | return {}; |
| 2280 | } |
| 2281 | |
| 2282 | std::unique_lock<std::mutex> lk(mRequestListLock); |
| 2283 | std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList); |
| 2284 | mRequestList.clear(); |
| 2285 | if (mProcessingRequest) { |
| 2286 | auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec); |
| 2287 | auto st = mRequestDoneCond.wait_for(lk, timeout); |
| 2288 | if (st == std::cv_status::timeout) { |
| 2289 | ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__); |
| 2290 | } |
| 2291 | } |
| 2292 | lk.unlock(); |
| 2293 | clearIntermediateBuffers(); |
| 2294 | ALOGV("%s: returning %zu request for offline processing", __FUNCTION__, reqs.size()); |
| 2295 | return reqs; |
| 2296 | } |
| 2297 | |
| 2298 | int ExternalCameraDeviceSession::OutputThread::requestBufferStart( |
| 2299 | const std::vector<HalStreamBuffer>& bufs) { |
| 2300 | if (mBufferRequestThread == nullptr) { |
| 2301 | return 0; |
| 2302 | } |
| 2303 | return mBufferRequestThread->requestBufferStart(bufs); |
| 2304 | } |
| 2305 | |
| 2306 | int ExternalCameraDeviceSession::OutputThread::waitForBufferRequestDone( |
| 2307 | std::vector<HalStreamBuffer>* outBufs) { |
| 2308 | if (mBufferRequestThread == nullptr) { |
| 2309 | return 0; |
| 2310 | } |
| 2311 | return mBufferRequestThread->waitForBufferRequestDone(outBufs); |
| 2312 | } |
| 2313 | |
| 2314 | void ExternalCameraDeviceSession::OutputThread::waitForNextRequest( |
| 2315 | std::shared_ptr<HalRequest>* out) { |
| 2316 | ATRACE_CALL(); |
| 2317 | if (out == nullptr) { |
| 2318 | ALOGE("%s: out is null", __FUNCTION__); |
| 2319 | return; |
| 2320 | } |
| 2321 | |
| 2322 | std::unique_lock<std::mutex> lk(mRequestListLock); |
| 2323 | int waitTimes = 0; |
| 2324 | while (mRequestList.empty()) { |
| 2325 | if (exitPending()) { |
| 2326 | return; |
| 2327 | } |
| 2328 | auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs); |
| 2329 | auto st = mRequestCond.wait_for(lk, timeout); |
| 2330 | if (st == std::cv_status::timeout) { |
| 2331 | waitTimes++; |
| 2332 | if (waitTimes == kReqWaitTimesMax) { |
| 2333 | // no new request, return |
| 2334 | return; |
| 2335 | } |
| 2336 | } |
| 2337 | } |
| 2338 | *out = mRequestList.front(); |
| 2339 | mRequestList.pop_front(); |
| 2340 | mProcessingRequest = true; |
| 2341 | mProcessingFrameNumber = (*out)->frameNumber; |
| 2342 | } |
| 2343 | |
| 2344 | void ExternalCameraDeviceSession::OutputThread::signalRequestDone() { |
| 2345 | std::unique_lock<std::mutex> lk(mRequestListLock); |
| 2346 | mProcessingRequest = false; |
| 2347 | mProcessingFrameNumber = 0; |
| 2348 | lk.unlock(); |
| 2349 | mRequestDoneCond.notify_one(); |
| 2350 | } |
| 2351 | |
| 2352 | int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked( |
| 2353 | std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) { |
| 2354 | Size inSz = {in->mWidth, in->mHeight}; |
| 2355 | |
| 2356 | int ret; |
| 2357 | if (inSz == outSz) { |
| 2358 | ret = in->getLayout(out); |
| 2359 | if (ret != 0) { |
| 2360 | ALOGE("%s: failed to get input image layout", __FUNCTION__); |
| 2361 | return ret; |
| 2362 | } |
| 2363 | return ret; |
| 2364 | } |
| 2365 | |
| 2366 | // Cropping to output aspect ratio |
| 2367 | IMapper::Rect inputCrop; |
| 2368 | ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop); |
| 2369 | if (ret != 0) { |
| 2370 | ALOGE("%s: failed to compute crop rect for output size %dx%d", __FUNCTION__, outSz.width, |
| 2371 | outSz.height); |
| 2372 | return ret; |
| 2373 | } |
| 2374 | |
| 2375 | YCbCrLayout croppedLayout; |
| 2376 | ret = in->getCroppedLayout(inputCrop, &croppedLayout); |
| 2377 | if (ret != 0) { |
| 2378 | ALOGE("%s: failed to crop input image %dx%d to output size %dx%d", __FUNCTION__, inSz.width, |
| 2379 | inSz.height, outSz.width, outSz.height); |
| 2380 | return ret; |
| 2381 | } |
| 2382 | |
| 2383 | if ((mCroppingType == VERTICAL && inSz.width == outSz.width) || |
| 2384 | (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) { |
| 2385 | // No scale is needed |
| 2386 | *out = croppedLayout; |
| 2387 | return 0; |
| 2388 | } |
| 2389 | |
| 2390 | auto it = mScaledYu12Frames.find(outSz); |
| 2391 | std::shared_ptr<AllocatedFrame> scaledYu12Buf; |
| 2392 | if (it != mScaledYu12Frames.end()) { |
| 2393 | scaledYu12Buf = it->second; |
| 2394 | } else { |
| 2395 | it = mIntermediateBuffers.find(outSz); |
| 2396 | if (it == mIntermediateBuffers.end()) { |
| 2397 | ALOGE("%s: failed to find intermediate buffer size %dx%d", __FUNCTION__, outSz.width, |
| 2398 | outSz.height); |
| 2399 | return -1; |
| 2400 | } |
| 2401 | scaledYu12Buf = it->second; |
| 2402 | } |
| 2403 | // Scale |
| 2404 | YCbCrLayout outLayout; |
| 2405 | ret = scaledYu12Buf->getLayout(&outLayout); |
| 2406 | if (ret != 0) { |
| 2407 | ALOGE("%s: failed to get output buffer layout", __FUNCTION__); |
| 2408 | return ret; |
| 2409 | } |
| 2410 | |
| 2411 | ret = libyuv::I420Scale( |
| 2412 | static_cast<uint8_t*>(croppedLayout.y), croppedLayout.yStride, |
| 2413 | static_cast<uint8_t*>(croppedLayout.cb), croppedLayout.cStride, |
| 2414 | static_cast<uint8_t*>(croppedLayout.cr), croppedLayout.cStride, inputCrop.width, |
| 2415 | inputCrop.height, static_cast<uint8_t*>(outLayout.y), outLayout.yStride, |
| 2416 | static_cast<uint8_t*>(outLayout.cb), outLayout.cStride, |
| 2417 | static_cast<uint8_t*>(outLayout.cr), outLayout.cStride, outSz.width, outSz.height, |
| 2418 | // TODO: b/72261744 see if we can use better filter without losing too much perf |
| 2419 | libyuv::FilterMode::kFilterNone); |
| 2420 | |
| 2421 | if (ret != 0) { |
| 2422 | ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__, |
| 2423 | inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret); |
| 2424 | return ret; |
| 2425 | } |
| 2426 | |
| 2427 | *out = outLayout; |
| 2428 | mScaledYu12Frames.insert({outSz, scaledYu12Buf}); |
| 2429 | return 0; |
| 2430 | } |
| 2431 | |
| 2432 | int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked( |
| 2433 | std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) { |
| 2434 | Size inSz{in->mWidth, in->mHeight}; |
| 2435 | |
| 2436 | if ((outSz.width * outSz.height) > (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) { |
| 2437 | ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)", __FUNCTION__, outSz.width, |
| 2438 | outSz.height, mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight); |
| 2439 | return -1; |
| 2440 | } |
| 2441 | |
| 2442 | int ret; |
| 2443 | |
| 2444 | /* This will crop-and-zoom the input YUV frame to the thumbnail size |
| 2445 | * Based on the following logic: |
| 2446 | * 1) Square pixels come in, square pixels come out, therefore single |
| 2447 | * scale factor is computed to either make input bigger or smaller |
| 2448 | * depending on if we are upscaling or downscaling |
| 2449 | * 2) That single scale factor would either make height too tall or width |
| 2450 | * too wide so we need to crop the input either horizontally or vertically |
| 2451 | * but not both |
| 2452 | */ |
| 2453 | |
| 2454 | /* Convert the input and output dimensions into floats for ease of math */ |
| 2455 | float fWin = static_cast<float>(inSz.width); |
| 2456 | float fHin = static_cast<float>(inSz.height); |
| 2457 | float fWout = static_cast<float>(outSz.width); |
| 2458 | float fHout = static_cast<float>(outSz.height); |
| 2459 | |
| 2460 | /* Compute the one scale factor from (1) above, it will be the smaller of |
| 2461 | * the two possibilities. */ |
| 2462 | float scaleFactor = std::min(fHin / fHout, fWin / fWout); |
| 2463 | |
| 2464 | /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can |
| 2465 | * simply multiply the output by our scaleFactor to get the cropped input |
| 2466 | * size. Note that at least one of {fWcrop, fHcrop} is going to wind up |
| 2467 | * being {fWin, fHin} respectively because fHout or fWout cancels out the |
| 2468 | * scaleFactor calculation above. |
| 2469 | * |
| 2470 | * Specifically: |
| 2471 | * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off |
| 2472 | * input, in which case |
| 2473 | * scaleFactor = fHin / fHout |
| 2474 | * fWcrop = fHin / fHout * fWout |
| 2475 | * fHcrop = fHin |
| 2476 | * |
| 2477 | * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which |
| 2478 | * is just the inequality above with both sides multiplied by fWout |
| 2479 | * |
| 2480 | * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top |
| 2481 | * and the bottom off of input, and |
| 2482 | * scaleFactor = fWin / fWout |
| 2483 | * fWcrop = fWin |
| 2484 | * fHCrop = fWin / fWout * fHout |
| 2485 | */ |
| 2486 | float fWcrop = scaleFactor * fWout; |
| 2487 | float fHcrop = scaleFactor * fHout; |
| 2488 | |
| 2489 | /* Convert to integer and truncate to an even number */ |
| 2490 | Size cropSz = {.width = 2 * static_cast<int32_t>(fWcrop / 2.0f), |
| 2491 | .height = 2 * static_cast<int32_t>(fHcrop / 2.0f)}; |
| 2492 | |
| 2493 | /* Convert to a centered rectange with even top/left */ |
| 2494 | IMapper::Rect inputCrop{.left = 2 * static_cast<int32_t>((inSz.width - cropSz.width) / 4), |
| 2495 | .top = 2 * static_cast<int32_t>((inSz.height - cropSz.height) / 4), |
| 2496 | .width = static_cast<int32_t>(cropSz.width), |
| 2497 | .height = static_cast<int32_t>(cropSz.height)}; |
| 2498 | |
| 2499 | if ((inputCrop.top < 0) || (inputCrop.top >= static_cast<int32_t>(inSz.height)) || |
| 2500 | (inputCrop.left < 0) || (inputCrop.left >= static_cast<int32_t>(inSz.width)) || |
| 2501 | (inputCrop.width <= 0) || |
| 2502 | (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) || |
| 2503 | (inputCrop.height <= 0) || |
| 2504 | (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height))) { |
| 2505 | ALOGE("%s: came up with really wrong crop rectangle", __FUNCTION__); |
| 2506 | ALOGE("%s: input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width, |
| 2507 | inSz.height, outSz.width, outSz.height); |
| 2508 | ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top, |
| 2509 | inputCrop.width, inputCrop.height); |
| 2510 | return -1; |
| 2511 | } |
| 2512 | |
| 2513 | YCbCrLayout inputLayout; |
| 2514 | ret = in->getCroppedLayout(inputCrop, &inputLayout); |
| 2515 | if (ret != 0) { |
| 2516 | ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d", __FUNCTION__, |
| 2517 | inSz.width, inSz.height, outSz.width, outSz.height); |
| 2518 | ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top, |
| 2519 | inputCrop.width, inputCrop.height); |
| 2520 | return ret; |
| 2521 | } |
| 2522 | ALOGV("%s: crop input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width, |
| 2523 | inSz.height, outSz.width, outSz.height); |
| 2524 | ALOGV("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top, |
| 2525 | inputCrop.width, inputCrop.height); |
| 2526 | |
| 2527 | // Scale |
| 2528 | YCbCrLayout outFullLayout; |
| 2529 | |
| 2530 | ret = mYu12ThumbFrame->getLayout(&outFullLayout); |
| 2531 | if (ret != 0) { |
| 2532 | ALOGE("%s: failed to get output buffer layout", __FUNCTION__); |
| 2533 | return ret; |
| 2534 | } |
| 2535 | |
| 2536 | ret = libyuv::I420Scale(static_cast<uint8_t*>(inputLayout.y), inputLayout.yStride, |
| 2537 | static_cast<uint8_t*>(inputLayout.cb), inputLayout.cStride, |
| 2538 | static_cast<uint8_t*>(inputLayout.cr), inputLayout.cStride, |
| 2539 | inputCrop.width, inputCrop.height, |
| 2540 | static_cast<uint8_t*>(outFullLayout.y), outFullLayout.yStride, |
| 2541 | static_cast<uint8_t*>(outFullLayout.cb), outFullLayout.cStride, |
| 2542 | static_cast<uint8_t*>(outFullLayout.cr), outFullLayout.cStride, |
| 2543 | outSz.width, outSz.height, libyuv::FilterMode::kFilterNone); |
| 2544 | |
| 2545 | if (ret != 0) { |
| 2546 | ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__, |
| 2547 | inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret); |
| 2548 | return ret; |
| 2549 | } |
| 2550 | |
| 2551 | *out = outFullLayout; |
| 2552 | return 0; |
| 2553 | } |
| 2554 | |
| 2555 | int ExternalCameraDeviceSession::OutputThread::createJpegLocked( |
| 2556 | HalStreamBuffer& halBuf, const common::V1_0::helper::CameraMetadata& setting) { |
| 2557 | ATRACE_CALL(); |
| 2558 | int ret; |
| 2559 | auto lfail = [&](auto... args) { |
| 2560 | ALOGE(args...); |
| 2561 | |
| 2562 | return 1; |
| 2563 | }; |
| 2564 | auto parent = mParent.lock(); |
| 2565 | if (parent == nullptr) { |
| 2566 | ALOGE("%s: session has been disconnected!", __FUNCTION__); |
| 2567 | return 1; |
| 2568 | } |
| 2569 | |
| 2570 | ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u", __FUNCTION__, halBuf.streamId, |
| 2571 | static_cast<uint64_t>(halBuf.bufferId), halBuf.width, halBuf.height); |
| 2572 | ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p", __FUNCTION__, halBuf.format, |
| 2573 | static_cast<uint64_t>(halBuf.usage), halBuf.bufPtr); |
| 2574 | ALOGV("%s: YV12 buffer %d x %d", __FUNCTION__, mYu12Frame->mWidth, mYu12Frame->mHeight); |
| 2575 | |
| 2576 | int jpegQuality, thumbQuality; |
| 2577 | Size thumbSize; |
| 2578 | bool outputThumbnail = true; |
| 2579 | |
| 2580 | if (setting.exists(ANDROID_JPEG_QUALITY)) { |
| 2581 | camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_QUALITY); |
| 2582 | jpegQuality = entry.data.u8[0]; |
| 2583 | } else { |
| 2584 | return lfail("%s: ANDROID_JPEG_QUALITY not set", __FUNCTION__); |
| 2585 | } |
| 2586 | |
| 2587 | if (setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) { |
| 2588 | camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY); |
| 2589 | thumbQuality = entry.data.u8[0]; |
| 2590 | } else { |
| 2591 | return lfail("%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set", __FUNCTION__); |
| 2592 | } |
| 2593 | |
| 2594 | if (setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) { |
| 2595 | camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_SIZE); |
| 2596 | thumbSize = Size{.width = entry.data.i32[0], .height = entry.data.i32[1]}; |
| 2597 | if (thumbSize.width == 0 && thumbSize.height == 0) { |
| 2598 | outputThumbnail = false; |
| 2599 | } |
| 2600 | } else { |
| 2601 | return lfail("%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__); |
| 2602 | } |
| 2603 | |
| 2604 | /* Cropped and scaled YU12 buffer for main and thumbnail */ |
| 2605 | YCbCrLayout yu12Main; |
| 2606 | Size jpegSize{halBuf.width, halBuf.height}; |
| 2607 | |
| 2608 | /* Compute temporary buffer sizes accounting for the following: |
| 2609 | * thumbnail can't exceed APP1 size of 64K |
| 2610 | * main image needs to hold APP1, headers, and at most a poorly |
| 2611 | * compressed image */ |
| 2612 | const ssize_t maxThumbCodeSize = 64 * 1024; |
| 2613 | const ssize_t maxJpegCodeSize = |
| 2614 | mBlobBufferSize == 0 ? parent->getJpegBufferSize(jpegSize.width, jpegSize.height) |
| 2615 | : mBlobBufferSize; |
| 2616 | |
| 2617 | /* Check that getJpegBufferSize did not return an error */ |
| 2618 | if (maxJpegCodeSize < 0) { |
| 2619 | return lfail("%s: getJpegBufferSize returned %zd", __FUNCTION__, maxJpegCodeSize); |
| 2620 | } |
| 2621 | |
| 2622 | /* Hold actual thumbnail and main image code sizes */ |
| 2623 | size_t thumbCodeSize = 0, jpegCodeSize = 0; |
| 2624 | /* Temporary thumbnail code buffer */ |
| 2625 | std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0); |
| 2626 | |
| 2627 | YCbCrLayout yu12Thumb; |
| 2628 | if (outputThumbnail) { |
| 2629 | ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb); |
| 2630 | |
| 2631 | if (ret != 0) { |
| 2632 | return lfail("%s: crop and scale thumbnail failed!", __FUNCTION__); |
| 2633 | } |
| 2634 | } |
| 2635 | |
| 2636 | /* Scale and crop main jpeg */ |
| 2637 | ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main); |
| 2638 | |
| 2639 | if (ret != 0) { |
| 2640 | return lfail("%s: crop and scale main failed!", __FUNCTION__); |
| 2641 | } |
| 2642 | |
| 2643 | /* Encode the thumbnail image */ |
| 2644 | if (outputThumbnail) { |
| 2645 | ret = encodeJpegYU12(thumbSize, yu12Thumb, thumbQuality, 0, 0, &thumbCode[0], |
| 2646 | maxThumbCodeSize, thumbCodeSize); |
| 2647 | |
| 2648 | if (ret != 0) { |
| 2649 | return lfail("%s: thumbnail encodeJpegYU12 failed with %d", __FUNCTION__, ret); |
| 2650 | } |
| 2651 | } |
| 2652 | |
| 2653 | /* Combine camera characteristics with request settings to form EXIF |
| 2654 | * metadata */ |
| 2655 | common::V1_0::helper::CameraMetadata meta(mCameraCharacteristics); |
| 2656 | meta.append(setting); |
| 2657 | |
| 2658 | /* Generate EXIF object */ |
| 2659 | std::unique_ptr<ExifUtils> utils(ExifUtils::create()); |
| 2660 | /* Make sure it's initialized */ |
| 2661 | utils->initialize(); |
| 2662 | |
| 2663 | utils->setFromMetadata(meta, jpegSize.width, jpegSize.height); |
| 2664 | utils->setMake(mExifMake); |
| 2665 | utils->setModel(mExifModel); |
| 2666 | |
| 2667 | ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : nullptr, thumbCodeSize); |
| 2668 | |
| 2669 | if (!ret) { |
| 2670 | return lfail("%s: generating APP1 failed", __FUNCTION__); |
| 2671 | } |
| 2672 | |
| 2673 | /* Get internal buffer */ |
| 2674 | size_t exifDataSize = utils->getApp1Length(); |
| 2675 | const uint8_t* exifData = utils->getApp1Buffer(); |
| 2676 | |
| 2677 | /* Lock the HAL jpeg code buffer */ |
| 2678 | void* bufPtr = sHandleImporter.lock(*(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), |
| 2679 | maxJpegCodeSize); |
| 2680 | |
| 2681 | if (!bufPtr) { |
| 2682 | return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize); |
| 2683 | } |
| 2684 | |
| 2685 | /* Encode the main jpeg image */ |
| 2686 | ret = encodeJpegYU12(jpegSize, yu12Main, jpegQuality, exifData, exifDataSize, bufPtr, |
| 2687 | maxJpegCodeSize, jpegCodeSize); |
| 2688 | |
| 2689 | /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out |
| 2690 | * and do this when returning buffer to parent */ |
| 2691 | CameraBlob blob{CameraBlobId::JPEG, static_cast<int32_t>(jpegCodeSize)}; |
| 2692 | void* blobDst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) + maxJpegCodeSize - |
| 2693 | sizeof(CameraBlob)); |
| 2694 | memcpy(blobDst, &blob, sizeof(CameraBlob)); |
| 2695 | |
| 2696 | /* Unlock the HAL jpeg code buffer */ |
| 2697 | int relFence = sHandleImporter.unlock(*(halBuf.bufPtr)); |
| 2698 | if (relFence >= 0) { |
| 2699 | halBuf.acquireFence = relFence; |
| 2700 | } |
| 2701 | |
| 2702 | /* Check if our JPEG actually succeeded */ |
| 2703 | if (ret != 0) { |
| 2704 | return lfail("%s: encodeJpegYU12 failed with %d", __FUNCTION__, ret); |
| 2705 | } |
| 2706 | |
| 2707 | ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu", __FUNCTION__, ret, jpegQuality, |
| 2708 | maxJpegCodeSize); |
| 2709 | |
| 2710 | return 0; |
| 2711 | } |
| 2712 | |
| 2713 | void ExternalCameraDeviceSession::OutputThread::clearIntermediateBuffers() { |
| 2714 | std::lock_guard<std::mutex> lk(mBufferLock); |
| 2715 | mYu12Frame.reset(); |
| 2716 | mYu12ThumbFrame.reset(); |
| 2717 | mIntermediateBuffers.clear(); |
| 2718 | mMuteTestPatternFrame.clear(); |
| 2719 | mBlobBufferSize = 0; |
| 2720 | } |
| 2721 | |
| 2722 | bool ExternalCameraDeviceSession::OutputThread::threadLoop() { |
| 2723 | std::shared_ptr<HalRequest> req; |
| 2724 | auto parent = mParent.lock(); |
| 2725 | if (parent == nullptr) { |
| 2726 | ALOGE("%s: session has been disconnected!", __FUNCTION__); |
| 2727 | return false; |
| 2728 | } |
| 2729 | |
| 2730 | // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames |
| 2731 | // regularly to prevent v4l buffer queue filled with stale buffers |
| 2732 | // when app doesn't program a preview request |
| 2733 | waitForNextRequest(&req); |
| 2734 | if (req == nullptr) { |
| 2735 | // No new request, wait again |
| 2736 | return true; |
| 2737 | } |
| 2738 | |
| 2739 | auto onDeviceError = [&](auto... args) { |
| 2740 | ALOGE(args...); |
| 2741 | parent->notifyError(req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_DEVICE); |
| 2742 | signalRequestDone(); |
| 2743 | return false; |
| 2744 | }; |
| 2745 | |
| 2746 | if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) { |
| 2747 | return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__, |
| 2748 | req->frameIn->mFourcc & 0xFF, (req->frameIn->mFourcc >> 8) & 0xFF, |
| 2749 | (req->frameIn->mFourcc >> 16) & 0xFF, |
| 2750 | (req->frameIn->mFourcc >> 24) & 0xFF); |
| 2751 | } |
| 2752 | |
| 2753 | int res = requestBufferStart(req->buffers); |
| 2754 | if (res != 0) { |
| 2755 | ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res); |
| 2756 | return onDeviceError("%s: failed to send buffer request!", __FUNCTION__); |
| 2757 | } |
| 2758 | |
| 2759 | std::unique_lock<std::mutex> lk(mBufferLock); |
| 2760 | // Convert input V4L2 frame to YU12 of the same size |
| 2761 | // TODO: see if we can save some computation by converting to YV12 here |
| 2762 | uint8_t* inData; |
| 2763 | size_t inDataSize; |
| 2764 | if (req->frameIn->getData(&inData, &inDataSize) != 0) { |
| 2765 | lk.unlock(); |
| 2766 | return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__); |
| 2767 | } |
| 2768 | |
| 2769 | // Process camera mute state |
| 2770 | auto testPatternMode = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_MODE); |
| 2771 | if (testPatternMode.count == 1) { |
| 2772 | if (mCameraMuted != (testPatternMode.data.u8[0] != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF)) { |
| 2773 | mCameraMuted = !mCameraMuted; |
| 2774 | // Get solid color for test pattern, if any was set |
| 2775 | if (testPatternMode.data.u8[0] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) { |
| 2776 | auto entry = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_DATA); |
| 2777 | if (entry.count == 4) { |
| 2778 | // Update the mute frame if the pattern color has changed |
| 2779 | if (memcmp(entry.data.i32, mTestPatternData, sizeof(mTestPatternData)) != 0) { |
| 2780 | memcpy(mTestPatternData, entry.data.i32, sizeof(mTestPatternData)); |
| 2781 | // Fill the mute frame with the solid color, use only 8 MSB of RGGB as RGB |
| 2782 | for (int i = 0; i < mMuteTestPatternFrame.size(); i += 3) { |
| 2783 | mMuteTestPatternFrame[i] = entry.data.i32[0] >> 24; |
| 2784 | mMuteTestPatternFrame[i + 1] = entry.data.i32[1] >> 24; |
| 2785 | mMuteTestPatternFrame[i + 2] = entry.data.i32[3] >> 24; |
| 2786 | } |
| 2787 | } |
| 2788 | } |
| 2789 | } |
| 2790 | } |
| 2791 | } |
| 2792 | |
| 2793 | // TODO: in some special case maybe we can decode jpg directly to gralloc output? |
| 2794 | if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) { |
| 2795 | ATRACE_BEGIN("MJPGtoI420"); |
| 2796 | res = 0; |
| 2797 | if (mCameraMuted) { |
| 2798 | res = libyuv::ConvertToI420( |
| 2799 | mMuteTestPatternFrame.data(), mMuteTestPatternFrame.size(), |
| 2800 | static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride, |
| 2801 | static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride, |
| 2802 | static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride, 0, 0, |
| 2803 | mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth, |
| 2804 | mYu12Frame->mHeight, libyuv::kRotate0, libyuv::FOURCC_RAW); |
| 2805 | } else { |
| 2806 | res = libyuv::MJPGToI420( |
| 2807 | inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y), |
| 2808 | mYu12FrameLayout.yStride, static_cast<uint8_t*>(mYu12FrameLayout.cb), |
| 2809 | mYu12FrameLayout.cStride, static_cast<uint8_t*>(mYu12FrameLayout.cr), |
| 2810 | mYu12FrameLayout.cStride, mYu12Frame->mWidth, mYu12Frame->mHeight, |
| 2811 | mYu12Frame->mWidth, mYu12Frame->mHeight); |
| 2812 | } |
| 2813 | ATRACE_END(); |
| 2814 | |
| 2815 | if (res != 0) { |
| 2816 | // For some webcam, the first few V4L2 frames might be malformed... |
| 2817 | ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res); |
| 2818 | lk.unlock(); |
| 2819 | Status st = parent->processCaptureRequestError(req); |
| 2820 | if (st != Status::OK) { |
| 2821 | return onDeviceError("%s: failed to process capture request error!", __FUNCTION__); |
| 2822 | } |
| 2823 | signalRequestDone(); |
| 2824 | return true; |
| 2825 | } |
| 2826 | } |
| 2827 | |
| 2828 | ATRACE_BEGIN("Wait for BufferRequest done"); |
| 2829 | res = waitForBufferRequestDone(&req->buffers); |
| 2830 | ATRACE_END(); |
| 2831 | |
| 2832 | if (res != 0) { |
| 2833 | ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res); |
| 2834 | lk.unlock(); |
| 2835 | return onDeviceError("%s: failed to process buffer request error!", __FUNCTION__); |
| 2836 | } |
| 2837 | |
| 2838 | ALOGV("%s processing new request", __FUNCTION__); |
| 2839 | const int kSyncWaitTimeoutMs = 500; |
| 2840 | for (auto& halBuf : req->buffers) { |
| 2841 | if (*(halBuf.bufPtr) == nullptr) { |
| 2842 | ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId); |
| 2843 | halBuf.fenceTimeout = true; |
| 2844 | } else if (halBuf.acquireFence >= 0) { |
| 2845 | int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs); |
| 2846 | if (ret) { |
| 2847 | halBuf.fenceTimeout = true; |
| 2848 | } else { |
| 2849 | ::close(halBuf.acquireFence); |
| 2850 | halBuf.acquireFence = -1; |
| 2851 | } |
| 2852 | } |
| 2853 | |
| 2854 | if (halBuf.fenceTimeout) { |
| 2855 | continue; |
| 2856 | } |
| 2857 | |
| 2858 | // Gralloc lockYCbCr the buffer |
| 2859 | switch (halBuf.format) { |
| 2860 | case PixelFormat::BLOB: { |
| 2861 | int ret = createJpegLocked(halBuf, req->setting); |
| 2862 | |
| 2863 | if (ret != 0) { |
| 2864 | lk.unlock(); |
| 2865 | return onDeviceError("%s: createJpegLocked failed with %d", __FUNCTION__, ret); |
| 2866 | } |
| 2867 | } break; |
| 2868 | case PixelFormat::Y16: { |
| 2869 | void* outLayout = sHandleImporter.lock( |
| 2870 | *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), inDataSize); |
| 2871 | |
| 2872 | std::memcpy(outLayout, inData, inDataSize); |
| 2873 | |
| 2874 | int relFence = sHandleImporter.unlock(*(halBuf.bufPtr)); |
| 2875 | if (relFence >= 0) { |
| 2876 | halBuf.acquireFence = relFence; |
| 2877 | } |
| 2878 | } break; |
| 2879 | case PixelFormat::YCBCR_420_888: |
| 2880 | case PixelFormat::YV12: { |
Devin Moore | 523660c | 2023-10-02 15:55:11 +0000 | [diff] [blame] | 2881 | android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width), |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 2882 | static_cast<int32_t>(halBuf.height)}; |
Devin Moore | 523660c | 2023-10-02 15:55:11 +0000 | [diff] [blame] | 2883 | android_ycbcr result = sHandleImporter.lockYCbCr( |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 2884 | *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect); |
Devin Moore | 523660c | 2023-10-02 15:55:11 +0000 | [diff] [blame] | 2885 | ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__, |
| 2886 | result.y, result.cb, result.cr, result.ystride, result.cstride, |
| 2887 | result.chroma_step); |
| 2888 | if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX || |
| 2889 | result.chroma_step > UINT32_MAX) { |
| 2890 | return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__); |
| 2891 | } |
| 2892 | YCbCrLayout outLayout = {.y = result.y, |
| 2893 | .cb = result.cb, |
| 2894 | .cr = result.cr, |
| 2895 | .yStride = static_cast<uint32_t>(result.ystride), |
| 2896 | .cStride = static_cast<uint32_t>(result.cstride), |
| 2897 | .chromaStep = static_cast<uint32_t>(result.chroma_step)}; |
Avichal Rakesh | e1857f8 | 2022-06-08 17:47:23 -0700 | [diff] [blame] | 2898 | |
| 2899 | // Convert to output buffer size/format |
| 2900 | uint32_t outputFourcc = getFourCcFromLayout(outLayout); |
| 2901 | ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__, outputFourcc & 0xFF, |
| 2902 | (outputFourcc >> 8) & 0xFF, (outputFourcc >> 16) & 0xFF, |
| 2903 | (outputFourcc >> 24) & 0xFF); |
| 2904 | |
| 2905 | YCbCrLayout cropAndScaled; |
| 2906 | ATRACE_BEGIN("cropAndScaleLocked"); |
| 2907 | int ret = cropAndScaleLocked(mYu12Frame, Size{halBuf.width, halBuf.height}, |
| 2908 | &cropAndScaled); |
| 2909 | ATRACE_END(); |
| 2910 | if (ret != 0) { |
| 2911 | lk.unlock(); |
| 2912 | return onDeviceError("%s: crop and scale failed!", __FUNCTION__); |
| 2913 | } |
| 2914 | |
| 2915 | Size sz{halBuf.width, halBuf.height}; |
| 2916 | ATRACE_BEGIN("formatConvert"); |
| 2917 | ret = formatConvert(cropAndScaled, outLayout, sz, outputFourcc); |
| 2918 | ATRACE_END(); |
| 2919 | if (ret != 0) { |
| 2920 | lk.unlock(); |
| 2921 | return onDeviceError("%s: format conversion failed!", __FUNCTION__); |
| 2922 | } |
| 2923 | int relFence = sHandleImporter.unlock(*(halBuf.bufPtr)); |
| 2924 | if (relFence >= 0) { |
| 2925 | halBuf.acquireFence = relFence; |
| 2926 | } |
| 2927 | } break; |
| 2928 | default: |
| 2929 | lk.unlock(); |
| 2930 | return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format); |
| 2931 | } |
| 2932 | } // for each buffer |
| 2933 | mScaledYu12Frames.clear(); |
| 2934 | |
| 2935 | // Don't hold the lock while calling back to parent |
| 2936 | lk.unlock(); |
| 2937 | Status st = parent->processCaptureResult(req); |
| 2938 | if (st != Status::OK) { |
| 2939 | return onDeviceError("%s: failed to process capture result!", __FUNCTION__); |
| 2940 | } |
| 2941 | signalRequestDone(); |
| 2942 | return true; |
| 2943 | } |
| 2944 | |
| 2945 | // End ExternalCameraDeviceSession::OutputThread functions |
| 2946 | |
| 2947 | } // namespace implementation |
| 2948 | } // namespace device |
| 2949 | } // namespace camera |
| 2950 | } // namespace hardware |
| 2951 | } // namespace android |