Camera3Device.cpp revision efff1c4ba2bf195d97de2fd5718b708e4b942901
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "Camera3-Device" 18#define ATRACE_TAG ATRACE_TAG_CAMERA 19//#define LOG_NDEBUG 0 20//#define LOG_NNDEBUG 0 // Per-frame verbose logging 21 22#ifdef LOG_NNDEBUG 23#define ALOGVV(...) ALOGV(__VA_ARGS__) 24#else 25#define ALOGVV(...) ((void)0) 26#endif 27 28// Convenience macro for transient errors 29#define CLOGE(fmt, ...) ALOGE("Camera %d: %s: " fmt, mId, __FUNCTION__, \ 30 ##__VA_ARGS__) 31 32// Convenience macros for transitioning to the error state 33#define SET_ERR(fmt, ...) setErrorState( \ 34 "%s: " fmt, __FUNCTION__, \ 35 ##__VA_ARGS__) 36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \ 37 "%s: " fmt, __FUNCTION__, \ 38 ##__VA_ARGS__) 39 40#include <inttypes.h> 41 42#include <utils/Log.h> 43#include <utils/Trace.h> 44#include <utils/Timers.h> 45 46#include "utils/CameraTraces.h" 47#include "device3/Camera3Device.h" 48#include "device3/Camera3OutputStream.h" 49#include "device3/Camera3InputStream.h" 50#include "device3/Camera3ZslStream.h" 51#include "device3/Camera3DummyStream.h" 52#include "CameraService.h" 53 54using namespace android::camera3; 55 56namespace android { 57 58Camera3Device::Camera3Device(int id): 59 mId(id), 60 mIsConstrainedHighSpeedConfiguration(false), 61 mHal3Device(NULL), 62 mStatus(STATUS_UNINITIALIZED), 63 mStatusWaiters(0), 64 mUsePartialResult(false), 65 mNumPartialResults(1), 66 mNextResultFrameNumber(0), 67 mNextReprocessResultFrameNumber(0), 68 mNextShutterFrameNumber(0), 69 mListener(NULL) 70{ 71 ATRACE_CALL(); 72 camera3_callback_ops::notify = &sNotify; 73 camera3_callback_ops::process_capture_result = &sProcessCaptureResult; 74 ALOGV("%s: Created device for camera %d", __FUNCTION__, id); 75} 76 77Camera3Device::~Camera3Device() 78{ 79 ATRACE_CALL(); 80 ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId); 81 disconnect(); 82} 83 84int Camera3Device::getId() const { 85 return mId; 86} 87 88/** 89 * CameraDeviceBase interface 90 */ 91 92status_t Camera3Device::initialize(CameraModule *module) 93{ 94 ATRACE_CALL(); 95 Mutex::Autolock il(mInterfaceLock); 96 Mutex::Autolock l(mLock); 97 98 ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId); 99 if (mStatus != STATUS_UNINITIALIZED) { 100 CLOGE("Already initialized!"); 101 return INVALID_OPERATION; 102 } 103 104 /** Open HAL device */ 105 106 status_t res; 107 String8 deviceName = String8::format("%d", mId); 108 109 camera3_device_t *device; 110 111 ATRACE_BEGIN("camera3->open"); 112 res = module->open(deviceName.string(), 113 reinterpret_cast<hw_device_t**>(&device)); 114 ATRACE_END(); 115 116 if (res != OK) { 117 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res); 118 return res; 119 } 120 121 /** Cross-check device version */ 122 if (device->common.version < CAMERA_DEVICE_API_VERSION_3_0) { 123 SET_ERR_L("Could not open camera: " 124 "Camera device should be at least %x, reports %x instead", 125 CAMERA_DEVICE_API_VERSION_3_0, 126 device->common.version); 127 device->common.close(&device->common); 128 return BAD_VALUE; 129 } 130 131 camera_info info; 132 res = CameraService::filterGetInfoErrorCode(module->getCameraInfo( 133 mId, &info)); 134 if (res != OK) return res; 135 136 if (info.device_version != device->common.version) { 137 SET_ERR_L("HAL reporting mismatched camera_info version (%x)" 138 " and device version (%x).", 139 info.device_version, device->common.version); 140 device->common.close(&device->common); 141 return BAD_VALUE; 142 } 143 144 /** Initialize device with callback functions */ 145 146 ATRACE_BEGIN("camera3->initialize"); 147 res = device->ops->initialize(device, this); 148 ATRACE_END(); 149 150 if (res != OK) { 151 SET_ERR_L("Unable to initialize HAL device: %s (%d)", 152 strerror(-res), res); 153 device->common.close(&device->common); 154 return BAD_VALUE; 155 } 156 157 /** Start up status tracker thread */ 158 mStatusTracker = new StatusTracker(this); 159 res = mStatusTracker->run(String8::format("C3Dev-%d-Status", mId).string()); 160 if (res != OK) { 161 SET_ERR_L("Unable to start status tracking thread: %s (%d)", 162 strerror(-res), res); 163 device->common.close(&device->common); 164 mStatusTracker.clear(); 165 return res; 166 } 167 168 bool aeLockAvailable = false; 169 camera_metadata_ro_entry aeLockAvailableEntry; 170 res = find_camera_metadata_ro_entry(info.static_camera_characteristics, 171 ANDROID_CONTROL_AE_LOCK_AVAILABLE, &aeLockAvailableEntry); 172 if (res == OK && aeLockAvailableEntry.count > 0) { 173 aeLockAvailable = (aeLockAvailableEntry.data.u8[0] == 174 ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE); 175 } 176 177 /** Start up request queue thread */ 178 mRequestThread = new RequestThread(this, mStatusTracker, device, aeLockAvailable); 179 res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string()); 180 if (res != OK) { 181 SET_ERR_L("Unable to start request queue thread: %s (%d)", 182 strerror(-res), res); 183 device->common.close(&device->common); 184 mRequestThread.clear(); 185 return res; 186 } 187 188 mPreparerThread = new PreparerThread(); 189 190 /** Everything is good to go */ 191 192 mDeviceVersion = device->common.version; 193 mDeviceInfo = info.static_camera_characteristics; 194 mHal3Device = device; 195 196 internalUpdateStatusLocked(STATUS_UNCONFIGURED); 197 mNextStreamId = 0; 198 mDummyStreamId = NO_STREAM; 199 mNeedConfig = true; 200 mPauseStateNotify = false; 201 202 // Will the HAL be sending in early partial result metadata? 203 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) { 204 camera_metadata_entry partialResultsCount = 205 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT); 206 if (partialResultsCount.count > 0) { 207 mNumPartialResults = partialResultsCount.data.i32[0]; 208 mUsePartialResult = (mNumPartialResults > 1); 209 } 210 } else { 211 camera_metadata_entry partialResultsQuirk = 212 mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT); 213 if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) { 214 mUsePartialResult = true; 215 } 216 } 217 218 camera_metadata_entry configs = 219 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS); 220 for (uint32_t i = 0; i < configs.count; i += 4) { 221 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED && 222 configs.data.i32[i + 3] == 223 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) { 224 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1], 225 configs.data.i32[i + 2])); 226 } 227 } 228 229 return OK; 230} 231 232status_t Camera3Device::disconnect() { 233 ATRACE_CALL(); 234 Mutex::Autolock il(mInterfaceLock); 235 236 ALOGV("%s: E", __FUNCTION__); 237 238 status_t res = OK; 239 240 { 241 Mutex::Autolock l(mLock); 242 if (mStatus == STATUS_UNINITIALIZED) return res; 243 244 if (mStatus == STATUS_ACTIVE || 245 (mStatus == STATUS_ERROR && mRequestThread != NULL)) { 246 res = mRequestThread->clearRepeatingRequests(); 247 if (res != OK) { 248 SET_ERR_L("Can't stop streaming"); 249 // Continue to close device even in case of error 250 } else { 251 res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout); 252 if (res != OK) { 253 SET_ERR_L("Timeout waiting for HAL to drain"); 254 // Continue to close device even in case of error 255 } 256 } 257 } 258 259 if (mStatus == STATUS_ERROR) { 260 CLOGE("Shutting down in an error state"); 261 } 262 263 if (mStatusTracker != NULL) { 264 mStatusTracker->requestExit(); 265 } 266 267 if (mRequestThread != NULL) { 268 mRequestThread->requestExit(); 269 } 270 271 mOutputStreams.clear(); 272 mInputStream.clear(); 273 } 274 275 // Joining done without holding mLock, otherwise deadlocks may ensue 276 // as the threads try to access parent state 277 if (mRequestThread != NULL && mStatus != STATUS_ERROR) { 278 // HAL may be in a bad state, so waiting for request thread 279 // (which may be stuck in the HAL processCaptureRequest call) 280 // could be dangerous. 281 mRequestThread->join(); 282 } 283 284 if (mStatusTracker != NULL) { 285 mStatusTracker->join(); 286 } 287 288 camera3_device_t *hal3Device; 289 { 290 Mutex::Autolock l(mLock); 291 292 mRequestThread.clear(); 293 mStatusTracker.clear(); 294 295 hal3Device = mHal3Device; 296 } 297 298 // Call close without internal mutex held, as the HAL close may need to 299 // wait on assorted callbacks,etc, to complete before it can return. 300 if (hal3Device != NULL) { 301 ATRACE_BEGIN("camera3->close"); 302 hal3Device->common.close(&hal3Device->common); 303 ATRACE_END(); 304 } 305 306 { 307 Mutex::Autolock l(mLock); 308 mHal3Device = NULL; 309 internalUpdateStatusLocked(STATUS_UNINITIALIZED); 310 } 311 312 ALOGV("%s: X", __FUNCTION__); 313 return res; 314} 315 316// For dumping/debugging only - 317// try to acquire a lock a few times, eventually give up to proceed with 318// debug/dump operations 319bool Camera3Device::tryLockSpinRightRound(Mutex& lock) { 320 bool gotLock = false; 321 for (size_t i = 0; i < kDumpLockAttempts; ++i) { 322 if (lock.tryLock() == NO_ERROR) { 323 gotLock = true; 324 break; 325 } else { 326 usleep(kDumpSleepDuration); 327 } 328 } 329 return gotLock; 330} 331 332Camera3Device::Size Camera3Device::getMaxJpegResolution() const { 333 int32_t maxJpegWidth = 0, maxJpegHeight = 0; 334 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) { 335 const int STREAM_CONFIGURATION_SIZE = 4; 336 const int STREAM_FORMAT_OFFSET = 0; 337 const int STREAM_WIDTH_OFFSET = 1; 338 const int STREAM_HEIGHT_OFFSET = 2; 339 const int STREAM_IS_INPUT_OFFSET = 3; 340 camera_metadata_ro_entry_t availableStreamConfigs = 341 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS); 342 if (availableStreamConfigs.count == 0 || 343 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) { 344 return Size(0, 0); 345 } 346 347 // Get max jpeg size (area-wise). 348 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) { 349 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET]; 350 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET]; 351 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET]; 352 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET]; 353 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT 354 && format == HAL_PIXEL_FORMAT_BLOB && 355 (width * height > maxJpegWidth * maxJpegHeight)) { 356 maxJpegWidth = width; 357 maxJpegHeight = height; 358 } 359 } 360 } else { 361 camera_metadata_ro_entry availableJpegSizes = 362 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES); 363 if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) { 364 return Size(0, 0); 365 } 366 367 // Get max jpeg size (area-wise). 368 for (size_t i = 0; i < availableJpegSizes.count; i += 2) { 369 if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1]) 370 > (maxJpegWidth * maxJpegHeight)) { 371 maxJpegWidth = availableJpegSizes.data.i32[i]; 372 maxJpegHeight = availableJpegSizes.data.i32[i + 1]; 373 } 374 } 375 } 376 return Size(maxJpegWidth, maxJpegHeight); 377} 378 379ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const { 380 // Get max jpeg size (area-wise). 381 Size maxJpegResolution = getMaxJpegResolution(); 382 if (maxJpegResolution.width == 0) { 383 ALOGE("%s: Camera %d: Can't find valid available jpeg sizes in static metadata!", 384 __FUNCTION__, mId); 385 return BAD_VALUE; 386 } 387 388 // Get max jpeg buffer size 389 ssize_t maxJpegBufferSize = 0; 390 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE); 391 if (jpegBufMaxSize.count == 0) { 392 ALOGE("%s: Camera %d: Can't find maximum JPEG size in static metadata!", __FUNCTION__, mId); 393 return BAD_VALUE; 394 } 395 maxJpegBufferSize = jpegBufMaxSize.data.i32[0]; 396 assert(kMinJpegBufferSize < maxJpegBufferSize); 397 398 // Calculate final jpeg buffer size for the given resolution. 399 float scaleFactor = ((float) (width * height)) / 400 (maxJpegResolution.width * maxJpegResolution.height); 401 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) + 402 kMinJpegBufferSize; 403 if (jpegBufferSize > maxJpegBufferSize) { 404 jpegBufferSize = maxJpegBufferSize; 405 } 406 407 return jpegBufferSize; 408} 409 410ssize_t Camera3Device::getPointCloudBufferSize() const { 411 const int FLOATS_PER_POINT=4; 412 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES); 413 if (maxPointCount.count == 0) { 414 ALOGE("%s: Camera %d: Can't find maximum depth point cloud size in static metadata!", 415 __FUNCTION__, mId); 416 return BAD_VALUE; 417 } 418 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) + 419 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT; 420 return maxBytesForPointCloud; 421} 422 423 424 425status_t Camera3Device::dump(int fd, const Vector<String16> &args) { 426 ATRACE_CALL(); 427 (void)args; 428 429 // Try to lock, but continue in case of failure (to avoid blocking in 430 // deadlocks) 431 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock); 432 bool gotLock = tryLockSpinRightRound(mLock); 433 434 ALOGW_IF(!gotInterfaceLock, 435 "Camera %d: %s: Unable to lock interface lock, proceeding anyway", 436 mId, __FUNCTION__); 437 ALOGW_IF(!gotLock, 438 "Camera %d: %s: Unable to lock main lock, proceeding anyway", 439 mId, __FUNCTION__); 440 441 String8 lines; 442 443 const char *status = 444 mStatus == STATUS_ERROR ? "ERROR" : 445 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" : 446 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" : 447 mStatus == STATUS_CONFIGURED ? "CONFIGURED" : 448 mStatus == STATUS_ACTIVE ? "ACTIVE" : 449 "Unknown"; 450 451 lines.appendFormat(" Device status: %s\n", status); 452 if (mStatus == STATUS_ERROR) { 453 lines.appendFormat(" Error cause: %s\n", mErrorCause.string()); 454 } 455 lines.appendFormat(" Stream configuration:\n"); 456 lines.appendFormat(" Operation mode: %s \n", mIsConstrainedHighSpeedConfiguration ? 457 "CONSTRAINED HIGH SPEED VIDEO" : "NORMAL"); 458 459 if (mInputStream != NULL) { 460 write(fd, lines.string(), lines.size()); 461 mInputStream->dump(fd, args); 462 } else { 463 lines.appendFormat(" No input stream.\n"); 464 write(fd, lines.string(), lines.size()); 465 } 466 for (size_t i = 0; i < mOutputStreams.size(); i++) { 467 mOutputStreams[i]->dump(fd,args); 468 } 469 470 lines = String8(" In-flight requests:\n"); 471 if (mInFlightMap.size() == 0) { 472 lines.append(" None\n"); 473 } else { 474 for (size_t i = 0; i < mInFlightMap.size(); i++) { 475 InFlightRequest r = mInFlightMap.valueAt(i); 476 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata" 477 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i), 478 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false", 479 r.numBuffersLeft); 480 } 481 } 482 write(fd, lines.string(), lines.size()); 483 484 { 485 lines = String8(" Last request sent:\n"); 486 write(fd, lines.string(), lines.size()); 487 488 CameraMetadata lastRequest = getLatestRequestLocked(); 489 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6); 490 } 491 492 if (mHal3Device != NULL) { 493 lines = String8(" HAL device dump:\n"); 494 write(fd, lines.string(), lines.size()); 495 mHal3Device->ops->dump(mHal3Device, fd); 496 } 497 498 if (gotLock) mLock.unlock(); 499 if (gotInterfaceLock) mInterfaceLock.unlock(); 500 501 return OK; 502} 503 504const CameraMetadata& Camera3Device::info() const { 505 ALOGVV("%s: E", __FUNCTION__); 506 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED || 507 mStatus == STATUS_ERROR)) { 508 ALOGW("%s: Access to static info %s!", __FUNCTION__, 509 mStatus == STATUS_ERROR ? 510 "when in error state" : "before init"); 511 } 512 return mDeviceInfo; 513} 514 515status_t Camera3Device::checkStatusOkToCaptureLocked() { 516 switch (mStatus) { 517 case STATUS_ERROR: 518 CLOGE("Device has encountered a serious error"); 519 return INVALID_OPERATION; 520 case STATUS_UNINITIALIZED: 521 CLOGE("Device not initialized"); 522 return INVALID_OPERATION; 523 case STATUS_UNCONFIGURED: 524 case STATUS_CONFIGURED: 525 case STATUS_ACTIVE: 526 // OK 527 break; 528 default: 529 SET_ERR_L("Unexpected status: %d", mStatus); 530 return INVALID_OPERATION; 531 } 532 return OK; 533} 534 535status_t Camera3Device::convertMetadataListToRequestListLocked( 536 const List<const CameraMetadata> &metadataList, RequestList *requestList) { 537 if (requestList == NULL) { 538 CLOGE("requestList cannot be NULL."); 539 return BAD_VALUE; 540 } 541 542 int32_t burstId = 0; 543 for (List<const CameraMetadata>::const_iterator it = metadataList.begin(); 544 it != metadataList.end(); ++it) { 545 sp<CaptureRequest> newRequest = setUpRequestLocked(*it); 546 if (newRequest == 0) { 547 CLOGE("Can't create capture request"); 548 return BAD_VALUE; 549 } 550 551 // Setup burst Id and request Id 552 newRequest->mResultExtras.burstId = burstId++; 553 if (it->exists(ANDROID_REQUEST_ID)) { 554 if (it->find(ANDROID_REQUEST_ID).count == 0) { 555 CLOGE("RequestID entry exists; but must not be empty in metadata"); 556 return BAD_VALUE; 557 } 558 newRequest->mResultExtras.requestId = it->find(ANDROID_REQUEST_ID).data.i32[0]; 559 } else { 560 CLOGE("RequestID does not exist in metadata"); 561 return BAD_VALUE; 562 } 563 564 requestList->push_back(newRequest); 565 566 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId); 567 } 568 return OK; 569} 570 571status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) { 572 ATRACE_CALL(); 573 574 List<const CameraMetadata> requests; 575 requests.push_back(request); 576 return captureList(requests, /*lastFrameNumber*/NULL); 577} 578 579status_t Camera3Device::submitRequestsHelper( 580 const List<const CameraMetadata> &requests, bool repeating, 581 /*out*/ 582 int64_t *lastFrameNumber) { 583 ATRACE_CALL(); 584 Mutex::Autolock il(mInterfaceLock); 585 Mutex::Autolock l(mLock); 586 587 status_t res = checkStatusOkToCaptureLocked(); 588 if (res != OK) { 589 // error logged by previous call 590 return res; 591 } 592 593 RequestList requestList; 594 595 res = convertMetadataListToRequestListLocked(requests, /*out*/&requestList); 596 if (res != OK) { 597 // error logged by previous call 598 return res; 599 } 600 601 if (repeating) { 602 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber); 603 } else { 604 res = mRequestThread->queueRequestList(requestList, lastFrameNumber); 605 } 606 607 if (res == OK) { 608 waitUntilStateThenRelock(/*active*/true, kActiveTimeout); 609 if (res != OK) { 610 SET_ERR_L("Can't transition to active in %f seconds!", 611 kActiveTimeout/1e9); 612 } 613 ALOGV("Camera %d: Capture request %" PRId32 " enqueued", mId, 614 (*(requestList.begin()))->mResultExtras.requestId); 615 } else { 616 CLOGE("Cannot queue request. Impossible."); 617 return BAD_VALUE; 618 } 619 620 return res; 621} 622 623status_t Camera3Device::captureList(const List<const CameraMetadata> &requests, 624 int64_t *lastFrameNumber) { 625 ATRACE_CALL(); 626 627 return submitRequestsHelper(requests, /*repeating*/false, lastFrameNumber); 628} 629 630status_t Camera3Device::setStreamingRequest(const CameraMetadata &request, 631 int64_t* /*lastFrameNumber*/) { 632 ATRACE_CALL(); 633 634 List<const CameraMetadata> requests; 635 requests.push_back(request); 636 return setStreamingRequestList(requests, /*lastFrameNumber*/NULL); 637} 638 639status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests, 640 int64_t *lastFrameNumber) { 641 ATRACE_CALL(); 642 643 return submitRequestsHelper(requests, /*repeating*/true, lastFrameNumber); 644} 645 646sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked( 647 const CameraMetadata &request) { 648 status_t res; 649 650 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) { 651 res = configureStreamsLocked(); 652 // Stream configuration failed due to unsupported configuration. 653 // Device back to unconfigured state. Client might try other configuraitons 654 if (res == BAD_VALUE && mStatus == STATUS_UNCONFIGURED) { 655 CLOGE("No streams configured"); 656 return NULL; 657 } 658 // Stream configuration failed for other reason. Fatal. 659 if (res != OK) { 660 SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res); 661 return NULL; 662 } 663 // Stream configuration successfully configure to empty stream configuration. 664 if (mStatus == STATUS_UNCONFIGURED) { 665 CLOGE("No streams configured"); 666 return NULL; 667 } 668 } 669 670 sp<CaptureRequest> newRequest = createCaptureRequest(request); 671 return newRequest; 672} 673 674status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) { 675 ATRACE_CALL(); 676 Mutex::Autolock il(mInterfaceLock); 677 Mutex::Autolock l(mLock); 678 679 switch (mStatus) { 680 case STATUS_ERROR: 681 CLOGE("Device has encountered a serious error"); 682 return INVALID_OPERATION; 683 case STATUS_UNINITIALIZED: 684 CLOGE("Device not initialized"); 685 return INVALID_OPERATION; 686 case STATUS_UNCONFIGURED: 687 case STATUS_CONFIGURED: 688 case STATUS_ACTIVE: 689 // OK 690 break; 691 default: 692 SET_ERR_L("Unexpected status: %d", mStatus); 693 return INVALID_OPERATION; 694 } 695 ALOGV("Camera %d: Clearing repeating request", mId); 696 697 return mRequestThread->clearRepeatingRequests(lastFrameNumber); 698} 699 700status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) { 701 ATRACE_CALL(); 702 Mutex::Autolock il(mInterfaceLock); 703 704 return mRequestThread->waitUntilRequestProcessed(requestId, timeout); 705} 706 707status_t Camera3Device::createInputStream( 708 uint32_t width, uint32_t height, int format, int *id) { 709 ATRACE_CALL(); 710 Mutex::Autolock il(mInterfaceLock); 711 Mutex::Autolock l(mLock); 712 ALOGV("Camera %d: Creating new input stream %d: %d x %d, format %d", 713 mId, mNextStreamId, width, height, format); 714 715 status_t res; 716 bool wasActive = false; 717 718 switch (mStatus) { 719 case STATUS_ERROR: 720 ALOGE("%s: Device has encountered a serious error", __FUNCTION__); 721 return INVALID_OPERATION; 722 case STATUS_UNINITIALIZED: 723 ALOGE("%s: Device not initialized", __FUNCTION__); 724 return INVALID_OPERATION; 725 case STATUS_UNCONFIGURED: 726 case STATUS_CONFIGURED: 727 // OK 728 break; 729 case STATUS_ACTIVE: 730 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 731 res = internalPauseAndWaitLocked(); 732 if (res != OK) { 733 SET_ERR_L("Can't pause captures to reconfigure streams!"); 734 return res; 735 } 736 wasActive = true; 737 break; 738 default: 739 SET_ERR_L("%s: Unexpected status: %d", mStatus); 740 return INVALID_OPERATION; 741 } 742 assert(mStatus != STATUS_ACTIVE); 743 744 if (mInputStream != 0) { 745 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__); 746 return INVALID_OPERATION; 747 } 748 749 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId, 750 width, height, format); 751 newStream->setStatusTracker(mStatusTracker); 752 753 mInputStream = newStream; 754 755 *id = mNextStreamId++; 756 757 // Continue captures if active at start 758 if (wasActive) { 759 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 760 res = configureStreamsLocked(); 761 if (res != OK) { 762 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)", 763 __FUNCTION__, mNextStreamId, strerror(-res), res); 764 return res; 765 } 766 internalResumeLocked(); 767 } 768 769 ALOGV("Camera %d: Created input stream", mId); 770 return OK; 771} 772 773 774status_t Camera3Device::createZslStream( 775 uint32_t width, uint32_t height, 776 int depth, 777 /*out*/ 778 int *id, 779 sp<Camera3ZslStream>* zslStream) { 780 ATRACE_CALL(); 781 Mutex::Autolock il(mInterfaceLock); 782 Mutex::Autolock l(mLock); 783 ALOGV("Camera %d: Creating ZSL stream %d: %d x %d, depth %d", 784 mId, mNextStreamId, width, height, depth); 785 786 status_t res; 787 bool wasActive = false; 788 789 switch (mStatus) { 790 case STATUS_ERROR: 791 ALOGE("%s: Device has encountered a serious error", __FUNCTION__); 792 return INVALID_OPERATION; 793 case STATUS_UNINITIALIZED: 794 ALOGE("%s: Device not initialized", __FUNCTION__); 795 return INVALID_OPERATION; 796 case STATUS_UNCONFIGURED: 797 case STATUS_CONFIGURED: 798 // OK 799 break; 800 case STATUS_ACTIVE: 801 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 802 res = internalPauseAndWaitLocked(); 803 if (res != OK) { 804 SET_ERR_L("Can't pause captures to reconfigure streams!"); 805 return res; 806 } 807 wasActive = true; 808 break; 809 default: 810 SET_ERR_L("Unexpected status: %d", mStatus); 811 return INVALID_OPERATION; 812 } 813 assert(mStatus != STATUS_ACTIVE); 814 815 if (mInputStream != 0) { 816 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__); 817 return INVALID_OPERATION; 818 } 819 820 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId, 821 width, height, depth); 822 newStream->setStatusTracker(mStatusTracker); 823 824 res = mOutputStreams.add(mNextStreamId, newStream); 825 if (res < 0) { 826 ALOGE("%s: Can't add new stream to set: %s (%d)", 827 __FUNCTION__, strerror(-res), res); 828 return res; 829 } 830 mInputStream = newStream; 831 832 mNeedConfig = true; 833 834 *id = mNextStreamId++; 835 *zslStream = newStream; 836 837 // Continue captures if active at start 838 if (wasActive) { 839 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 840 res = configureStreamsLocked(); 841 if (res != OK) { 842 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)", 843 __FUNCTION__, mNextStreamId, strerror(-res), res); 844 return res; 845 } 846 internalResumeLocked(); 847 } 848 849 ALOGV("Camera %d: Created ZSL stream", mId); 850 return OK; 851} 852 853status_t Camera3Device::createStream(sp<Surface> consumer, 854 uint32_t width, uint32_t height, int format, android_dataspace dataSpace, 855 camera3_stream_rotation_t rotation, int *id) { 856 ATRACE_CALL(); 857 Mutex::Autolock il(mInterfaceLock); 858 Mutex::Autolock l(mLock); 859 ALOGV("Camera %d: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d", 860 mId, mNextStreamId, width, height, format, dataSpace, rotation); 861 862 status_t res; 863 bool wasActive = false; 864 865 switch (mStatus) { 866 case STATUS_ERROR: 867 CLOGE("Device has encountered a serious error"); 868 return INVALID_OPERATION; 869 case STATUS_UNINITIALIZED: 870 CLOGE("Device not initialized"); 871 return INVALID_OPERATION; 872 case STATUS_UNCONFIGURED: 873 case STATUS_CONFIGURED: 874 // OK 875 break; 876 case STATUS_ACTIVE: 877 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 878 res = internalPauseAndWaitLocked(); 879 if (res != OK) { 880 SET_ERR_L("Can't pause captures to reconfigure streams!"); 881 return res; 882 } 883 wasActive = true; 884 break; 885 default: 886 SET_ERR_L("Unexpected status: %d", mStatus); 887 return INVALID_OPERATION; 888 } 889 assert(mStatus != STATUS_ACTIVE); 890 891 sp<Camera3OutputStream> newStream; 892 if (format == HAL_PIXEL_FORMAT_BLOB) { 893 ssize_t blobBufferSize; 894 if (dataSpace != HAL_DATASPACE_DEPTH) { 895 blobBufferSize = getJpegBufferSize(width, height); 896 if (blobBufferSize <= 0) { 897 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize); 898 return BAD_VALUE; 899 } 900 } else { 901 blobBufferSize = getPointCloudBufferSize(); 902 if (blobBufferSize <= 0) { 903 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize); 904 return BAD_VALUE; 905 } 906 } 907 newStream = new Camera3OutputStream(mNextStreamId, consumer, 908 width, height, blobBufferSize, format, dataSpace, rotation); 909 } else { 910 newStream = new Camera3OutputStream(mNextStreamId, consumer, 911 width, height, format, dataSpace, rotation); 912 } 913 newStream->setStatusTracker(mStatusTracker); 914 915 res = mOutputStreams.add(mNextStreamId, newStream); 916 if (res < 0) { 917 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res); 918 return res; 919 } 920 921 *id = mNextStreamId++; 922 mNeedConfig = true; 923 924 // Continue captures if active at start 925 if (wasActive) { 926 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 927 res = configureStreamsLocked(); 928 if (res != OK) { 929 CLOGE("Can't reconfigure device for new stream %d: %s (%d)", 930 mNextStreamId, strerror(-res), res); 931 return res; 932 } 933 internalResumeLocked(); 934 } 935 ALOGV("Camera %d: Created new stream", mId); 936 return OK; 937} 938 939status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) { 940 ATRACE_CALL(); 941 (void)outputId; (void)id; 942 943 CLOGE("Unimplemented"); 944 return INVALID_OPERATION; 945} 946 947 948status_t Camera3Device::getStreamInfo(int id, 949 uint32_t *width, uint32_t *height, 950 uint32_t *format, android_dataspace *dataSpace) { 951 ATRACE_CALL(); 952 Mutex::Autolock il(mInterfaceLock); 953 Mutex::Autolock l(mLock); 954 955 switch (mStatus) { 956 case STATUS_ERROR: 957 CLOGE("Device has encountered a serious error"); 958 return INVALID_OPERATION; 959 case STATUS_UNINITIALIZED: 960 CLOGE("Device not initialized!"); 961 return INVALID_OPERATION; 962 case STATUS_UNCONFIGURED: 963 case STATUS_CONFIGURED: 964 case STATUS_ACTIVE: 965 // OK 966 break; 967 default: 968 SET_ERR_L("Unexpected status: %d", mStatus); 969 return INVALID_OPERATION; 970 } 971 972 ssize_t idx = mOutputStreams.indexOfKey(id); 973 if (idx == NAME_NOT_FOUND) { 974 CLOGE("Stream %d is unknown", id); 975 return idx; 976 } 977 978 if (width) *width = mOutputStreams[idx]->getWidth(); 979 if (height) *height = mOutputStreams[idx]->getHeight(); 980 if (format) *format = mOutputStreams[idx]->getFormat(); 981 if (dataSpace) *dataSpace = mOutputStreams[idx]->getDataSpace(); 982 return OK; 983} 984 985status_t Camera3Device::setStreamTransform(int id, 986 int transform) { 987 ATRACE_CALL(); 988 Mutex::Autolock il(mInterfaceLock); 989 Mutex::Autolock l(mLock); 990 991 switch (mStatus) { 992 case STATUS_ERROR: 993 CLOGE("Device has encountered a serious error"); 994 return INVALID_OPERATION; 995 case STATUS_UNINITIALIZED: 996 CLOGE("Device not initialized"); 997 return INVALID_OPERATION; 998 case STATUS_UNCONFIGURED: 999 case STATUS_CONFIGURED: 1000 case STATUS_ACTIVE: 1001 // OK 1002 break; 1003 default: 1004 SET_ERR_L("Unexpected status: %d", mStatus); 1005 return INVALID_OPERATION; 1006 } 1007 1008 ssize_t idx = mOutputStreams.indexOfKey(id); 1009 if (idx == NAME_NOT_FOUND) { 1010 CLOGE("Stream %d does not exist", 1011 id); 1012 return BAD_VALUE; 1013 } 1014 1015 return mOutputStreams.editValueAt(idx)->setTransform(transform); 1016} 1017 1018status_t Camera3Device::deleteStream(int id) { 1019 ATRACE_CALL(); 1020 Mutex::Autolock il(mInterfaceLock); 1021 Mutex::Autolock l(mLock); 1022 status_t res; 1023 1024 ALOGV("%s: Camera %d: Deleting stream %d", __FUNCTION__, mId, id); 1025 1026 // CameraDevice semantics require device to already be idle before 1027 // deleteStream is called, unlike for createStream. 1028 if (mStatus == STATUS_ACTIVE) { 1029 ALOGV("%s: Camera %d: Device not idle", __FUNCTION__, mId); 1030 return -EBUSY; 1031 } 1032 1033 sp<Camera3StreamInterface> deletedStream; 1034 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id); 1035 if (mInputStream != NULL && id == mInputStream->getId()) { 1036 deletedStream = mInputStream; 1037 mInputStream.clear(); 1038 } else { 1039 if (outputStreamIdx == NAME_NOT_FOUND) { 1040 CLOGE("Stream %d does not exist", id); 1041 return BAD_VALUE; 1042 } 1043 } 1044 1045 // Delete output stream or the output part of a bi-directional stream. 1046 if (outputStreamIdx != NAME_NOT_FOUND) { 1047 deletedStream = mOutputStreams.editValueAt(outputStreamIdx); 1048 mOutputStreams.removeItem(id); 1049 } 1050 1051 // Free up the stream endpoint so that it can be used by some other stream 1052 res = deletedStream->disconnect(); 1053 if (res != OK) { 1054 SET_ERR_L("Can't disconnect deleted stream %d", id); 1055 // fall through since we want to still list the stream as deleted. 1056 } 1057 mDeletedStreams.add(deletedStream); 1058 mNeedConfig = true; 1059 1060 return res; 1061} 1062 1063status_t Camera3Device::deleteReprocessStream(int id) { 1064 ATRACE_CALL(); 1065 (void)id; 1066 1067 CLOGE("Unimplemented"); 1068 return INVALID_OPERATION; 1069} 1070 1071status_t Camera3Device::configureStreams(bool isConstrainedHighSpeed) { 1072 ATRACE_CALL(); 1073 ALOGV("%s: E", __FUNCTION__); 1074 1075 Mutex::Autolock il(mInterfaceLock); 1076 Mutex::Autolock l(mLock); 1077 1078 if (mIsConstrainedHighSpeedConfiguration != isConstrainedHighSpeed) { 1079 mNeedConfig = true; 1080 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed; 1081 } 1082 1083 return configureStreamsLocked(); 1084} 1085 1086status_t Camera3Device::getInputBufferProducer( 1087 sp<IGraphicBufferProducer> *producer) { 1088 Mutex::Autolock il(mInterfaceLock); 1089 Mutex::Autolock l(mLock); 1090 1091 if (producer == NULL) { 1092 return BAD_VALUE; 1093 } else if (mInputStream == NULL) { 1094 return INVALID_OPERATION; 1095 } 1096 1097 return mInputStream->getInputBufferProducer(producer); 1098} 1099 1100status_t Camera3Device::createDefaultRequest(int templateId, 1101 CameraMetadata *request) { 1102 ATRACE_CALL(); 1103 ALOGV("%s: for template %d", __FUNCTION__, templateId); 1104 Mutex::Autolock il(mInterfaceLock); 1105 Mutex::Autolock l(mLock); 1106 1107 switch (mStatus) { 1108 case STATUS_ERROR: 1109 CLOGE("Device has encountered a serious error"); 1110 return INVALID_OPERATION; 1111 case STATUS_UNINITIALIZED: 1112 CLOGE("Device is not initialized!"); 1113 return INVALID_OPERATION; 1114 case STATUS_UNCONFIGURED: 1115 case STATUS_CONFIGURED: 1116 case STATUS_ACTIVE: 1117 // OK 1118 break; 1119 default: 1120 SET_ERR_L("Unexpected status: %d", mStatus); 1121 return INVALID_OPERATION; 1122 } 1123 1124 if (!mRequestTemplateCache[templateId].isEmpty()) { 1125 *request = mRequestTemplateCache[templateId]; 1126 return OK; 1127 } 1128 1129 const camera_metadata_t *rawRequest; 1130 ATRACE_BEGIN("camera3->construct_default_request_settings"); 1131 rawRequest = mHal3Device->ops->construct_default_request_settings( 1132 mHal3Device, templateId); 1133 ATRACE_END(); 1134 if (rawRequest == NULL) { 1135 ALOGI("%s: template %d is not supported on this camera device", 1136 __FUNCTION__, templateId); 1137 return BAD_VALUE; 1138 } 1139 *request = rawRequest; 1140 mRequestTemplateCache[templateId] = rawRequest; 1141 1142 return OK; 1143} 1144 1145status_t Camera3Device::waitUntilDrained() { 1146 ATRACE_CALL(); 1147 Mutex::Autolock il(mInterfaceLock); 1148 Mutex::Autolock l(mLock); 1149 1150 return waitUntilDrainedLocked(); 1151} 1152 1153status_t Camera3Device::waitUntilDrainedLocked() { 1154 switch (mStatus) { 1155 case STATUS_UNINITIALIZED: 1156 case STATUS_UNCONFIGURED: 1157 ALOGV("%s: Already idle", __FUNCTION__); 1158 return OK; 1159 case STATUS_CONFIGURED: 1160 // To avoid race conditions, check with tracker to be sure 1161 case STATUS_ERROR: 1162 case STATUS_ACTIVE: 1163 // Need to verify shut down 1164 break; 1165 default: 1166 SET_ERR_L("Unexpected status: %d",mStatus); 1167 return INVALID_OPERATION; 1168 } 1169 1170 ALOGV("%s: Camera %d: Waiting until idle", __FUNCTION__, mId); 1171 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout); 1172 if (res != OK) { 1173 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res), 1174 res); 1175 } 1176 return res; 1177} 1178 1179 1180void Camera3Device::internalUpdateStatusLocked(Status status) { 1181 mStatus = status; 1182 mRecentStatusUpdates.add(mStatus); 1183 mStatusChanged.broadcast(); 1184} 1185 1186// Pause to reconfigure 1187status_t Camera3Device::internalPauseAndWaitLocked() { 1188 mRequestThread->setPaused(true); 1189 mPauseStateNotify = true; 1190 1191 ALOGV("%s: Camera %d: Internal wait until idle", __FUNCTION__, mId); 1192 status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout); 1193 if (res != OK) { 1194 SET_ERR_L("Can't idle device in %f seconds!", 1195 kShutdownTimeout/1e9); 1196 } 1197 1198 return res; 1199} 1200 1201// Resume after internalPauseAndWaitLocked 1202status_t Camera3Device::internalResumeLocked() { 1203 status_t res; 1204 1205 mRequestThread->setPaused(false); 1206 1207 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout); 1208 if (res != OK) { 1209 SET_ERR_L("Can't transition to active in %f seconds!", 1210 kActiveTimeout/1e9); 1211 } 1212 mPauseStateNotify = false; 1213 return OK; 1214} 1215 1216status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) { 1217 status_t res = OK; 1218 1219 size_t startIndex = 0; 1220 if (mStatusWaiters == 0) { 1221 // Clear the list of recent statuses if there are no existing threads waiting on updates to 1222 // this status list 1223 mRecentStatusUpdates.clear(); 1224 } else { 1225 // If other threads are waiting on updates to this status list, set the position of the 1226 // first element that this list will check rather than clearing the list. 1227 startIndex = mRecentStatusUpdates.size(); 1228 } 1229 1230 mStatusWaiters++; 1231 1232 bool stateSeen = false; 1233 do { 1234 if (active == (mStatus == STATUS_ACTIVE)) { 1235 // Desired state is current 1236 break; 1237 } 1238 1239 res = mStatusChanged.waitRelative(mLock, timeout); 1240 if (res != OK) break; 1241 1242 // This is impossible, but if not, could result in subtle deadlocks and invalid state 1243 // transitions. 1244 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(), 1245 "%s: Skipping status updates in Camera3Device, may result in deadlock.", 1246 __FUNCTION__); 1247 1248 // Encountered desired state since we began waiting 1249 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) { 1250 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) { 1251 stateSeen = true; 1252 break; 1253 } 1254 } 1255 } while (!stateSeen); 1256 1257 mStatusWaiters--; 1258 1259 return res; 1260} 1261 1262 1263status_t Camera3Device::setNotifyCallback(NotificationListener *listener) { 1264 ATRACE_CALL(); 1265 Mutex::Autolock l(mOutputLock); 1266 1267 if (listener != NULL && mListener != NULL) { 1268 ALOGW("%s: Replacing old callback listener", __FUNCTION__); 1269 } 1270 mListener = listener; 1271 mRequestThread->setNotificationListener(listener); 1272 mPreparerThread->setNotificationListener(listener); 1273 1274 return OK; 1275} 1276 1277bool Camera3Device::willNotify3A() { 1278 return false; 1279} 1280 1281status_t Camera3Device::waitForNextFrame(nsecs_t timeout) { 1282 status_t res; 1283 Mutex::Autolock l(mOutputLock); 1284 1285 while (mResultQueue.empty()) { 1286 res = mResultSignal.waitRelative(mOutputLock, timeout); 1287 if (res == TIMED_OUT) { 1288 return res; 1289 } else if (res != OK) { 1290 ALOGW("%s: Camera %d: No frame in %" PRId64 " ns: %s (%d)", 1291 __FUNCTION__, mId, timeout, strerror(-res), res); 1292 return res; 1293 } 1294 } 1295 return OK; 1296} 1297 1298status_t Camera3Device::getNextResult(CaptureResult *frame) { 1299 ATRACE_CALL(); 1300 Mutex::Autolock l(mOutputLock); 1301 1302 if (mResultQueue.empty()) { 1303 return NOT_ENOUGH_DATA; 1304 } 1305 1306 if (frame == NULL) { 1307 ALOGE("%s: argument cannot be NULL", __FUNCTION__); 1308 return BAD_VALUE; 1309 } 1310 1311 CaptureResult &result = *(mResultQueue.begin()); 1312 frame->mResultExtras = result.mResultExtras; 1313 frame->mMetadata.acquire(result.mMetadata); 1314 mResultQueue.erase(mResultQueue.begin()); 1315 1316 return OK; 1317} 1318 1319status_t Camera3Device::triggerAutofocus(uint32_t id) { 1320 ATRACE_CALL(); 1321 Mutex::Autolock il(mInterfaceLock); 1322 1323 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id); 1324 // Mix-in this trigger into the next request and only the next request. 1325 RequestTrigger trigger[] = { 1326 { 1327 ANDROID_CONTROL_AF_TRIGGER, 1328 ANDROID_CONTROL_AF_TRIGGER_START 1329 }, 1330 { 1331 ANDROID_CONTROL_AF_TRIGGER_ID, 1332 static_cast<int32_t>(id) 1333 } 1334 }; 1335 1336 return mRequestThread->queueTrigger(trigger, 1337 sizeof(trigger)/sizeof(trigger[0])); 1338} 1339 1340status_t Camera3Device::triggerCancelAutofocus(uint32_t id) { 1341 ATRACE_CALL(); 1342 Mutex::Autolock il(mInterfaceLock); 1343 1344 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id); 1345 // Mix-in this trigger into the next request and only the next request. 1346 RequestTrigger trigger[] = { 1347 { 1348 ANDROID_CONTROL_AF_TRIGGER, 1349 ANDROID_CONTROL_AF_TRIGGER_CANCEL 1350 }, 1351 { 1352 ANDROID_CONTROL_AF_TRIGGER_ID, 1353 static_cast<int32_t>(id) 1354 } 1355 }; 1356 1357 return mRequestThread->queueTrigger(trigger, 1358 sizeof(trigger)/sizeof(trigger[0])); 1359} 1360 1361status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) { 1362 ATRACE_CALL(); 1363 Mutex::Autolock il(mInterfaceLock); 1364 1365 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id); 1366 // Mix-in this trigger into the next request and only the next request. 1367 RequestTrigger trigger[] = { 1368 { 1369 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, 1370 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START 1371 }, 1372 { 1373 ANDROID_CONTROL_AE_PRECAPTURE_ID, 1374 static_cast<int32_t>(id) 1375 } 1376 }; 1377 1378 return mRequestThread->queueTrigger(trigger, 1379 sizeof(trigger)/sizeof(trigger[0])); 1380} 1381 1382status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId, 1383 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) { 1384 ATRACE_CALL(); 1385 (void)reprocessStreamId; (void)buffer; (void)listener; 1386 1387 CLOGE("Unimplemented"); 1388 return INVALID_OPERATION; 1389} 1390 1391status_t Camera3Device::flush(int64_t *frameNumber) { 1392 ATRACE_CALL(); 1393 ALOGV("%s: Camera %d: Flushing all requests", __FUNCTION__, mId); 1394 Mutex::Autolock il(mInterfaceLock); 1395 1396 NotificationListener* listener; 1397 { 1398 Mutex::Autolock l(mOutputLock); 1399 listener = mListener; 1400 } 1401 1402 { 1403 Mutex::Autolock l(mLock); 1404 mRequestThread->clear(listener, /*out*/frameNumber); 1405 } 1406 1407 status_t res; 1408 if (mHal3Device->common.version >= CAMERA_DEVICE_API_VERSION_3_1) { 1409 res = mHal3Device->ops->flush(mHal3Device); 1410 } else { 1411 Mutex::Autolock l(mLock); 1412 res = waitUntilDrainedLocked(); 1413 } 1414 1415 return res; 1416} 1417 1418status_t Camera3Device::prepare(int streamId) { 1419 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId); 1420} 1421 1422status_t Camera3Device::prepare(int maxCount, int streamId) { 1423 ATRACE_CALL(); 1424 ALOGV("%s: Camera %d: Preparing stream %d", __FUNCTION__, mId, streamId); 1425 Mutex::Autolock il(mInterfaceLock); 1426 Mutex::Autolock l(mLock); 1427 1428 sp<Camera3StreamInterface> stream; 1429 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId); 1430 if (outputStreamIdx == NAME_NOT_FOUND) { 1431 CLOGE("Stream %d does not exist", streamId); 1432 return BAD_VALUE; 1433 } 1434 1435 stream = mOutputStreams.editValueAt(outputStreamIdx); 1436 1437 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) { 1438 CLOGE("Stream %d has already been a request target", streamId); 1439 return BAD_VALUE; 1440 } 1441 1442 if (mRequestThread->isStreamPending(stream)) { 1443 CLOGE("Stream %d is already a target in a pending request", streamId); 1444 return BAD_VALUE; 1445 } 1446 1447 return mPreparerThread->prepare(maxCount, stream); 1448} 1449 1450status_t Camera3Device::tearDown(int streamId) { 1451 ATRACE_CALL(); 1452 ALOGV("%s: Camera %d: Tearing down stream %d", __FUNCTION__, mId, streamId); 1453 Mutex::Autolock il(mInterfaceLock); 1454 Mutex::Autolock l(mLock); 1455 1456 // Teardown can only be accomplished on devices that don't require register_stream_buffers, 1457 // since we cannot call register_stream_buffers except right after configure_streams. 1458 if (mHal3Device->common.version < CAMERA_DEVICE_API_VERSION_3_2) { 1459 ALOGE("%s: Unable to tear down streams on device HAL v%x", 1460 __FUNCTION__, mHal3Device->common.version); 1461 return NO_INIT; 1462 } 1463 1464 sp<Camera3StreamInterface> stream; 1465 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId); 1466 if (outputStreamIdx == NAME_NOT_FOUND) { 1467 CLOGE("Stream %d does not exist", streamId); 1468 return BAD_VALUE; 1469 } 1470 1471 stream = mOutputStreams.editValueAt(outputStreamIdx); 1472 1473 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) { 1474 CLOGE("Stream %d is a target of a in-progress request", streamId); 1475 return BAD_VALUE; 1476 } 1477 1478 return stream->tearDown(); 1479} 1480 1481uint32_t Camera3Device::getDeviceVersion() { 1482 ATRACE_CALL(); 1483 Mutex::Autolock il(mInterfaceLock); 1484 return mDeviceVersion; 1485} 1486 1487/** 1488 * Methods called by subclasses 1489 */ 1490 1491void Camera3Device::notifyStatus(bool idle) { 1492 { 1493 // Need mLock to safely update state and synchronize to current 1494 // state of methods in flight. 1495 Mutex::Autolock l(mLock); 1496 // We can get various system-idle notices from the status tracker 1497 // while starting up. Only care about them if we've actually sent 1498 // in some requests recently. 1499 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) { 1500 return; 1501 } 1502 ALOGV("%s: Camera %d: Now %s", __FUNCTION__, mId, 1503 idle ? "idle" : "active"); 1504 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE); 1505 1506 // Skip notifying listener if we're doing some user-transparent 1507 // state changes 1508 if (mPauseStateNotify) return; 1509 } 1510 NotificationListener *listener; 1511 { 1512 Mutex::Autolock l(mOutputLock); 1513 listener = mListener; 1514 } 1515 if (idle && listener != NULL) { 1516 listener->notifyIdle(); 1517 } 1518} 1519 1520/** 1521 * Camera3Device private methods 1522 */ 1523 1524sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest( 1525 const CameraMetadata &request) { 1526 ATRACE_CALL(); 1527 status_t res; 1528 1529 sp<CaptureRequest> newRequest = new CaptureRequest; 1530 newRequest->mSettings = request; 1531 1532 camera_metadata_entry_t inputStreams = 1533 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS); 1534 if (inputStreams.count > 0) { 1535 if (mInputStream == NULL || 1536 mInputStream->getId() != inputStreams.data.i32[0]) { 1537 CLOGE("Request references unknown input stream %d", 1538 inputStreams.data.u8[0]); 1539 return NULL; 1540 } 1541 // Lazy completion of stream configuration (allocation/registration) 1542 // on first use 1543 if (mInputStream->isConfiguring()) { 1544 res = mInputStream->finishConfiguration(mHal3Device); 1545 if (res != OK) { 1546 SET_ERR_L("Unable to finish configuring input stream %d:" 1547 " %s (%d)", 1548 mInputStream->getId(), strerror(-res), res); 1549 return NULL; 1550 } 1551 } 1552 // Check if stream is being prepared 1553 if (mInputStream->isPreparing()) { 1554 CLOGE("Request references an input stream that's being prepared!"); 1555 return NULL; 1556 } 1557 1558 newRequest->mInputStream = mInputStream; 1559 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS); 1560 } 1561 1562 camera_metadata_entry_t streams = 1563 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS); 1564 if (streams.count == 0) { 1565 CLOGE("Zero output streams specified!"); 1566 return NULL; 1567 } 1568 1569 for (size_t i = 0; i < streams.count; i++) { 1570 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]); 1571 if (idx == NAME_NOT_FOUND) { 1572 CLOGE("Request references unknown stream %d", 1573 streams.data.u8[i]); 1574 return NULL; 1575 } 1576 sp<Camera3OutputStreamInterface> stream = 1577 mOutputStreams.editValueAt(idx); 1578 1579 // Lazy completion of stream configuration (allocation/registration) 1580 // on first use 1581 if (stream->isConfiguring()) { 1582 res = stream->finishConfiguration(mHal3Device); 1583 if (res != OK) { 1584 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)", 1585 stream->getId(), strerror(-res), res); 1586 return NULL; 1587 } 1588 } 1589 // Check if stream is being prepared 1590 if (stream->isPreparing()) { 1591 CLOGE("Request references an output stream that's being prepared!"); 1592 return NULL; 1593 } 1594 1595 newRequest->mOutputStreams.push(stream); 1596 } 1597 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS); 1598 1599 return newRequest; 1600} 1601 1602bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) { 1603 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) { 1604 Size size = mSupportedOpaqueInputSizes[i]; 1605 if (size.width == width && size.height == height) { 1606 return true; 1607 } 1608 } 1609 1610 return false; 1611} 1612 1613status_t Camera3Device::configureStreamsLocked() { 1614 ATRACE_CALL(); 1615 status_t res; 1616 1617 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) { 1618 CLOGE("Not idle"); 1619 return INVALID_OPERATION; 1620 } 1621 1622 if (!mNeedConfig) { 1623 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__); 1624 return OK; 1625 } 1626 1627 // Workaround for device HALv3.2 or older spec bug - zero streams requires 1628 // adding a dummy stream instead. 1629 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround. 1630 if (mOutputStreams.size() == 0) { 1631 addDummyStreamLocked(); 1632 } else { 1633 tryRemoveDummyStreamLocked(); 1634 } 1635 1636 // Start configuring the streams 1637 ALOGV("%s: Camera %d: Starting stream configuration", __FUNCTION__, mId); 1638 1639 camera3_stream_configuration config; 1640 config.operation_mode = mIsConstrainedHighSpeedConfiguration ? 1641 CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE : 1642 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE; 1643 config.num_streams = (mInputStream != NULL) + mOutputStreams.size(); 1644 1645 Vector<camera3_stream_t*> streams; 1646 streams.setCapacity(config.num_streams); 1647 1648 if (mInputStream != NULL) { 1649 camera3_stream_t *inputStream; 1650 inputStream = mInputStream->startConfiguration(); 1651 if (inputStream == NULL) { 1652 SET_ERR_L("Can't start input stream configuration"); 1653 return INVALID_OPERATION; 1654 } 1655 streams.add(inputStream); 1656 } 1657 1658 for (size_t i = 0; i < mOutputStreams.size(); i++) { 1659 1660 // Don't configure bidi streams twice, nor add them twice to the list 1661 if (mOutputStreams[i].get() == 1662 static_cast<Camera3StreamInterface*>(mInputStream.get())) { 1663 1664 config.num_streams--; 1665 continue; 1666 } 1667 1668 camera3_stream_t *outputStream; 1669 outputStream = mOutputStreams.editValueAt(i)->startConfiguration(); 1670 if (outputStream == NULL) { 1671 SET_ERR_L("Can't start output stream configuration"); 1672 return INVALID_OPERATION; 1673 } 1674 streams.add(outputStream); 1675 } 1676 1677 config.streams = streams.editArray(); 1678 1679 // Do the HAL configuration; will potentially touch stream 1680 // max_buffers, usage, priv fields. 1681 ATRACE_BEGIN("camera3->configure_streams"); 1682 res = mHal3Device->ops->configure_streams(mHal3Device, &config); 1683 ATRACE_END(); 1684 1685 if (res == BAD_VALUE) { 1686 // HAL rejected this set of streams as unsupported, clean up config 1687 // attempt and return to unconfigured state 1688 if (mInputStream != NULL && mInputStream->isConfiguring()) { 1689 res = mInputStream->cancelConfiguration(); 1690 if (res != OK) { 1691 SET_ERR_L("Can't cancel configuring input stream %d: %s (%d)", 1692 mInputStream->getId(), strerror(-res), res); 1693 return res; 1694 } 1695 } 1696 1697 for (size_t i = 0; i < mOutputStreams.size(); i++) { 1698 sp<Camera3OutputStreamInterface> outputStream = 1699 mOutputStreams.editValueAt(i); 1700 if (outputStream->isConfiguring()) { 1701 res = outputStream->cancelConfiguration(); 1702 if (res != OK) { 1703 SET_ERR_L( 1704 "Can't cancel configuring output stream %d: %s (%d)", 1705 outputStream->getId(), strerror(-res), res); 1706 return res; 1707 } 1708 } 1709 } 1710 1711 // Return state to that at start of call, so that future configures 1712 // properly clean things up 1713 internalUpdateStatusLocked(STATUS_UNCONFIGURED); 1714 mNeedConfig = true; 1715 1716 ALOGV("%s: Camera %d: Stream configuration failed", __FUNCTION__, mId); 1717 return BAD_VALUE; 1718 } else if (res != OK) { 1719 // Some other kind of error from configure_streams - this is not 1720 // expected 1721 SET_ERR_L("Unable to configure streams with HAL: %s (%d)", 1722 strerror(-res), res); 1723 return res; 1724 } 1725 1726 // Finish all stream configuration immediately. 1727 // TODO: Try to relax this later back to lazy completion, which should be 1728 // faster 1729 1730 if (mInputStream != NULL && mInputStream->isConfiguring()) { 1731 res = mInputStream->finishConfiguration(mHal3Device); 1732 if (res != OK) { 1733 SET_ERR_L("Can't finish configuring input stream %d: %s (%d)", 1734 mInputStream->getId(), strerror(-res), res); 1735 return res; 1736 } 1737 } 1738 1739 for (size_t i = 0; i < mOutputStreams.size(); i++) { 1740 sp<Camera3OutputStreamInterface> outputStream = 1741 mOutputStreams.editValueAt(i); 1742 if (outputStream->isConfiguring()) { 1743 res = outputStream->finishConfiguration(mHal3Device); 1744 if (res != OK) { 1745 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)", 1746 outputStream->getId(), strerror(-res), res); 1747 return res; 1748 } 1749 } 1750 } 1751 1752 // Request thread needs to know to avoid using repeat-last-settings protocol 1753 // across configure_streams() calls 1754 mRequestThread->configurationComplete(); 1755 1756 // Update device state 1757 1758 mNeedConfig = false; 1759 1760 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ? 1761 STATUS_CONFIGURED : STATUS_UNCONFIGURED); 1762 1763 ALOGV("%s: Camera %d: Stream configuration complete", __FUNCTION__, mId); 1764 1765 // tear down the deleted streams after configure streams. 1766 mDeletedStreams.clear(); 1767 1768 return OK; 1769} 1770 1771status_t Camera3Device::addDummyStreamLocked() { 1772 ATRACE_CALL(); 1773 status_t res; 1774 1775 if (mDummyStreamId != NO_STREAM) { 1776 // Should never be adding a second dummy stream when one is already 1777 // active 1778 SET_ERR_L("%s: Camera %d: A dummy stream already exists!", 1779 __FUNCTION__, mId); 1780 return INVALID_OPERATION; 1781 } 1782 1783 ALOGV("%s: Camera %d: Adding a dummy stream", __FUNCTION__, mId); 1784 1785 sp<Camera3OutputStreamInterface> dummyStream = 1786 new Camera3DummyStream(mNextStreamId); 1787 1788 res = mOutputStreams.add(mNextStreamId, dummyStream); 1789 if (res < 0) { 1790 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res); 1791 return res; 1792 } 1793 1794 mDummyStreamId = mNextStreamId; 1795 mNextStreamId++; 1796 1797 return OK; 1798} 1799 1800status_t Camera3Device::tryRemoveDummyStreamLocked() { 1801 ATRACE_CALL(); 1802 status_t res; 1803 1804 if (mDummyStreamId == NO_STREAM) return OK; 1805 if (mOutputStreams.size() == 1) return OK; 1806 1807 ALOGV("%s: Camera %d: Removing the dummy stream", __FUNCTION__, mId); 1808 1809 // Ok, have a dummy stream and there's at least one other output stream, 1810 // so remove the dummy 1811 1812 sp<Camera3StreamInterface> deletedStream; 1813 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId); 1814 if (outputStreamIdx == NAME_NOT_FOUND) { 1815 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId); 1816 return INVALID_OPERATION; 1817 } 1818 1819 deletedStream = mOutputStreams.editValueAt(outputStreamIdx); 1820 mOutputStreams.removeItemsAt(outputStreamIdx); 1821 1822 // Free up the stream endpoint so that it can be used by some other stream 1823 res = deletedStream->disconnect(); 1824 if (res != OK) { 1825 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId); 1826 // fall through since we want to still list the stream as deleted. 1827 } 1828 mDeletedStreams.add(deletedStream); 1829 mDummyStreamId = NO_STREAM; 1830 1831 return res; 1832} 1833 1834void Camera3Device::setErrorState(const char *fmt, ...) { 1835 Mutex::Autolock l(mLock); 1836 va_list args; 1837 va_start(args, fmt); 1838 1839 setErrorStateLockedV(fmt, args); 1840 1841 va_end(args); 1842} 1843 1844void Camera3Device::setErrorStateV(const char *fmt, va_list args) { 1845 Mutex::Autolock l(mLock); 1846 setErrorStateLockedV(fmt, args); 1847} 1848 1849void Camera3Device::setErrorStateLocked(const char *fmt, ...) { 1850 va_list args; 1851 va_start(args, fmt); 1852 1853 setErrorStateLockedV(fmt, args); 1854 1855 va_end(args); 1856} 1857 1858void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) { 1859 // Print out all error messages to log 1860 String8 errorCause = String8::formatV(fmt, args); 1861 ALOGE("Camera %d: %s", mId, errorCause.string()); 1862 1863 // But only do error state transition steps for the first error 1864 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return; 1865 1866 mErrorCause = errorCause; 1867 1868 mRequestThread->setPaused(true); 1869 internalUpdateStatusLocked(STATUS_ERROR); 1870 1871 // Notify upstream about a device error 1872 if (mListener != NULL) { 1873 mListener->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE, 1874 CaptureResultExtras()); 1875 } 1876 1877 // Save stack trace. View by dumping it later. 1878 CameraTraces::saveTrace(); 1879 // TODO: consider adding errorCause and client pid/procname 1880} 1881 1882/** 1883 * In-flight request management 1884 */ 1885 1886status_t Camera3Device::registerInFlight(uint32_t frameNumber, 1887 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput, 1888 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) { 1889 ATRACE_CALL(); 1890 Mutex::Autolock l(mInFlightLock); 1891 1892 ssize_t res; 1893 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput, 1894 aeTriggerCancelOverride)); 1895 if (res < 0) return res; 1896 1897 return OK; 1898} 1899 1900/** 1901 * Check if all 3A fields are ready, and send off a partial 3A-only result 1902 * to the output frame queue 1903 */ 1904bool Camera3Device::processPartial3AResult( 1905 uint32_t frameNumber, 1906 const CameraMetadata& partial, const CaptureResultExtras& resultExtras) { 1907 1908 // Check if all 3A states are present 1909 // The full list of fields is 1910 // android.control.afMode 1911 // android.control.awbMode 1912 // android.control.aeState 1913 // android.control.awbState 1914 // android.control.afState 1915 // android.control.afTriggerID 1916 // android.control.aePrecaptureID 1917 // TODO: Add android.control.aeMode 1918 1919 bool gotAllStates = true; 1920 1921 uint8_t afMode; 1922 uint8_t awbMode; 1923 uint8_t aeState; 1924 uint8_t afState; 1925 uint8_t awbState; 1926 1927 gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_MODE, 1928 &afMode, frameNumber); 1929 1930 gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_MODE, 1931 &awbMode, frameNumber); 1932 1933 gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AE_STATE, 1934 &aeState, frameNumber); 1935 1936 gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_STATE, 1937 &afState, frameNumber); 1938 1939 gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_STATE, 1940 &awbState, frameNumber); 1941 1942 if (!gotAllStates) return false; 1943 1944 ALOGVV("%s: Camera %d: Frame %d, Request ID %d: AF mode %d, AWB mode %d, " 1945 "AF state %d, AE state %d, AWB state %d, " 1946 "AF trigger %d, AE precapture trigger %d", 1947 __FUNCTION__, mId, frameNumber, resultExtras.requestId, 1948 afMode, awbMode, 1949 afState, aeState, awbState, 1950 resultExtras.afTriggerId, resultExtras.precaptureTriggerId); 1951 1952 // Got all states, so construct a minimal result to send 1953 // In addition to the above fields, this means adding in 1954 // android.request.frameCount 1955 // android.request.requestId 1956 // android.quirks.partialResult (for HAL version below HAL3.2) 1957 1958 const size_t kMinimal3AResultEntries = 10; 1959 1960 Mutex::Autolock l(mOutputLock); 1961 1962 CaptureResult captureResult; 1963 captureResult.mResultExtras = resultExtras; 1964 captureResult.mMetadata = CameraMetadata(kMinimal3AResultEntries, /*dataCapacity*/ 0); 1965 // TODO: change this to sp<CaptureResult>. This will need other changes, including, 1966 // but not limited to CameraDeviceBase::getNextResult 1967 CaptureResult& min3AResult = 1968 *mResultQueue.insert(mResultQueue.end(), captureResult); 1969 1970 if (!insert3AResult(min3AResult.mMetadata, ANDROID_REQUEST_FRAME_COUNT, 1971 // TODO: This is problematic casting. Need to fix CameraMetadata. 1972 reinterpret_cast<int32_t*>(&frameNumber), frameNumber)) { 1973 return false; 1974 } 1975 1976 int32_t requestId = resultExtras.requestId; 1977 if (!insert3AResult(min3AResult.mMetadata, ANDROID_REQUEST_ID, 1978 &requestId, frameNumber)) { 1979 return false; 1980 } 1981 1982 if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) { 1983 static const uint8_t partialResult = ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL; 1984 if (!insert3AResult(min3AResult.mMetadata, ANDROID_QUIRKS_PARTIAL_RESULT, 1985 &partialResult, frameNumber)) { 1986 return false; 1987 } 1988 } 1989 1990 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_MODE, 1991 &afMode, frameNumber)) { 1992 return false; 1993 } 1994 1995 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AWB_MODE, 1996 &awbMode, frameNumber)) { 1997 return false; 1998 } 1999 2000 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AE_STATE, 2001 &aeState, frameNumber)) { 2002 return false; 2003 } 2004 2005 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_STATE, 2006 &afState, frameNumber)) { 2007 return false; 2008 } 2009 2010 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AWB_STATE, 2011 &awbState, frameNumber)) { 2012 return false; 2013 } 2014 2015 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_TRIGGER_ID, 2016 &resultExtras.afTriggerId, frameNumber)) { 2017 return false; 2018 } 2019 2020 if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AE_PRECAPTURE_ID, 2021 &resultExtras.precaptureTriggerId, frameNumber)) { 2022 return false; 2023 } 2024 2025 // We only send the aggregated partial when all 3A related metadata are available 2026 // For both API1 and API2. 2027 // TODO: we probably should pass through all partials to API2 unconditionally. 2028 mResultSignal.signal(); 2029 2030 return true; 2031} 2032 2033template<typename T> 2034bool Camera3Device::get3AResult(const CameraMetadata& result, int32_t tag, 2035 T* value, uint32_t frameNumber) { 2036 (void) frameNumber; 2037 2038 camera_metadata_ro_entry_t entry; 2039 2040 entry = result.find(tag); 2041 if (entry.count == 0) { 2042 ALOGVV("%s: Camera %d: Frame %d: No %s provided by HAL!", __FUNCTION__, 2043 mId, frameNumber, get_camera_metadata_tag_name(tag)); 2044 return false; 2045 } 2046 2047 if (sizeof(T) == sizeof(uint8_t)) { 2048 *value = entry.data.u8[0]; 2049 } else if (sizeof(T) == sizeof(int32_t)) { 2050 *value = entry.data.i32[0]; 2051 } else { 2052 ALOGE("%s: Unexpected type", __FUNCTION__); 2053 return false; 2054 } 2055 return true; 2056} 2057 2058template<typename T> 2059bool Camera3Device::insert3AResult(CameraMetadata& result, int32_t tag, 2060 const T* value, uint32_t frameNumber) { 2061 if (result.update(tag, value, 1) != NO_ERROR) { 2062 mResultQueue.erase(--mResultQueue.end(), mResultQueue.end()); 2063 SET_ERR("Frame %d: Failed to set %s in partial metadata", 2064 frameNumber, get_camera_metadata_tag_name(tag)); 2065 return false; 2066 } 2067 return true; 2068} 2069 2070void Camera3Device::returnOutputBuffers( 2071 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers, 2072 nsecs_t timestamp) { 2073 for (size_t i = 0; i < numBuffers; i++) 2074 { 2075 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream); 2076 status_t res = stream->returnBuffer(outputBuffers[i], timestamp); 2077 // Note: stream may be deallocated at this point, if this buffer was 2078 // the last reference to it. 2079 if (res != OK) { 2080 ALOGE("Can't return buffer to its stream: %s (%d)", 2081 strerror(-res), res); 2082 } 2083 } 2084} 2085 2086 2087void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) { 2088 2089 const InFlightRequest &request = mInFlightMap.valueAt(idx); 2090 const uint32_t frameNumber = mInFlightMap.keyAt(idx); 2091 2092 nsecs_t sensorTimestamp = request.sensorTimestamp; 2093 nsecs_t shutterTimestamp = request.shutterTimestamp; 2094 2095 // Check if it's okay to remove the request from InFlightMap: 2096 // In the case of a successful request: 2097 // all input and output buffers, all result metadata, shutter callback 2098 // arrived. 2099 // In the case of a unsuccessful request: 2100 // all input and output buffers arrived. 2101 if (request.numBuffersLeft == 0 && 2102 (request.requestStatus != OK || 2103 (request.haveResultMetadata && shutterTimestamp != 0))) { 2104 ATRACE_ASYNC_END("frame capture", frameNumber); 2105 2106 // Sanity check - if sensor timestamp matches shutter timestamp 2107 if (request.requestStatus == OK && 2108 sensorTimestamp != shutterTimestamp) { 2109 SET_ERR("sensor timestamp (%" PRId64 2110 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")", 2111 sensorTimestamp, frameNumber, shutterTimestamp); 2112 } 2113 2114 // for an unsuccessful request, it may have pending output buffers to 2115 // return. 2116 assert(request.requestStatus != OK || 2117 request.pendingOutputBuffers.size() == 0); 2118 returnOutputBuffers(request.pendingOutputBuffers.array(), 2119 request.pendingOutputBuffers.size(), 0); 2120 2121 mInFlightMap.removeItemsAt(idx, 1); 2122 2123 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber); 2124 } 2125 2126 // Sanity check - if we have too many in-flight frames, something has 2127 // likely gone wrong 2128 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) { 2129 CLOGE("In-flight list too large: %zu", mInFlightMap.size()); 2130 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > 2131 kInFlightWarnLimitHighSpeed) { 2132 CLOGE("In-flight list too large for high speed configuration: %zu", 2133 mInFlightMap.size()); 2134 } 2135} 2136 2137 2138void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata, 2139 CaptureResultExtras &resultExtras, 2140 CameraMetadata &collectedPartialResult, 2141 uint32_t frameNumber, 2142 bool reprocess, 2143 const AeTriggerCancelOverride_t &aeTriggerCancelOverride) { 2144 if (pendingMetadata.isEmpty()) 2145 return; 2146 2147 Mutex::Autolock l(mOutputLock); 2148 2149 // TODO: need to track errors for tighter bounds on expected frame number 2150 if (reprocess) { 2151 if (frameNumber < mNextReprocessResultFrameNumber) { 2152 SET_ERR("Out-of-order reprocess capture result metadata submitted! " 2153 "(got frame number %d, expecting %d)", 2154 frameNumber, mNextReprocessResultFrameNumber); 2155 return; 2156 } 2157 mNextReprocessResultFrameNumber = frameNumber + 1; 2158 } else { 2159 if (frameNumber < mNextResultFrameNumber) { 2160 SET_ERR("Out-of-order capture result metadata submitted! " 2161 "(got frame number %d, expecting %d)", 2162 frameNumber, mNextResultFrameNumber); 2163 return; 2164 } 2165 mNextResultFrameNumber = frameNumber + 1; 2166 } 2167 2168 CaptureResult captureResult; 2169 captureResult.mResultExtras = resultExtras; 2170 captureResult.mMetadata = pendingMetadata; 2171 2172 if (captureResult.mMetadata.update(ANDROID_REQUEST_FRAME_COUNT, 2173 (int32_t*)&frameNumber, 1) != OK) { 2174 SET_ERR("Failed to set frame# in metadata (%d)", 2175 frameNumber); 2176 return; 2177 } else { 2178 ALOGVV("%s: Camera %d: Set frame# in metadata (%d)", 2179 __FUNCTION__, mId, frameNumber); 2180 } 2181 2182 // Append any previous partials to form a complete result 2183 if (mUsePartialResult && !collectedPartialResult.isEmpty()) { 2184 captureResult.mMetadata.append(collectedPartialResult); 2185 } 2186 2187 captureResult.mMetadata.sort(); 2188 2189 // Check that there's a timestamp in the result metadata 2190 camera_metadata_entry entry = 2191 captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP); 2192 if (entry.count == 0) { 2193 SET_ERR("No timestamp provided by HAL for frame %d!", 2194 frameNumber); 2195 return; 2196 } 2197 2198 overrideResultForPrecaptureCancel(&captureResult.mMetadata, aeTriggerCancelOverride); 2199 2200 // Valid result, insert into queue 2201 List<CaptureResult>::iterator queuedResult = 2202 mResultQueue.insert(mResultQueue.end(), CaptureResult(captureResult)); 2203 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64 2204 ", burstId = %" PRId32, __FUNCTION__, 2205 queuedResult->mResultExtras.requestId, 2206 queuedResult->mResultExtras.frameNumber, 2207 queuedResult->mResultExtras.burstId); 2208 2209 mResultSignal.signal(); 2210} 2211 2212/** 2213 * Camera HAL device callback methods 2214 */ 2215 2216void Camera3Device::processCaptureResult(const camera3_capture_result *result) { 2217 ATRACE_CALL(); 2218 2219 status_t res; 2220 2221 uint32_t frameNumber = result->frame_number; 2222 if (result->result == NULL && result->num_output_buffers == 0 && 2223 result->input_buffer == NULL) { 2224 SET_ERR("No result data provided by HAL for frame %d", 2225 frameNumber); 2226 return; 2227 } 2228 2229 // For HAL3.2 or above, If HAL doesn't support partial, it must always set 2230 // partial_result to 1 when metadata is included in this result. 2231 if (!mUsePartialResult && 2232 mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 && 2233 result->result != NULL && 2234 result->partial_result != 1) { 2235 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1" 2236 " if partial result is not supported", 2237 frameNumber, result->partial_result); 2238 return; 2239 } 2240 2241 bool isPartialResult = false; 2242 CameraMetadata collectedPartialResult; 2243 CaptureResultExtras resultExtras; 2244 bool hasInputBufferInRequest = false; 2245 2246 // Get shutter timestamp and resultExtras from list of in-flight requests, 2247 // where it was added by the shutter notification for this frame. If the 2248 // shutter timestamp isn't received yet, append the output buffers to the 2249 // in-flight request and they will be returned when the shutter timestamp 2250 // arrives. Update the in-flight status and remove the in-flight entry if 2251 // all result data and shutter timestamp have been received. 2252 nsecs_t shutterTimestamp = 0; 2253 2254 { 2255 Mutex::Autolock l(mInFlightLock); 2256 ssize_t idx = mInFlightMap.indexOfKey(frameNumber); 2257 if (idx == NAME_NOT_FOUND) { 2258 SET_ERR("Unknown frame number for capture result: %d", 2259 frameNumber); 2260 return; 2261 } 2262 InFlightRequest &request = mInFlightMap.editValueAt(idx); 2263 ALOGVV("%s: got InFlightRequest requestId = %" PRId32 2264 ", frameNumber = %" PRId64 ", burstId = %" PRId32 2265 ", partialResultCount = %d", 2266 __FUNCTION__, request.resultExtras.requestId, 2267 request.resultExtras.frameNumber, request.resultExtras.burstId, 2268 result->partial_result); 2269 // Always update the partial count to the latest one if it's not 0 2270 // (buffers only). When framework aggregates adjacent partial results 2271 // into one, the latest partial count will be used. 2272 if (result->partial_result != 0) 2273 request.resultExtras.partialResultCount = result->partial_result; 2274 2275 // Check if this result carries only partial metadata 2276 if (mUsePartialResult && result->result != NULL) { 2277 if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) { 2278 if (result->partial_result > mNumPartialResults || result->partial_result < 1) { 2279 SET_ERR("Result is malformed for frame %d: partial_result %u must be in" 2280 " the range of [1, %d] when metadata is included in the result", 2281 frameNumber, result->partial_result, mNumPartialResults); 2282 return; 2283 } 2284 isPartialResult = (result->partial_result < mNumPartialResults); 2285 if (isPartialResult) { 2286 request.partialResult.collectedResult.append(result->result); 2287 } 2288 } else { 2289 camera_metadata_ro_entry_t partialResultEntry; 2290 res = find_camera_metadata_ro_entry(result->result, 2291 ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry); 2292 if (res != NAME_NOT_FOUND && 2293 partialResultEntry.count > 0 && 2294 partialResultEntry.data.u8[0] == 2295 ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) { 2296 // A partial result. Flag this as such, and collect this 2297 // set of metadata into the in-flight entry. 2298 isPartialResult = true; 2299 request.partialResult.collectedResult.append( 2300 result->result); 2301 request.partialResult.collectedResult.erase( 2302 ANDROID_QUIRKS_PARTIAL_RESULT); 2303 } 2304 } 2305 2306 if (isPartialResult) { 2307 // Fire off a 3A-only result if possible 2308 if (!request.partialResult.haveSent3A) { 2309 request.partialResult.haveSent3A = 2310 processPartial3AResult(frameNumber, 2311 request.partialResult.collectedResult, 2312 request.resultExtras); 2313 } 2314 } 2315 } 2316 2317 shutterTimestamp = request.shutterTimestamp; 2318 hasInputBufferInRequest = request.hasInputBuffer; 2319 2320 // Did we get the (final) result metadata for this capture? 2321 if (result->result != NULL && !isPartialResult) { 2322 if (request.haveResultMetadata) { 2323 SET_ERR("Called multiple times with metadata for frame %d", 2324 frameNumber); 2325 return; 2326 } 2327 if (mUsePartialResult && 2328 !request.partialResult.collectedResult.isEmpty()) { 2329 collectedPartialResult.acquire( 2330 request.partialResult.collectedResult); 2331 } 2332 request.haveResultMetadata = true; 2333 } 2334 2335 uint32_t numBuffersReturned = result->num_output_buffers; 2336 if (result->input_buffer != NULL) { 2337 if (hasInputBufferInRequest) { 2338 numBuffersReturned += 1; 2339 } else { 2340 ALOGW("%s: Input buffer should be NULL if there is no input" 2341 " buffer sent in the request", 2342 __FUNCTION__); 2343 } 2344 } 2345 request.numBuffersLeft -= numBuffersReturned; 2346 if (request.numBuffersLeft < 0) { 2347 SET_ERR("Too many buffers returned for frame %d", 2348 frameNumber); 2349 return; 2350 } 2351 2352 camera_metadata_ro_entry_t entry; 2353 res = find_camera_metadata_ro_entry(result->result, 2354 ANDROID_SENSOR_TIMESTAMP, &entry); 2355 if (res == OK && entry.count == 1) { 2356 request.sensorTimestamp = entry.data.i64[0]; 2357 } 2358 2359 // If shutter event isn't received yet, append the output buffers to 2360 // the in-flight request. Otherwise, return the output buffers to 2361 // streams. 2362 if (shutterTimestamp == 0) { 2363 request.pendingOutputBuffers.appendArray(result->output_buffers, 2364 result->num_output_buffers); 2365 } else { 2366 returnOutputBuffers(result->output_buffers, 2367 result->num_output_buffers, shutterTimestamp); 2368 } 2369 2370 if (result->result != NULL && !isPartialResult) { 2371 if (shutterTimestamp == 0) { 2372 request.pendingMetadata = result->result; 2373 request.partialResult.collectedResult = collectedPartialResult; 2374 } else { 2375 CameraMetadata metadata; 2376 metadata = result->result; 2377 sendCaptureResult(metadata, request.resultExtras, 2378 collectedPartialResult, frameNumber, hasInputBufferInRequest, 2379 request.aeTriggerCancelOverride); 2380 } 2381 } 2382 2383 removeInFlightRequestIfReadyLocked(idx); 2384 } // scope for mInFlightLock 2385 2386 if (result->input_buffer != NULL) { 2387 if (hasInputBufferInRequest) { 2388 Camera3Stream *stream = 2389 Camera3Stream::cast(result->input_buffer->stream); 2390 res = stream->returnInputBuffer(*(result->input_buffer)); 2391 // Note: stream may be deallocated at this point, if this buffer was the 2392 // last reference to it. 2393 if (res != OK) { 2394 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to" 2395 " its stream:%s (%d)", __FUNCTION__, 2396 frameNumber, strerror(-res), res); 2397 } 2398 } else { 2399 ALOGW("%s: Input buffer should be NULL if there is no input" 2400 " buffer sent in the request, skipping input buffer return.", 2401 __FUNCTION__); 2402 } 2403 } 2404} 2405 2406void Camera3Device::notify(const camera3_notify_msg *msg) { 2407 ATRACE_CALL(); 2408 NotificationListener *listener; 2409 { 2410 Mutex::Autolock l(mOutputLock); 2411 listener = mListener; 2412 } 2413 2414 if (msg == NULL) { 2415 SET_ERR("HAL sent NULL notify message!"); 2416 return; 2417 } 2418 2419 switch (msg->type) { 2420 case CAMERA3_MSG_ERROR: { 2421 notifyError(msg->message.error, listener); 2422 break; 2423 } 2424 case CAMERA3_MSG_SHUTTER: { 2425 notifyShutter(msg->message.shutter, listener); 2426 break; 2427 } 2428 default: 2429 SET_ERR("Unknown notify message from HAL: %d", 2430 msg->type); 2431 } 2432} 2433 2434void Camera3Device::notifyError(const camera3_error_msg_t &msg, 2435 NotificationListener *listener) { 2436 2437 // Map camera HAL error codes to ICameraDeviceCallback error codes 2438 // Index into this with the HAL error code 2439 static const ICameraDeviceCallbacks::CameraErrorCode 2440 halErrorMap[CAMERA3_MSG_NUM_ERRORS] = { 2441 // 0 = Unused error code 2442 ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR, 2443 // 1 = CAMERA3_MSG_ERROR_DEVICE 2444 ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE, 2445 // 2 = CAMERA3_MSG_ERROR_REQUEST 2446 ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST, 2447 // 3 = CAMERA3_MSG_ERROR_RESULT 2448 ICameraDeviceCallbacks::ERROR_CAMERA_RESULT, 2449 // 4 = CAMERA3_MSG_ERROR_BUFFER 2450 ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER 2451 }; 2452 2453 ICameraDeviceCallbacks::CameraErrorCode errorCode = 2454 ((msg.error_code >= 0) && 2455 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ? 2456 halErrorMap[msg.error_code] : 2457 ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR; 2458 2459 int streamId = 0; 2460 if (msg.error_stream != NULL) { 2461 Camera3Stream *stream = 2462 Camera3Stream::cast(msg.error_stream); 2463 streamId = stream->getId(); 2464 } 2465 ALOGV("Camera %d: %s: HAL error, frame %d, stream %d: %d", 2466 mId, __FUNCTION__, msg.frame_number, 2467 streamId, msg.error_code); 2468 2469 CaptureResultExtras resultExtras; 2470 switch (errorCode) { 2471 case ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE: 2472 // SET_ERR calls notifyError 2473 SET_ERR("Camera HAL reported serious device error"); 2474 break; 2475 case ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST: 2476 case ICameraDeviceCallbacks::ERROR_CAMERA_RESULT: 2477 case ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER: 2478 { 2479 Mutex::Autolock l(mInFlightLock); 2480 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number); 2481 if (idx >= 0) { 2482 InFlightRequest &r = mInFlightMap.editValueAt(idx); 2483 r.requestStatus = msg.error_code; 2484 resultExtras = r.resultExtras; 2485 } else { 2486 resultExtras.frameNumber = msg.frame_number; 2487 ALOGE("Camera %d: %s: cannot find in-flight request on " 2488 "frame %" PRId64 " error", mId, __FUNCTION__, 2489 resultExtras.frameNumber); 2490 } 2491 } 2492 if (listener != NULL) { 2493 listener->notifyError(errorCode, resultExtras); 2494 } else { 2495 ALOGE("Camera %d: %s: no listener available", mId, __FUNCTION__); 2496 } 2497 break; 2498 default: 2499 // SET_ERR calls notifyError 2500 SET_ERR("Unknown error message from HAL: %d", msg.error_code); 2501 break; 2502 } 2503} 2504 2505void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg, 2506 NotificationListener *listener) { 2507 ssize_t idx; 2508 // Verify ordering of shutter notifications 2509 { 2510 Mutex::Autolock l(mOutputLock); 2511 // TODO: need to track errors for tighter bounds on expected frame number. 2512 if (msg.frame_number < mNextShutterFrameNumber) { 2513 SET_ERR("Shutter notification out-of-order. Expected " 2514 "notification for frame %d, got frame %d", 2515 mNextShutterFrameNumber, msg.frame_number); 2516 return; 2517 } 2518 mNextShutterFrameNumber = msg.frame_number + 1; 2519 } 2520 2521 // Set timestamp for the request in the in-flight tracking 2522 // and get the request ID to send upstream 2523 { 2524 Mutex::Autolock l(mInFlightLock); 2525 idx = mInFlightMap.indexOfKey(msg.frame_number); 2526 if (idx >= 0) { 2527 InFlightRequest &r = mInFlightMap.editValueAt(idx); 2528 2529 ALOGVV("Camera %d: %s: Shutter fired for frame %d (id %d) at %" PRId64, 2530 mId, __FUNCTION__, 2531 msg.frame_number, r.resultExtras.requestId, msg.timestamp); 2532 // Call listener, if any 2533 if (listener != NULL) { 2534 listener->notifyShutter(r.resultExtras, msg.timestamp); 2535 } 2536 2537 r.shutterTimestamp = msg.timestamp; 2538 2539 // send pending result and buffers 2540 sendCaptureResult(r.pendingMetadata, r.resultExtras, 2541 r.partialResult.collectedResult, msg.frame_number, 2542 r.hasInputBuffer, r.aeTriggerCancelOverride); 2543 returnOutputBuffers(r.pendingOutputBuffers.array(), 2544 r.pendingOutputBuffers.size(), r.shutterTimestamp); 2545 r.pendingOutputBuffers.clear(); 2546 2547 removeInFlightRequestIfReadyLocked(idx); 2548 } 2549 } 2550 if (idx < 0) { 2551 SET_ERR("Shutter notification for non-existent frame number %d", 2552 msg.frame_number); 2553 } 2554} 2555 2556 2557CameraMetadata Camera3Device::getLatestRequestLocked() { 2558 ALOGV("%s", __FUNCTION__); 2559 2560 CameraMetadata retVal; 2561 2562 if (mRequestThread != NULL) { 2563 retVal = mRequestThread->getLatestRequest(); 2564 } 2565 2566 return retVal; 2567} 2568 2569 2570/** 2571 * RequestThread inner class methods 2572 */ 2573 2574Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent, 2575 sp<StatusTracker> statusTracker, 2576 camera3_device_t *hal3Device, 2577 bool aeLockAvailable) : 2578 Thread(/*canCallJava*/false), 2579 mParent(parent), 2580 mStatusTracker(statusTracker), 2581 mHal3Device(hal3Device), 2582 mId(getId(parent)), 2583 mReconfigured(false), 2584 mDoPause(false), 2585 mPaused(true), 2586 mFrameNumber(0), 2587 mLatestRequestId(NAME_NOT_FOUND), 2588 mCurrentAfTriggerId(0), 2589 mCurrentPreCaptureTriggerId(0), 2590 mRepeatingLastFrameNumber(NO_IN_FLIGHT_REPEATING_FRAMES), 2591 mAeLockAvailable(aeLockAvailable) { 2592 mStatusId = statusTracker->addComponent(); 2593} 2594 2595void Camera3Device::RequestThread::setNotificationListener( 2596 NotificationListener *listener) { 2597 Mutex::Autolock l(mRequestLock); 2598 mListener = listener; 2599} 2600 2601void Camera3Device::RequestThread::configurationComplete() { 2602 Mutex::Autolock l(mRequestLock); 2603 mReconfigured = true; 2604} 2605 2606status_t Camera3Device::RequestThread::queueRequestList( 2607 List<sp<CaptureRequest> > &requests, 2608 /*out*/ 2609 int64_t *lastFrameNumber) { 2610 Mutex::Autolock l(mRequestLock); 2611 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end(); 2612 ++it) { 2613 mRequestQueue.push_back(*it); 2614 } 2615 2616 if (lastFrameNumber != NULL) { 2617 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1; 2618 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".", 2619 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber, 2620 *lastFrameNumber); 2621 } 2622 2623 unpauseForNewRequests(); 2624 2625 return OK; 2626} 2627 2628 2629status_t Camera3Device::RequestThread::queueTrigger( 2630 RequestTrigger trigger[], 2631 size_t count) { 2632 2633 Mutex::Autolock l(mTriggerMutex); 2634 status_t ret; 2635 2636 for (size_t i = 0; i < count; ++i) { 2637 ret = queueTriggerLocked(trigger[i]); 2638 2639 if (ret != OK) { 2640 return ret; 2641 } 2642 } 2643 2644 return OK; 2645} 2646 2647int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) { 2648 sp<Camera3Device> d = device.promote(); 2649 if (d != NULL) return d->mId; 2650 return 0; 2651} 2652 2653status_t Camera3Device::RequestThread::queueTriggerLocked( 2654 RequestTrigger trigger) { 2655 2656 uint32_t tag = trigger.metadataTag; 2657 ssize_t index = mTriggerMap.indexOfKey(tag); 2658 2659 switch (trigger.getTagType()) { 2660 case TYPE_BYTE: 2661 // fall-through 2662 case TYPE_INT32: 2663 break; 2664 default: 2665 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__, 2666 trigger.getTagType()); 2667 return INVALID_OPERATION; 2668 } 2669 2670 /** 2671 * Collect only the latest trigger, since we only have 1 field 2672 * in the request settings per trigger tag, and can't send more than 1 2673 * trigger per request. 2674 */ 2675 if (index != NAME_NOT_FOUND) { 2676 mTriggerMap.editValueAt(index) = trigger; 2677 } else { 2678 mTriggerMap.add(tag, trigger); 2679 } 2680 2681 return OK; 2682} 2683 2684status_t Camera3Device::RequestThread::setRepeatingRequests( 2685 const RequestList &requests, 2686 /*out*/ 2687 int64_t *lastFrameNumber) { 2688 Mutex::Autolock l(mRequestLock); 2689 if (lastFrameNumber != NULL) { 2690 *lastFrameNumber = mRepeatingLastFrameNumber; 2691 } 2692 mRepeatingRequests.clear(); 2693 mRepeatingRequests.insert(mRepeatingRequests.begin(), 2694 requests.begin(), requests.end()); 2695 2696 unpauseForNewRequests(); 2697 2698 mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES; 2699 return OK; 2700} 2701 2702bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest> requestIn) { 2703 if (mRepeatingRequests.empty()) { 2704 return false; 2705 } 2706 int32_t requestId = requestIn->mResultExtras.requestId; 2707 const RequestList &repeatRequests = mRepeatingRequests; 2708 // All repeating requests are guaranteed to have same id so only check first quest 2709 const sp<CaptureRequest> firstRequest = *repeatRequests.begin(); 2710 return (firstRequest->mResultExtras.requestId == requestId); 2711} 2712 2713status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) { 2714 Mutex::Autolock l(mRequestLock); 2715 mRepeatingRequests.clear(); 2716 if (lastFrameNumber != NULL) { 2717 *lastFrameNumber = mRepeatingLastFrameNumber; 2718 } 2719 mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES; 2720 return OK; 2721} 2722 2723status_t Camera3Device::RequestThread::clear( 2724 NotificationListener *listener, 2725 /*out*/int64_t *lastFrameNumber) { 2726 Mutex::Autolock l(mRequestLock); 2727 ALOGV("RequestThread::%s:", __FUNCTION__); 2728 2729 mRepeatingRequests.clear(); 2730 2731 // Send errors for all requests pending in the request queue, including 2732 // pending repeating requests 2733 if (listener != NULL) { 2734 for (RequestList::iterator it = mRequestQueue.begin(); 2735 it != mRequestQueue.end(); ++it) { 2736 // Abort the input buffers for reprocess requests. 2737 if ((*it)->mInputStream != NULL) { 2738 camera3_stream_buffer_t inputBuffer; 2739 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer); 2740 if (res != OK) { 2741 ALOGW("%s: %d: couldn't get input buffer while clearing the request " 2742 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res); 2743 } else { 2744 res = (*it)->mInputStream->returnInputBuffer(inputBuffer); 2745 if (res != OK) { 2746 ALOGE("%s: %d: couldn't return input buffer while clearing the request " 2747 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res); 2748 } 2749 } 2750 } 2751 // Set the frame number this request would have had, if it 2752 // had been submitted; this frame number will not be reused. 2753 // The requestId and burstId fields were set when the request was 2754 // submitted originally (in convertMetadataListToRequestListLocked) 2755 (*it)->mResultExtras.frameNumber = mFrameNumber++; 2756 listener->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST, 2757 (*it)->mResultExtras); 2758 } 2759 } 2760 mRequestQueue.clear(); 2761 mTriggerMap.clear(); 2762 if (lastFrameNumber != NULL) { 2763 *lastFrameNumber = mRepeatingLastFrameNumber; 2764 } 2765 mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES; 2766 return OK; 2767} 2768 2769void Camera3Device::RequestThread::setPaused(bool paused) { 2770 Mutex::Autolock l(mPauseLock); 2771 mDoPause = paused; 2772 mDoPauseSignal.signal(); 2773} 2774 2775status_t Camera3Device::RequestThread::waitUntilRequestProcessed( 2776 int32_t requestId, nsecs_t timeout) { 2777 Mutex::Autolock l(mLatestRequestMutex); 2778 status_t res; 2779 while (mLatestRequestId != requestId) { 2780 nsecs_t startTime = systemTime(); 2781 2782 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout); 2783 if (res != OK) return res; 2784 2785 timeout -= (systemTime() - startTime); 2786 } 2787 2788 return OK; 2789} 2790 2791void Camera3Device::RequestThread::requestExit() { 2792 // Call parent to set up shutdown 2793 Thread::requestExit(); 2794 // The exit from any possible waits 2795 mDoPauseSignal.signal(); 2796 mRequestSignal.signal(); 2797} 2798 2799 2800/** 2801 * For devices <= CAMERA_DEVICE_API_VERSION_3_2, AE_PRECAPTURE_TRIGGER_CANCEL is not supported so 2802 * we need to override AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE and AE_LOCK_OFF 2803 * to AE_LOCK_ON to start cancelling AE precapture. If AE lock is not available, it still overrides 2804 * AE_PRECAPTURE_TRIGGER_CANCEL to AE_PRECAPTURE_TRIGGER_IDLE but doesn't add AE_LOCK_ON to the 2805 * request. 2806 */ 2807void Camera3Device::RequestThread::handleAePrecaptureCancelRequest(sp<CaptureRequest> request) { 2808 request->mAeTriggerCancelOverride.applyAeLock = false; 2809 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = false; 2810 2811 if (mHal3Device->common.version > CAMERA_DEVICE_API_VERSION_3_2) { 2812 return; 2813 } 2814 2815 camera_metadata_entry_t aePrecaptureTrigger = 2816 request->mSettings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER); 2817 if (aePrecaptureTrigger.count > 0 && 2818 aePrecaptureTrigger.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) { 2819 // Always override CANCEL to IDLE 2820 uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE; 2821 request->mSettings.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1); 2822 request->mAeTriggerCancelOverride.applyAePrecaptureTrigger = true; 2823 request->mAeTriggerCancelOverride.aePrecaptureTrigger = 2824 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL; 2825 2826 if (mAeLockAvailable == true) { 2827 camera_metadata_entry_t aeLock = request->mSettings.find(ANDROID_CONTROL_AE_LOCK); 2828 if (aeLock.count == 0 || aeLock.data.u8[0] == ANDROID_CONTROL_AE_LOCK_OFF) { 2829 uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_ON; 2830 request->mSettings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1); 2831 request->mAeTriggerCancelOverride.applyAeLock = true; 2832 request->mAeTriggerCancelOverride.aeLock = ANDROID_CONTROL_AE_LOCK_OFF; 2833 } 2834 } 2835 } 2836} 2837 2838/** 2839 * Override result metadata for cancelling AE precapture trigger applied in 2840 * handleAePrecaptureCancelRequest(). 2841 */ 2842void Camera3Device::overrideResultForPrecaptureCancel( 2843 CameraMetadata *result, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) { 2844 if (aeTriggerCancelOverride.applyAeLock) { 2845 // Only devices <= v3.2 should have this override 2846 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2); 2847 result->update(ANDROID_CONTROL_AE_LOCK, &aeTriggerCancelOverride.aeLock, 1); 2848 } 2849 2850 if (aeTriggerCancelOverride.applyAePrecaptureTrigger) { 2851 // Only devices <= v3.2 should have this override 2852 assert(mDeviceVersion <= CAMERA_DEVICE_API_VERSION_3_2); 2853 result->update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, 2854 &aeTriggerCancelOverride.aePrecaptureTrigger, 1); 2855 } 2856} 2857 2858bool Camera3Device::RequestThread::threadLoop() { 2859 2860 status_t res; 2861 2862 // Handle paused state. 2863 if (waitIfPaused()) { 2864 return true; 2865 } 2866 2867 // Get work to do 2868 2869 sp<CaptureRequest> nextRequest = waitForNextRequest(); 2870 if (nextRequest == NULL) { 2871 return true; 2872 } 2873 2874 // Create request to HAL 2875 camera3_capture_request_t request = camera3_capture_request_t(); 2876 request.frame_number = nextRequest->mResultExtras.frameNumber; 2877 Vector<camera3_stream_buffer_t> outputBuffers; 2878 2879 // Get the request ID, if any 2880 int requestId; 2881 camera_metadata_entry_t requestIdEntry = 2882 nextRequest->mSettings.find(ANDROID_REQUEST_ID); 2883 if (requestIdEntry.count > 0) { 2884 requestId = requestIdEntry.data.i32[0]; 2885 } else { 2886 ALOGW("%s: Did not have android.request.id set in the request", 2887 __FUNCTION__); 2888 requestId = NAME_NOT_FOUND; 2889 } 2890 2891 // Insert any queued triggers (before metadata is locked) 2892 int32_t triggerCount; 2893 res = insertTriggers(nextRequest); 2894 if (res < 0) { 2895 SET_ERR("RequestThread: Unable to insert triggers " 2896 "(capture request %d, HAL device: %s (%d)", 2897 request.frame_number, strerror(-res), res); 2898 cleanUpFailedRequest(request, nextRequest, outputBuffers); 2899 return false; 2900 } 2901 triggerCount = res; 2902 2903 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0); 2904 2905 // If the request is the same as last, or we had triggers last time 2906 if (mPrevRequest != nextRequest || triggersMixedIn) { 2907 /** 2908 * HAL workaround: 2909 * Insert a dummy trigger ID if a trigger is set but no trigger ID is 2910 */ 2911 res = addDummyTriggerIds(nextRequest); 2912 if (res != OK) { 2913 SET_ERR("RequestThread: Unable to insert dummy trigger IDs " 2914 "(capture request %d, HAL device: %s (%d)", 2915 request.frame_number, strerror(-res), res); 2916 cleanUpFailedRequest(request, nextRequest, outputBuffers); 2917 return false; 2918 } 2919 2920 /** 2921 * The request should be presorted so accesses in HAL 2922 * are O(logn). Sidenote, sorting a sorted metadata is nop. 2923 */ 2924 nextRequest->mSettings.sort(); 2925 request.settings = nextRequest->mSettings.getAndLock(); 2926 mPrevRequest = nextRequest; 2927 ALOGVV("%s: Request settings are NEW", __FUNCTION__); 2928 2929 IF_ALOGV() { 2930 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t(); 2931 find_camera_metadata_ro_entry( 2932 request.settings, 2933 ANDROID_CONTROL_AF_TRIGGER, 2934 &e 2935 ); 2936 if (e.count > 0) { 2937 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x", 2938 __FUNCTION__, 2939 request.frame_number, 2940 e.data.u8[0]); 2941 } 2942 } 2943 } else { 2944 // leave request.settings NULL to indicate 'reuse latest given' 2945 ALOGVV("%s: Request settings are REUSED", 2946 __FUNCTION__); 2947 } 2948 2949 uint32_t totalNumBuffers = 0; 2950 2951 // Fill in buffers 2952 if (nextRequest->mInputStream != NULL) { 2953 request.input_buffer = &nextRequest->mInputBuffer; 2954 totalNumBuffers += 1; 2955 } else { 2956 request.input_buffer = NULL; 2957 } 2958 2959 outputBuffers.insertAt(camera3_stream_buffer_t(), 0, 2960 nextRequest->mOutputStreams.size()); 2961 request.output_buffers = outputBuffers.array(); 2962 for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) { 2963 res = nextRequest->mOutputStreams.editItemAt(i)-> 2964 getBuffer(&outputBuffers.editItemAt(i)); 2965 if (res != OK) { 2966 // Can't get output buffer from gralloc queue - this could be due to 2967 // abandoned queue or other consumer misbehavior, so not a fatal 2968 // error 2969 ALOGE("RequestThread: Can't get output buffer, skipping request:" 2970 " %s (%d)", strerror(-res), res); 2971 { 2972 Mutex::Autolock l(mRequestLock); 2973 if (mListener != NULL) { 2974 mListener->notifyError( 2975 ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST, 2976 nextRequest->mResultExtras); 2977 } 2978 } 2979 cleanUpFailedRequest(request, nextRequest, outputBuffers); 2980 return true; 2981 } 2982 request.num_output_buffers++; 2983 } 2984 totalNumBuffers += request.num_output_buffers; 2985 2986 // Log request in the in-flight queue 2987 sp<Camera3Device> parent = mParent.promote(); 2988 if (parent == NULL) { 2989 // Should not happen, and nowhere to send errors to, so just log it 2990 CLOGE("RequestThread: Parent is gone"); 2991 cleanUpFailedRequest(request, nextRequest, outputBuffers); 2992 return false; 2993 } 2994 2995 res = parent->registerInFlight(request.frame_number, 2996 totalNumBuffers, nextRequest->mResultExtras, 2997 /*hasInput*/request.input_buffer != NULL, 2998 nextRequest->mAeTriggerCancelOverride); 2999 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64 3000 ", burstId = %" PRId32 ".", 3001 __FUNCTION__, 3002 nextRequest->mResultExtras.requestId, nextRequest->mResultExtras.frameNumber, 3003 nextRequest->mResultExtras.burstId); 3004 if (res != OK) { 3005 SET_ERR("RequestThread: Unable to register new in-flight request:" 3006 " %s (%d)", strerror(-res), res); 3007 cleanUpFailedRequest(request, nextRequest, outputBuffers); 3008 return false; 3009 } 3010 3011 // Inform waitUntilRequestProcessed thread of a new request ID 3012 { 3013 Mutex::Autolock al(mLatestRequestMutex); 3014 3015 mLatestRequestId = requestId; 3016 mLatestRequestSignal.signal(); 3017 } 3018 3019 // Submit request and block until ready for next one 3020 ATRACE_ASYNC_BEGIN("frame capture", request.frame_number); 3021 ATRACE_BEGIN("camera3->process_capture_request"); 3022 res = mHal3Device->ops->process_capture_request(mHal3Device, &request); 3023 ATRACE_END(); 3024 3025 if (res != OK) { 3026 // Should only get a failure here for malformed requests or device-level 3027 // errors, so consider all errors fatal. Bad metadata failures should 3028 // come through notify. 3029 SET_ERR("RequestThread: Unable to submit capture request %d to HAL" 3030 " device: %s (%d)", request.frame_number, strerror(-res), res); 3031 cleanUpFailedRequest(request, nextRequest, outputBuffers); 3032 return false; 3033 } 3034 3035 // Update the latest request sent to HAL 3036 if (request.settings != NULL) { // Don't update them if they were unchanged 3037 Mutex::Autolock al(mLatestRequestMutex); 3038 3039 camera_metadata_t* cloned = clone_camera_metadata(request.settings); 3040 mLatestRequest.acquire(cloned); 3041 } 3042 3043 if (request.settings != NULL) { 3044 nextRequest->mSettings.unlock(request.settings); 3045 } 3046 3047 // Unset as current request 3048 { 3049 Mutex::Autolock l(mRequestLock); 3050 mNextRequest.clear(); 3051 } 3052 3053 // Remove any previously queued triggers (after unlock) 3054 res = removeTriggers(mPrevRequest); 3055 if (res != OK) { 3056 SET_ERR("RequestThread: Unable to remove triggers " 3057 "(capture request %d, HAL device: %s (%d)", 3058 request.frame_number, strerror(-res), res); 3059 return false; 3060 } 3061 mPrevTriggers = triggerCount; 3062 3063 return true; 3064} 3065 3066CameraMetadata Camera3Device::RequestThread::getLatestRequest() const { 3067 Mutex::Autolock al(mLatestRequestMutex); 3068 3069 ALOGV("RequestThread::%s", __FUNCTION__); 3070 3071 return mLatestRequest; 3072} 3073 3074bool Camera3Device::RequestThread::isStreamPending( 3075 sp<Camera3StreamInterface>& stream) { 3076 Mutex::Autolock l(mRequestLock); 3077 3078 if (mNextRequest != nullptr) { 3079 for (const auto& s : mNextRequest->mOutputStreams) { 3080 if (stream == s) return true; 3081 } 3082 if (stream == mNextRequest->mInputStream) return true; 3083 } 3084 3085 for (const auto& request : mRequestQueue) { 3086 for (const auto& s : request->mOutputStreams) { 3087 if (stream == s) return true; 3088 } 3089 if (stream == request->mInputStream) return true; 3090 } 3091 3092 for (const auto& request : mRepeatingRequests) { 3093 for (const auto& s : request->mOutputStreams) { 3094 if (stream == s) return true; 3095 } 3096 if (stream == request->mInputStream) return true; 3097 } 3098 3099 return false; 3100} 3101 3102void Camera3Device::RequestThread::cleanUpFailedRequest( 3103 camera3_capture_request_t &request, 3104 sp<CaptureRequest> &nextRequest, 3105 Vector<camera3_stream_buffer_t> &outputBuffers) { 3106 3107 if (request.settings != NULL) { 3108 nextRequest->mSettings.unlock(request.settings); 3109 } 3110 if (nextRequest->mInputStream != NULL) { 3111 nextRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR; 3112 nextRequest->mInputStream->returnInputBuffer(nextRequest->mInputBuffer); 3113 } 3114 for (size_t i = 0; i < request.num_output_buffers; i++) { 3115 outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR; 3116 nextRequest->mOutputStreams.editItemAt(i)->returnBuffer( 3117 outputBuffers[i], 0); 3118 } 3119 3120 Mutex::Autolock l(mRequestLock); 3121 mNextRequest.clear(); 3122} 3123 3124sp<Camera3Device::CaptureRequest> 3125 Camera3Device::RequestThread::waitForNextRequest() { 3126 status_t res; 3127 sp<CaptureRequest> nextRequest; 3128 3129 // Optimized a bit for the simple steady-state case (single repeating 3130 // request), to avoid putting that request in the queue temporarily. 3131 Mutex::Autolock l(mRequestLock); 3132 3133 while (mRequestQueue.empty()) { 3134 if (!mRepeatingRequests.empty()) { 3135 // Always atomically enqueue all requests in a repeating request 3136 // list. Guarantees a complete in-sequence set of captures to 3137 // application. 3138 const RequestList &requests = mRepeatingRequests; 3139 RequestList::const_iterator firstRequest = 3140 requests.begin(); 3141 nextRequest = *firstRequest; 3142 mRequestQueue.insert(mRequestQueue.end(), 3143 ++firstRequest, 3144 requests.end()); 3145 // No need to wait any longer 3146 3147 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1; 3148 3149 break; 3150 } 3151 3152 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout); 3153 3154 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) || 3155 exitPending()) { 3156 Mutex::Autolock pl(mPauseLock); 3157 if (mPaused == false) { 3158 ALOGV("%s: RequestThread: Going idle", __FUNCTION__); 3159 mPaused = true; 3160 // Let the tracker know 3161 sp<StatusTracker> statusTracker = mStatusTracker.promote(); 3162 if (statusTracker != 0) { 3163 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE); 3164 } 3165 } 3166 // Stop waiting for now and let thread management happen 3167 return NULL; 3168 } 3169 } 3170 3171 if (nextRequest == NULL) { 3172 // Don't have a repeating request already in hand, so queue 3173 // must have an entry now. 3174 RequestList::iterator firstRequest = 3175 mRequestQueue.begin(); 3176 nextRequest = *firstRequest; 3177 mRequestQueue.erase(firstRequest); 3178 } 3179 3180 // In case we've been unpaused by setPaused clearing mDoPause, need to 3181 // update internal pause state (capture/setRepeatingRequest unpause 3182 // directly). 3183 Mutex::Autolock pl(mPauseLock); 3184 if (mPaused) { 3185 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__); 3186 sp<StatusTracker> statusTracker = mStatusTracker.promote(); 3187 if (statusTracker != 0) { 3188 statusTracker->markComponentActive(mStatusId); 3189 } 3190 } 3191 mPaused = false; 3192 3193 // Check if we've reconfigured since last time, and reset the preview 3194 // request if so. Can't use 'NULL request == repeat' across configure calls. 3195 if (mReconfigured) { 3196 mPrevRequest.clear(); 3197 mReconfigured = false; 3198 } 3199 3200 if (nextRequest != NULL) { 3201 nextRequest->mResultExtras.frameNumber = mFrameNumber++; 3202 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId; 3203 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId; 3204 3205 // Since RequestThread::clear() removes buffers from the input stream, 3206 // get the right buffer here before unlocking mRequestLock 3207 if (nextRequest->mInputStream != NULL) { 3208 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer); 3209 if (res != OK) { 3210 // Can't get input buffer from gralloc queue - this could be due to 3211 // disconnected queue or other producer misbehavior, so not a fatal 3212 // error 3213 ALOGE("%s: Can't get input buffer, skipping request:" 3214 " %s (%d)", __FUNCTION__, strerror(-res), res); 3215 if (mListener != NULL) { 3216 mListener->notifyError( 3217 ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST, 3218 nextRequest->mResultExtras); 3219 } 3220 return NULL; 3221 } 3222 } 3223 } 3224 3225 handleAePrecaptureCancelRequest(nextRequest); 3226 3227 mNextRequest = nextRequest; 3228 3229 return nextRequest; 3230} 3231 3232bool Camera3Device::RequestThread::waitIfPaused() { 3233 status_t res; 3234 Mutex::Autolock l(mPauseLock); 3235 while (mDoPause) { 3236 if (mPaused == false) { 3237 mPaused = true; 3238 ALOGV("%s: RequestThread: Paused", __FUNCTION__); 3239 // Let the tracker know 3240 sp<StatusTracker> statusTracker = mStatusTracker.promote(); 3241 if (statusTracker != 0) { 3242 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE); 3243 } 3244 } 3245 3246 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout); 3247 if (res == TIMED_OUT || exitPending()) { 3248 return true; 3249 } 3250 } 3251 // We don't set mPaused to false here, because waitForNextRequest needs 3252 // to further manage the paused state in case of starvation. 3253 return false; 3254} 3255 3256void Camera3Device::RequestThread::unpauseForNewRequests() { 3257 // With work to do, mark thread as unpaused. 3258 // If paused by request (setPaused), don't resume, to avoid 3259 // extra signaling/waiting overhead to waitUntilPaused 3260 mRequestSignal.signal(); 3261 Mutex::Autolock p(mPauseLock); 3262 if (!mDoPause) { 3263 ALOGV("%s: RequestThread: Going active", __FUNCTION__); 3264 if (mPaused) { 3265 sp<StatusTracker> statusTracker = mStatusTracker.promote(); 3266 if (statusTracker != 0) { 3267 statusTracker->markComponentActive(mStatusId); 3268 } 3269 } 3270 mPaused = false; 3271 } 3272} 3273 3274void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) { 3275 sp<Camera3Device> parent = mParent.promote(); 3276 if (parent != NULL) { 3277 va_list args; 3278 va_start(args, fmt); 3279 3280 parent->setErrorStateV(fmt, args); 3281 3282 va_end(args); 3283 } 3284} 3285 3286status_t Camera3Device::RequestThread::insertTriggers( 3287 const sp<CaptureRequest> &request) { 3288 3289 Mutex::Autolock al(mTriggerMutex); 3290 3291 sp<Camera3Device> parent = mParent.promote(); 3292 if (parent == NULL) { 3293 CLOGE("RequestThread: Parent is gone"); 3294 return DEAD_OBJECT; 3295 } 3296 3297 CameraMetadata &metadata = request->mSettings; 3298 size_t count = mTriggerMap.size(); 3299 3300 for (size_t i = 0; i < count; ++i) { 3301 RequestTrigger trigger = mTriggerMap.valueAt(i); 3302 uint32_t tag = trigger.metadataTag; 3303 3304 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) { 3305 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID); 3306 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue); 3307 if (isAeTrigger) { 3308 request->mResultExtras.precaptureTriggerId = triggerId; 3309 mCurrentPreCaptureTriggerId = triggerId; 3310 } else { 3311 request->mResultExtras.afTriggerId = triggerId; 3312 mCurrentAfTriggerId = triggerId; 3313 } 3314 if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) { 3315 continue; // Trigger ID tag is deprecated since device HAL 3.2 3316 } 3317 } 3318 3319 camera_metadata_entry entry = metadata.find(tag); 3320 3321 if (entry.count > 0) { 3322 /** 3323 * Already has an entry for this trigger in the request. 3324 * Rewrite it with our requested trigger value. 3325 */ 3326 RequestTrigger oldTrigger = trigger; 3327 3328 oldTrigger.entryValue = entry.data.u8[0]; 3329 3330 mTriggerReplacedMap.add(tag, oldTrigger); 3331 } else { 3332 /** 3333 * More typical, no trigger entry, so we just add it 3334 */ 3335 mTriggerRemovedMap.add(tag, trigger); 3336 } 3337 3338 status_t res; 3339 3340 switch (trigger.getTagType()) { 3341 case TYPE_BYTE: { 3342 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue); 3343 res = metadata.update(tag, 3344 &entryValue, 3345 /*count*/1); 3346 break; 3347 } 3348 case TYPE_INT32: 3349 res = metadata.update(tag, 3350 &trigger.entryValue, 3351 /*count*/1); 3352 break; 3353 default: 3354 ALOGE("%s: Type not supported: 0x%x", 3355 __FUNCTION__, 3356 trigger.getTagType()); 3357 return INVALID_OPERATION; 3358 } 3359 3360 if (res != OK) { 3361 ALOGE("%s: Failed to update request metadata with trigger tag %s" 3362 ", value %d", __FUNCTION__, trigger.getTagName(), 3363 trigger.entryValue); 3364 return res; 3365 } 3366 3367 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__, 3368 trigger.getTagName(), 3369 trigger.entryValue); 3370 } 3371 3372 mTriggerMap.clear(); 3373 3374 return count; 3375} 3376 3377status_t Camera3Device::RequestThread::removeTriggers( 3378 const sp<CaptureRequest> &request) { 3379 Mutex::Autolock al(mTriggerMutex); 3380 3381 CameraMetadata &metadata = request->mSettings; 3382 3383 /** 3384 * Replace all old entries with their old values. 3385 */ 3386 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) { 3387 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i); 3388 3389 status_t res; 3390 3391 uint32_t tag = trigger.metadataTag; 3392 switch (trigger.getTagType()) { 3393 case TYPE_BYTE: { 3394 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue); 3395 res = metadata.update(tag, 3396 &entryValue, 3397 /*count*/1); 3398 break; 3399 } 3400 case TYPE_INT32: 3401 res = metadata.update(tag, 3402 &trigger.entryValue, 3403 /*count*/1); 3404 break; 3405 default: 3406 ALOGE("%s: Type not supported: 0x%x", 3407 __FUNCTION__, 3408 trigger.getTagType()); 3409 return INVALID_OPERATION; 3410 } 3411 3412 if (res != OK) { 3413 ALOGE("%s: Failed to restore request metadata with trigger tag %s" 3414 ", trigger value %d", __FUNCTION__, 3415 trigger.getTagName(), trigger.entryValue); 3416 return res; 3417 } 3418 } 3419 mTriggerReplacedMap.clear(); 3420 3421 /** 3422 * Remove all new entries. 3423 */ 3424 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) { 3425 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i); 3426 status_t res = metadata.erase(trigger.metadataTag); 3427 3428 if (res != OK) { 3429 ALOGE("%s: Failed to erase metadata with trigger tag %s" 3430 ", trigger value %d", __FUNCTION__, 3431 trigger.getTagName(), trigger.entryValue); 3432 return res; 3433 } 3434 } 3435 mTriggerRemovedMap.clear(); 3436 3437 return OK; 3438} 3439 3440status_t Camera3Device::RequestThread::addDummyTriggerIds( 3441 const sp<CaptureRequest> &request) { 3442 // Trigger ID 0 has special meaning in the HAL2 spec, so avoid it here 3443 static const int32_t dummyTriggerId = 1; 3444 status_t res; 3445 3446 CameraMetadata &metadata = request->mSettings; 3447 3448 // If AF trigger is active, insert a dummy AF trigger ID if none already 3449 // exists 3450 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER); 3451 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID); 3452 if (afTrigger.count > 0 && 3453 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE && 3454 afId.count == 0) { 3455 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1); 3456 if (res != OK) return res; 3457 } 3458 3459 // If AE precapture trigger is active, insert a dummy precapture trigger ID 3460 // if none already exists 3461 camera_metadata_entry pcTrigger = 3462 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER); 3463 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID); 3464 if (pcTrigger.count > 0 && 3465 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE && 3466 pcId.count == 0) { 3467 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID, 3468 &dummyTriggerId, 1); 3469 if (res != OK) return res; 3470 } 3471 3472 return OK; 3473} 3474 3475/** 3476 * PreparerThread inner class methods 3477 */ 3478 3479Camera3Device::PreparerThread::PreparerThread() : 3480 Thread(/*canCallJava*/false), mActive(false), mCancelNow(false) { 3481} 3482 3483Camera3Device::PreparerThread::~PreparerThread() { 3484 Thread::requestExitAndWait(); 3485 if (mCurrentStream != nullptr) { 3486 mCurrentStream->cancelPrepare(); 3487 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId()); 3488 mCurrentStream.clear(); 3489 } 3490 clear(); 3491} 3492 3493status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) { 3494 status_t res; 3495 3496 Mutex::Autolock l(mLock); 3497 3498 res = stream->startPrepare(maxCount); 3499 if (res == OK) { 3500 // No preparation needed, fire listener right off 3501 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId()); 3502 if (mListener) { 3503 mListener->notifyPrepared(stream->getId()); 3504 } 3505 return OK; 3506 } else if (res != NOT_ENOUGH_DATA) { 3507 return res; 3508 } 3509 3510 // Need to prepare, start up thread if necessary 3511 if (!mActive) { 3512 // mRunning will change to false before the thread fully shuts down, so wait to be sure it 3513 // isn't running 3514 Thread::requestExitAndWait(); 3515 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND); 3516 if (res != OK) { 3517 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res)); 3518 if (mListener) { 3519 mListener->notifyPrepared(stream->getId()); 3520 } 3521 return res; 3522 } 3523 mCancelNow = false; 3524 mActive = true; 3525 ALOGV("%s: Preparer stream started", __FUNCTION__); 3526 } 3527 3528 // queue up the work 3529 mPendingStreams.push_back(stream); 3530 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId()); 3531 3532 return OK; 3533} 3534 3535status_t Camera3Device::PreparerThread::clear() { 3536 status_t res; 3537 3538 Mutex::Autolock l(mLock); 3539 3540 for (const auto& stream : mPendingStreams) { 3541 stream->cancelPrepare(); 3542 } 3543 mPendingStreams.clear(); 3544 mCancelNow = true; 3545 3546 return OK; 3547} 3548 3549void Camera3Device::PreparerThread::setNotificationListener(NotificationListener *listener) { 3550 Mutex::Autolock l(mLock); 3551 mListener = listener; 3552} 3553 3554bool Camera3Device::PreparerThread::threadLoop() { 3555 status_t res; 3556 { 3557 Mutex::Autolock l(mLock); 3558 if (mCurrentStream == nullptr) { 3559 // End thread if done with work 3560 if (mPendingStreams.empty()) { 3561 ALOGV("%s: Preparer stream out of work", __FUNCTION__); 3562 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would 3563 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive. 3564 mActive = false; 3565 return false; 3566 } 3567 3568 // Get next stream to prepare 3569 auto it = mPendingStreams.begin(); 3570 mCurrentStream = *it; 3571 mPendingStreams.erase(it); 3572 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId()); 3573 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId()); 3574 } else if (mCancelNow) { 3575 mCurrentStream->cancelPrepare(); 3576 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId()); 3577 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId()); 3578 mCurrentStream.clear(); 3579 mCancelNow = false; 3580 return true; 3581 } 3582 } 3583 3584 res = mCurrentStream->prepareNextBuffer(); 3585 if (res == NOT_ENOUGH_DATA) return true; 3586 if (res != OK) { 3587 // Something bad happened; try to recover by cancelling prepare and 3588 // signalling listener anyway 3589 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__, 3590 mCurrentStream->getId(), res, strerror(-res)); 3591 mCurrentStream->cancelPrepare(); 3592 } 3593 3594 // This stream has finished, notify listener 3595 Mutex::Autolock l(mLock); 3596 if (mListener) { 3597 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__, 3598 mCurrentStream->getId()); 3599 mListener->notifyPrepared(mCurrentStream->getId()); 3600 } 3601 3602 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId()); 3603 mCurrentStream.clear(); 3604 3605 return true; 3606} 3607 3608/** 3609 * Static callback forwarding methods from HAL to instance 3610 */ 3611 3612void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb, 3613 const camera3_capture_result *result) { 3614 Camera3Device *d = 3615 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb)); 3616 3617 d->processCaptureResult(result); 3618} 3619 3620void Camera3Device::sNotify(const camera3_callback_ops *cb, 3621 const camera3_notify_msg *msg) { 3622 Camera3Device *d = 3623 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb)); 3624 d->notify(msg); 3625} 3626 3627}; // namespace android 3628