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