Camera3Device.cpp revision 1d1f846c0dbaa36d0944e7b1e54cc07863e00a92
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 <utils/Log.h> 41#include <utils/Trace.h> 42#include <utils/Timers.h> 43 44#include "device3/Camera3Device.h" 45#include "device3/Camera3OutputStream.h" 46#include "device3/Camera3InputStream.h" 47#include "device3/Camera3ZslStream.h" 48 49using namespace android::camera3; 50 51namespace android { 52 53Camera3Device::Camera3Device(int id): 54 mId(id), 55 mHal3Device(NULL), 56 mStatus(STATUS_UNINITIALIZED), 57 mNextResultFrameNumber(0), 58 mNextShutterFrameNumber(0), 59 mListener(NULL) 60{ 61 ATRACE_CALL(); 62 camera3_callback_ops::notify = &sNotify; 63 camera3_callback_ops::process_capture_result = &sProcessCaptureResult; 64 ALOGV("%s: Created device for camera %d", __FUNCTION__, id); 65} 66 67Camera3Device::~Camera3Device() 68{ 69 ATRACE_CALL(); 70 ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId); 71 disconnect(); 72} 73 74int Camera3Device::getId() const { 75 return mId; 76} 77 78/** 79 * CameraDeviceBase interface 80 */ 81 82status_t Camera3Device::initialize(camera_module_t *module) 83{ 84 ATRACE_CALL(); 85 Mutex::Autolock l(mLock); 86 87 ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId); 88 if (mStatus != STATUS_UNINITIALIZED) { 89 CLOGE("Already initialized!"); 90 return INVALID_OPERATION; 91 } 92 93 /** Open HAL device */ 94 95 status_t res; 96 String8 deviceName = String8::format("%d", mId); 97 98 camera3_device_t *device; 99 100 res = module->common.methods->open(&module->common, deviceName.string(), 101 reinterpret_cast<hw_device_t**>(&device)); 102 103 if (res != OK) { 104 SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res); 105 return res; 106 } 107 108 /** Cross-check device version */ 109 110 if (device->common.version != CAMERA_DEVICE_API_VERSION_3_0) { 111 SET_ERR_L("Could not open camera: " 112 "Camera device is not version %x, reports %x instead", 113 CAMERA_DEVICE_API_VERSION_3_0, 114 device->common.version); 115 device->common.close(&device->common); 116 return BAD_VALUE; 117 } 118 119 camera_info info; 120 res = module->get_camera_info(mId, &info); 121 if (res != OK) return res; 122 123 if (info.device_version != device->common.version) { 124 SET_ERR_L("HAL reporting mismatched camera_info version (%x)" 125 " and device version (%x).", 126 device->common.version, info.device_version); 127 device->common.close(&device->common); 128 return BAD_VALUE; 129 } 130 131 /** Initialize device with callback functions */ 132 133 ATRACE_BEGIN("camera3->initialize"); 134 res = device->ops->initialize(device, this); 135 ATRACE_END(); 136 137 if (res != OK) { 138 SET_ERR_L("Unable to initialize HAL device: %s (%d)", 139 strerror(-res), res); 140 device->common.close(&device->common); 141 return BAD_VALUE; 142 } 143 144 /** Get vendor metadata tags */ 145 146 mVendorTagOps.get_camera_vendor_section_name = NULL; 147 148 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops"); 149 device->ops->get_metadata_vendor_tag_ops(device, &mVendorTagOps); 150 ATRACE_END(); 151 152 if (mVendorTagOps.get_camera_vendor_section_name != NULL) { 153 res = set_camera_metadata_vendor_tag_ops(&mVendorTagOps); 154 if (res != OK) { 155 SET_ERR_L("Unable to set tag ops: %s (%d)", 156 strerror(-res), res); 157 device->common.close(&device->common); 158 return res; 159 } 160 } 161 162 /** Start up request queue thread */ 163 164 mRequestThread = new RequestThread(this, device); 165 res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string()); 166 if (res != OK) { 167 SET_ERR_L("Unable to start request queue thread: %s (%d)", 168 strerror(-res), res); 169 device->common.close(&device->common); 170 mRequestThread.clear(); 171 return res; 172 } 173 174 /** Everything is good to go */ 175 176 mDeviceInfo = info.static_camera_characteristics; 177 mHal3Device = device; 178 mStatus = STATUS_IDLE; 179 mNextStreamId = 0; 180 mNeedConfig = true; 181 182 return OK; 183} 184 185status_t Camera3Device::disconnect() { 186 ATRACE_CALL(); 187 Mutex::Autolock l(mLock); 188 189 ALOGV("%s: E", __FUNCTION__); 190 191 status_t res = OK; 192 if (mStatus == STATUS_UNINITIALIZED) return res; 193 194 if (mStatus == STATUS_ACTIVE || 195 (mStatus == STATUS_ERROR && mRequestThread != NULL)) { 196 res = mRequestThread->clearRepeatingRequests(); 197 if (res != OK) { 198 SET_ERR_L("Can't stop streaming"); 199 // Continue to close device even in case of error 200 } else { 201 res = waitUntilDrainedLocked(); 202 if (res != OK) { 203 SET_ERR_L("Timeout waiting for HAL to drain"); 204 // Continue to close device even in case of error 205 } 206 } 207 } 208 assert(mStatus == STATUS_IDLE || mStatus == STATUS_ERROR); 209 210 if (mStatus == STATUS_ERROR) { 211 CLOGE("Shutting down in an error state"); 212 } 213 214 if (mRequestThread != NULL) { 215 mRequestThread->requestExit(); 216 } 217 218 mOutputStreams.clear(); 219 mInputStream.clear(); 220 221 if (mRequestThread != NULL) { 222 if (mStatus != STATUS_ERROR) { 223 // HAL may be in a bad state, so waiting for request thread 224 // (which may be stuck in the HAL processCaptureRequest call) 225 // could be dangerous. 226 mRequestThread->join(); 227 } 228 mRequestThread.clear(); 229 } 230 231 if (mHal3Device != NULL) { 232 mHal3Device->common.close(&mHal3Device->common); 233 mHal3Device = NULL; 234 } 235 236 mStatus = STATUS_UNINITIALIZED; 237 238 ALOGV("%s: X", __FUNCTION__); 239 return res; 240} 241 242status_t Camera3Device::dump(int fd, const Vector<String16> &args) { 243 ATRACE_CALL(); 244 (void)args; 245 String8 lines; 246 247 const char *status = 248 mStatus == STATUS_ERROR ? "ERROR" : 249 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" : 250 mStatus == STATUS_IDLE ? "IDLE" : 251 mStatus == STATUS_ACTIVE ? "ACTIVE" : 252 "Unknown"; 253 lines.appendFormat(" Device status: %s\n", status); 254 if (mStatus == STATUS_ERROR) { 255 lines.appendFormat(" Error cause: %s\n", mErrorCause.string()); 256 } 257 lines.appendFormat(" Stream configuration:\n"); 258 259 if (mInputStream != NULL) { 260 write(fd, lines.string(), lines.size()); 261 mInputStream->dump(fd, args); 262 } else { 263 lines.appendFormat(" No input stream.\n"); 264 write(fd, lines.string(), lines.size()); 265 } 266 for (size_t i = 0; i < mOutputStreams.size(); i++) { 267 mOutputStreams[i]->dump(fd,args); 268 } 269 270 lines = String8(" In-flight requests:\n"); 271 if (mInFlightMap.size() == 0) { 272 lines.append(" None\n"); 273 } else { 274 for (size_t i = 0; i < mInFlightMap.size(); i++) { 275 InFlightRequest r = mInFlightMap.valueAt(i); 276 lines.appendFormat(" Frame %d | Timestamp: %lld, metadata" 277 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i), 278 r.captureTimestamp, r.haveResultMetadata ? "true" : "false", 279 r.numBuffersLeft); 280 } 281 } 282 write(fd, lines.string(), lines.size()); 283 284 { 285 lines = String8(" Last request sent:\n"); 286 write(fd, lines.string(), lines.size()); 287 288 CameraMetadata lastRequest = getLatestRequest(); 289 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6); 290 } 291 292 if (mHal3Device != NULL) { 293 lines = String8(" HAL device dump:\n"); 294 write(fd, lines.string(), lines.size()); 295 mHal3Device->ops->dump(mHal3Device, fd); 296 } 297 298 return OK; 299} 300 301const CameraMetadata& Camera3Device::info() const { 302 ALOGVV("%s: E", __FUNCTION__); 303 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED || 304 mStatus == STATUS_ERROR)) { 305 ALOGW("%s: Access to static info %s!", __FUNCTION__, 306 mStatus == STATUS_ERROR ? 307 "when in error state" : "before init"); 308 } 309 return mDeviceInfo; 310} 311 312status_t Camera3Device::capture(CameraMetadata &request) { 313 ATRACE_CALL(); 314 Mutex::Autolock l(mLock); 315 316 // TODO: take ownership of the request 317 318 switch (mStatus) { 319 case STATUS_ERROR: 320 CLOGE("Device has encountered a serious error"); 321 return INVALID_OPERATION; 322 case STATUS_UNINITIALIZED: 323 CLOGE("Device not initialized"); 324 return INVALID_OPERATION; 325 case STATUS_IDLE: 326 case STATUS_ACTIVE: 327 // OK 328 break; 329 default: 330 SET_ERR_L("Unexpected status: %d", mStatus); 331 return INVALID_OPERATION; 332 } 333 334 sp<CaptureRequest> newRequest = setUpRequestLocked(request); 335 if (newRequest == NULL) { 336 CLOGE("Can't create capture request"); 337 return BAD_VALUE; 338 } 339 340 return mRequestThread->queueRequest(newRequest); 341} 342 343 344status_t Camera3Device::setStreamingRequest(const CameraMetadata &request) { 345 ATRACE_CALL(); 346 Mutex::Autolock l(mLock); 347 348 switch (mStatus) { 349 case STATUS_ERROR: 350 CLOGE("Device has encountered a serious error"); 351 return INVALID_OPERATION; 352 case STATUS_UNINITIALIZED: 353 CLOGE("Device not initialized"); 354 return INVALID_OPERATION; 355 case STATUS_IDLE: 356 case STATUS_ACTIVE: 357 // OK 358 break; 359 default: 360 SET_ERR_L("Unexpected status: %d", mStatus); 361 return INVALID_OPERATION; 362 } 363 364 sp<CaptureRequest> newRepeatingRequest = setUpRequestLocked(request); 365 if (newRepeatingRequest == NULL) { 366 CLOGE("Can't create repeating request"); 367 return BAD_VALUE; 368 } 369 370 RequestList newRepeatingRequests; 371 newRepeatingRequests.push_back(newRepeatingRequest); 372 373 return mRequestThread->setRepeatingRequests(newRepeatingRequests); 374} 375 376 377sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked( 378 const CameraMetadata &request) { 379 status_t res; 380 381 if (mStatus == STATUS_IDLE) { 382 res = configureStreamsLocked(); 383 if (res != OK) { 384 SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res); 385 return NULL; 386 } 387 } 388 389 sp<CaptureRequest> newRequest = createCaptureRequest(request); 390 return newRequest; 391} 392 393status_t Camera3Device::clearStreamingRequest() { 394 ATRACE_CALL(); 395 Mutex::Autolock l(mLock); 396 397 switch (mStatus) { 398 case STATUS_ERROR: 399 CLOGE("Device has encountered a serious error"); 400 return INVALID_OPERATION; 401 case STATUS_UNINITIALIZED: 402 CLOGE("Device not initialized"); 403 return INVALID_OPERATION; 404 case STATUS_IDLE: 405 case STATUS_ACTIVE: 406 // OK 407 break; 408 default: 409 SET_ERR_L("Unexpected status: %d", mStatus); 410 return INVALID_OPERATION; 411 } 412 413 return mRequestThread->clearRepeatingRequests(); 414} 415 416status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) { 417 ATRACE_CALL(); 418 419 return mRequestThread->waitUntilRequestProcessed(requestId, timeout); 420} 421 422status_t Camera3Device::createInputStream( 423 uint32_t width, uint32_t height, int format, int *id) { 424 ATRACE_CALL(); 425 Mutex::Autolock l(mLock); 426 427 status_t res; 428 bool wasActive = false; 429 430 switch (mStatus) { 431 case STATUS_ERROR: 432 ALOGE("%s: Device has encountered a serious error", __FUNCTION__); 433 return INVALID_OPERATION; 434 case STATUS_UNINITIALIZED: 435 ALOGE("%s: Device not initialized", __FUNCTION__); 436 return INVALID_OPERATION; 437 case STATUS_IDLE: 438 // OK 439 break; 440 case STATUS_ACTIVE: 441 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 442 mRequestThread->setPaused(true); 443 res = waitUntilDrainedLocked(); 444 if (res != OK) { 445 ALOGE("%s: Can't pause captures to reconfigure streams!", 446 __FUNCTION__); 447 mStatus = STATUS_ERROR; 448 return res; 449 } 450 wasActive = true; 451 break; 452 default: 453 ALOGE("%s: Unexpected status: %d", __FUNCTION__, mStatus); 454 return INVALID_OPERATION; 455 } 456 assert(mStatus == STATUS_IDLE); 457 458 if (mInputStream != 0) { 459 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__); 460 return INVALID_OPERATION; 461 } 462 463 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId, 464 width, height, format); 465 466 mInputStream = newStream; 467 468 *id = mNextStreamId++; 469 470 // Continue captures if active at start 471 if (wasActive) { 472 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 473 res = configureStreamsLocked(); 474 if (res != OK) { 475 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)", 476 __FUNCTION__, mNextStreamId, strerror(-res), res); 477 return res; 478 } 479 mRequestThread->setPaused(false); 480 } 481 482 return OK; 483} 484 485 486status_t Camera3Device::createZslStream( 487 uint32_t width, uint32_t height, 488 int depth, 489 /*out*/ 490 int *id, 491 sp<Camera3ZslStream>* zslStream) { 492 ATRACE_CALL(); 493 Mutex::Autolock l(mLock); 494 495 status_t res; 496 bool wasActive = false; 497 498 switch (mStatus) { 499 case STATUS_ERROR: 500 ALOGE("%s: Device has encountered a serious error", __FUNCTION__); 501 return INVALID_OPERATION; 502 case STATUS_UNINITIALIZED: 503 ALOGE("%s: Device not initialized", __FUNCTION__); 504 return INVALID_OPERATION; 505 case STATUS_IDLE: 506 // OK 507 break; 508 case STATUS_ACTIVE: 509 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 510 mRequestThread->setPaused(true); 511 res = waitUntilDrainedLocked(); 512 if (res != OK) { 513 ALOGE("%s: Can't pause captures to reconfigure streams!", 514 __FUNCTION__); 515 mStatus = STATUS_ERROR; 516 return res; 517 } 518 wasActive = true; 519 break; 520 default: 521 ALOGE("%s: Unexpected status: %d", __FUNCTION__, mStatus); 522 return INVALID_OPERATION; 523 } 524 assert(mStatus == STATUS_IDLE); 525 526 if (mInputStream != 0) { 527 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__); 528 return INVALID_OPERATION; 529 } 530 531 sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId, 532 width, height, depth); 533 534 res = mOutputStreams.add(mNextStreamId, newStream); 535 if (res < 0) { 536 ALOGE("%s: Can't add new stream to set: %s (%d)", 537 __FUNCTION__, strerror(-res), res); 538 return res; 539 } 540 mInputStream = newStream; 541 542 *id = mNextStreamId++; 543 *zslStream = newStream; 544 545 // Continue captures if active at start 546 if (wasActive) { 547 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 548 res = configureStreamsLocked(); 549 if (res != OK) { 550 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)", 551 __FUNCTION__, mNextStreamId, strerror(-res), res); 552 return res; 553 } 554 mRequestThread->setPaused(false); 555 } 556 557 return OK; 558} 559 560status_t Camera3Device::createStream(sp<ANativeWindow> consumer, 561 uint32_t width, uint32_t height, int format, size_t size, int *id) { 562 ATRACE_CALL(); 563 Mutex::Autolock l(mLock); 564 565 status_t res; 566 bool wasActive = false; 567 568 switch (mStatus) { 569 case STATUS_ERROR: 570 CLOGE("Device has encountered a serious error"); 571 return INVALID_OPERATION; 572 case STATUS_UNINITIALIZED: 573 CLOGE("Device not initialized"); 574 return INVALID_OPERATION; 575 case STATUS_IDLE: 576 // OK 577 break; 578 case STATUS_ACTIVE: 579 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__); 580 mRequestThread->setPaused(true); 581 res = waitUntilDrainedLocked(); 582 if (res != OK) { 583 ALOGE("%s: Can't pause captures to reconfigure streams!", 584 __FUNCTION__); 585 return res; 586 } 587 wasActive = true; 588 break; 589 default: 590 SET_ERR_L("Unexpected status: %d", mStatus); 591 return INVALID_OPERATION; 592 } 593 assert(mStatus == STATUS_IDLE); 594 595 sp<Camera3OutputStream> newStream; 596 if (format == HAL_PIXEL_FORMAT_BLOB) { 597 newStream = new Camera3OutputStream(mNextStreamId, consumer, 598 width, height, size, format); 599 } else { 600 newStream = new Camera3OutputStream(mNextStreamId, consumer, 601 width, height, format); 602 } 603 604 res = mOutputStreams.add(mNextStreamId, newStream); 605 if (res < 0) { 606 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res); 607 return res; 608 } 609 610 *id = mNextStreamId++; 611 mNeedConfig = true; 612 613 // Continue captures if active at start 614 if (wasActive) { 615 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__); 616 res = configureStreamsLocked(); 617 if (res != OK) { 618 CLOGE("Can't reconfigure device for new stream %d: %s (%d)", 619 mNextStreamId, strerror(-res), res); 620 return res; 621 } 622 mRequestThread->setPaused(false); 623 } 624 625 return OK; 626} 627 628status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) { 629 ATRACE_CALL(); 630 (void)outputId; (void)id; 631 632 CLOGE("Unimplemented"); 633 return INVALID_OPERATION; 634} 635 636 637status_t Camera3Device::getStreamInfo(int id, 638 uint32_t *width, uint32_t *height, uint32_t *format) { 639 ATRACE_CALL(); 640 Mutex::Autolock l(mLock); 641 642 switch (mStatus) { 643 case STATUS_ERROR: 644 CLOGE("Device has encountered a serious error"); 645 return INVALID_OPERATION; 646 case STATUS_UNINITIALIZED: 647 CLOGE("Device not initialized!"); 648 return INVALID_OPERATION; 649 case STATUS_IDLE: 650 case STATUS_ACTIVE: 651 // OK 652 break; 653 default: 654 SET_ERR_L("Unexpected status: %d", mStatus); 655 return INVALID_OPERATION; 656 } 657 658 ssize_t idx = mOutputStreams.indexOfKey(id); 659 if (idx == NAME_NOT_FOUND) { 660 CLOGE("Stream %d is unknown", id); 661 return idx; 662 } 663 664 if (width) *width = mOutputStreams[idx]->getWidth(); 665 if (height) *height = mOutputStreams[idx]->getHeight(); 666 if (format) *format = mOutputStreams[idx]->getFormat(); 667 668 return OK; 669} 670 671status_t Camera3Device::setStreamTransform(int id, 672 int transform) { 673 ATRACE_CALL(); 674 Mutex::Autolock l(mLock); 675 676 switch (mStatus) { 677 case STATUS_ERROR: 678 CLOGE("Device has encountered a serious error"); 679 return INVALID_OPERATION; 680 case STATUS_UNINITIALIZED: 681 CLOGE("Device not initialized"); 682 return INVALID_OPERATION; 683 case STATUS_IDLE: 684 case STATUS_ACTIVE: 685 // OK 686 break; 687 default: 688 SET_ERR_L("Unexpected status: %d", mStatus); 689 return INVALID_OPERATION; 690 } 691 692 ssize_t idx = mOutputStreams.indexOfKey(id); 693 if (idx == NAME_NOT_FOUND) { 694 CLOGE("Stream %d does not exist", 695 id); 696 return BAD_VALUE; 697 } 698 699 return mOutputStreams.editValueAt(idx)->setTransform(transform); 700} 701 702status_t Camera3Device::deleteStream(int id) { 703 ATRACE_CALL(); 704 Mutex::Autolock l(mLock); 705 status_t res; 706 707 ALOGV("%s: Camera %d: Deleting stream %d", __FUNCTION__, mId, id); 708 709 // CameraDevice semantics require device to already be idle before 710 // deleteStream is called, unlike for createStream. 711 if (mStatus != STATUS_IDLE) { 712 ALOGV("%s: Camera %d: Device not idle", __FUNCTION__, mId); 713 return -EBUSY; 714 } 715 716 sp<Camera3StreamInterface> deletedStream; 717 if (mInputStream != NULL && id == mInputStream->getId()) { 718 deletedStream = mInputStream; 719 mInputStream.clear(); 720 } else { 721 ssize_t idx = mOutputStreams.indexOfKey(id); 722 if (idx == NAME_NOT_FOUND) { 723 CLOGE("Stream %d does not exist", id); 724 return BAD_VALUE; 725 } 726 deletedStream = mOutputStreams.editValueAt(idx); 727 mOutputStreams.removeItem(id); 728 } 729 730 // Free up the stream endpoint so that it can be used by some other stream 731 res = deletedStream->disconnect(); 732 if (res != OK) { 733 SET_ERR_L("Can't disconnect deleted stream %d", id); 734 // fall through since we want to still list the stream as deleted. 735 } 736 mDeletedStreams.add(deletedStream); 737 mNeedConfig = true; 738 739 return res; 740} 741 742status_t Camera3Device::deleteReprocessStream(int id) { 743 ATRACE_CALL(); 744 (void)id; 745 746 CLOGE("Unimplemented"); 747 return INVALID_OPERATION; 748} 749 750 751status_t Camera3Device::createDefaultRequest(int templateId, 752 CameraMetadata *request) { 753 ATRACE_CALL(); 754 ALOGV("%s: for template %d", __FUNCTION__, templateId); 755 Mutex::Autolock l(mLock); 756 757 switch (mStatus) { 758 case STATUS_ERROR: 759 CLOGE("Device has encountered a serious error"); 760 return INVALID_OPERATION; 761 case STATUS_UNINITIALIZED: 762 CLOGE("Device is not initialized!"); 763 return INVALID_OPERATION; 764 case STATUS_IDLE: 765 case STATUS_ACTIVE: 766 // OK 767 break; 768 default: 769 SET_ERR_L("Unexpected status: %d", mStatus); 770 return INVALID_OPERATION; 771 } 772 773 const camera_metadata_t *rawRequest; 774 ATRACE_BEGIN("camera3->construct_default_request_settings"); 775 rawRequest = mHal3Device->ops->construct_default_request_settings( 776 mHal3Device, templateId); 777 ATRACE_END(); 778 if (rawRequest == NULL) { 779 SET_ERR_L("HAL is unable to construct default settings for template %d", 780 templateId); 781 return DEAD_OBJECT; 782 } 783 *request = rawRequest; 784 785 return OK; 786} 787 788status_t Camera3Device::waitUntilDrained() { 789 ATRACE_CALL(); 790 Mutex::Autolock l(mLock); 791 792 return waitUntilDrainedLocked(); 793} 794 795status_t Camera3Device::waitUntilDrainedLocked() { 796 ATRACE_CALL(); 797 status_t res; 798 799 switch (mStatus) { 800 case STATUS_UNINITIALIZED: 801 case STATUS_IDLE: 802 ALOGV("%s: Already idle", __FUNCTION__); 803 return OK; 804 case STATUS_ERROR: 805 case STATUS_ACTIVE: 806 // Need to shut down 807 break; 808 default: 809 SET_ERR_L("Unexpected status: %d",mStatus); 810 return INVALID_OPERATION; 811 } 812 813 if (mRequestThread != NULL) { 814 res = mRequestThread->waitUntilPaused(kShutdownTimeout); 815 if (res != OK) { 816 SET_ERR_L("Can't stop request thread in %f seconds!", 817 kShutdownTimeout/1e9); 818 return res; 819 } 820 } 821 if (mInputStream != NULL) { 822 res = mInputStream->waitUntilIdle(kShutdownTimeout); 823 if (res != OK) { 824 SET_ERR_L("Can't idle input stream %d in %f seconds!", 825 mInputStream->getId(), kShutdownTimeout/1e9); 826 return res; 827 } 828 } 829 for (size_t i = 0; i < mOutputStreams.size(); i++) { 830 res = mOutputStreams.editValueAt(i)->waitUntilIdle(kShutdownTimeout); 831 if (res != OK) { 832 SET_ERR_L("Can't idle output stream %d in %f seconds!", 833 mOutputStreams.keyAt(i), kShutdownTimeout/1e9); 834 return res; 835 } 836 } 837 838 if (mStatus != STATUS_ERROR) { 839 mStatus = STATUS_IDLE; 840 } 841 842 return OK; 843} 844 845status_t Camera3Device::setNotifyCallback(NotificationListener *listener) { 846 ATRACE_CALL(); 847 Mutex::Autolock l(mOutputLock); 848 849 if (listener != NULL && mListener != NULL) { 850 ALOGW("%s: Replacing old callback listener", __FUNCTION__); 851 } 852 mListener = listener; 853 854 return OK; 855} 856 857bool Camera3Device::willNotify3A() { 858 return false; 859} 860 861status_t Camera3Device::waitForNextFrame(nsecs_t timeout) { 862 ATRACE_CALL(); 863 status_t res; 864 Mutex::Autolock l(mOutputLock); 865 866 while (mResultQueue.empty()) { 867 res = mResultSignal.waitRelative(mOutputLock, timeout); 868 if (res == TIMED_OUT) { 869 return res; 870 } else if (res != OK) { 871 ALOGW("%s: Camera %d: No frame in %lld ns: %s (%d)", 872 __FUNCTION__, mId, timeout, strerror(-res), res); 873 return res; 874 } 875 } 876 return OK; 877} 878 879status_t Camera3Device::getNextFrame(CameraMetadata *frame) { 880 ATRACE_CALL(); 881 Mutex::Autolock l(mOutputLock); 882 883 if (mResultQueue.empty()) { 884 return NOT_ENOUGH_DATA; 885 } 886 887 CameraMetadata &result = *(mResultQueue.begin()); 888 frame->acquire(result); 889 mResultQueue.erase(mResultQueue.begin()); 890 891 return OK; 892} 893 894status_t Camera3Device::triggerAutofocus(uint32_t id) { 895 ATRACE_CALL(); 896 897 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id); 898 // Mix-in this trigger into the next request and only the next request. 899 RequestTrigger trigger[] = { 900 { 901 ANDROID_CONTROL_AF_TRIGGER, 902 ANDROID_CONTROL_AF_TRIGGER_START 903 }, 904 { 905 ANDROID_CONTROL_AF_TRIGGER_ID, 906 static_cast<int32_t>(id) 907 }, 908 }; 909 910 return mRequestThread->queueTrigger(trigger, 911 sizeof(trigger)/sizeof(trigger[0])); 912} 913 914status_t Camera3Device::triggerCancelAutofocus(uint32_t id) { 915 ATRACE_CALL(); 916 917 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id); 918 // Mix-in this trigger into the next request and only the next request. 919 RequestTrigger trigger[] = { 920 { 921 ANDROID_CONTROL_AF_TRIGGER, 922 ANDROID_CONTROL_AF_TRIGGER_CANCEL 923 }, 924 { 925 ANDROID_CONTROL_AF_TRIGGER_ID, 926 static_cast<int32_t>(id) 927 }, 928 }; 929 930 return mRequestThread->queueTrigger(trigger, 931 sizeof(trigger)/sizeof(trigger[0])); 932} 933 934status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) { 935 ATRACE_CALL(); 936 937 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id); 938 // Mix-in this trigger into the next request and only the next request. 939 RequestTrigger trigger[] = { 940 { 941 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, 942 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START 943 }, 944 { 945 ANDROID_CONTROL_AE_PRECAPTURE_ID, 946 static_cast<int32_t>(id) 947 }, 948 }; 949 950 return mRequestThread->queueTrigger(trigger, 951 sizeof(trigger)/sizeof(trigger[0])); 952} 953 954status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId, 955 buffer_handle_t *buffer, wp<BufferReleasedListener> listener) { 956 ATRACE_CALL(); 957 (void)reprocessStreamId; (void)buffer; (void)listener; 958 959 CLOGE("Unimplemented"); 960 return INVALID_OPERATION; 961} 962 963status_t Camera3Device::flush() { 964 ATRACE_CALL(); 965 ALOGV("%s: Camera %d: Flushing all requests", __FUNCTION__, mId); 966 967 Mutex::Autolock l(mLock); 968 969 mRequestThread->clear(); 970 return mHal3Device->ops->flush(mHal3Device); 971} 972 973/** 974 * Camera3Device private methods 975 */ 976 977sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest( 978 const CameraMetadata &request) { 979 ATRACE_CALL(); 980 status_t res; 981 982 sp<CaptureRequest> newRequest = new CaptureRequest; 983 newRequest->mSettings = request; 984 985 camera_metadata_entry_t inputStreams = 986 newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS); 987 if (inputStreams.count > 0) { 988 if (mInputStream == NULL || 989 mInputStream->getId() != inputStreams.data.i32[0]) { 990 CLOGE("Request references unknown input stream %d", 991 inputStreams.data.u8[0]); 992 return NULL; 993 } 994 // Lazy completion of stream configuration (allocation/registration) 995 // on first use 996 if (mInputStream->isConfiguring()) { 997 res = mInputStream->finishConfiguration(mHal3Device); 998 if (res != OK) { 999 SET_ERR_L("Unable to finish configuring input stream %d:" 1000 " %s (%d)", 1001 mInputStream->getId(), strerror(-res), res); 1002 return NULL; 1003 } 1004 } 1005 1006 newRequest->mInputStream = mInputStream; 1007 newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS); 1008 } 1009 1010 camera_metadata_entry_t streams = 1011 newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS); 1012 if (streams.count == 0) { 1013 CLOGE("Zero output streams specified!"); 1014 return NULL; 1015 } 1016 1017 for (size_t i = 0; i < streams.count; i++) { 1018 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]); 1019 if (idx == NAME_NOT_FOUND) { 1020 CLOGE("Request references unknown stream %d", 1021 streams.data.u8[i]); 1022 return NULL; 1023 } 1024 sp<Camera3OutputStreamInterface> stream = 1025 mOutputStreams.editValueAt(idx); 1026 1027 // Lazy completion of stream configuration (allocation/registration) 1028 // on first use 1029 if (stream->isConfiguring()) { 1030 res = stream->finishConfiguration(mHal3Device); 1031 if (res != OK) { 1032 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)", 1033 stream->getId(), strerror(-res), res); 1034 return NULL; 1035 } 1036 } 1037 1038 newRequest->mOutputStreams.push(stream); 1039 } 1040 newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS); 1041 1042 return newRequest; 1043} 1044 1045status_t Camera3Device::configureStreamsLocked() { 1046 ATRACE_CALL(); 1047 status_t res; 1048 1049 if (mStatus != STATUS_IDLE) { 1050 CLOGE("Not idle"); 1051 return INVALID_OPERATION; 1052 } 1053 1054 if (!mNeedConfig) { 1055 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__); 1056 mStatus = STATUS_ACTIVE; 1057 return OK; 1058 } 1059 1060 // Start configuring the streams 1061 1062 camera3_stream_configuration config; 1063 1064 config.num_streams = (mInputStream != NULL) + mOutputStreams.size(); 1065 1066 Vector<camera3_stream_t*> streams; 1067 streams.setCapacity(config.num_streams); 1068 1069 if (mInputStream != NULL) { 1070 camera3_stream_t *inputStream; 1071 inputStream = mInputStream->startConfiguration(); 1072 if (inputStream == NULL) { 1073 SET_ERR_L("Can't start input stream configuration"); 1074 return INVALID_OPERATION; 1075 } 1076 streams.add(inputStream); 1077 } 1078 1079 for (size_t i = 0; i < mOutputStreams.size(); i++) { 1080 1081 // Don't configure bidi streams twice, nor add them twice to the list 1082 if (mOutputStreams[i].get() == 1083 static_cast<Camera3StreamInterface*>(mInputStream.get())) { 1084 1085 config.num_streams--; 1086 continue; 1087 } 1088 1089 camera3_stream_t *outputStream; 1090 outputStream = mOutputStreams.editValueAt(i)->startConfiguration(); 1091 if (outputStream == NULL) { 1092 SET_ERR_L("Can't start output stream configuration"); 1093 return INVALID_OPERATION; 1094 } 1095 streams.add(outputStream); 1096 } 1097 1098 config.streams = streams.editArray(); 1099 1100 // Do the HAL configuration; will potentially touch stream 1101 // max_buffers, usage, priv fields. 1102 ATRACE_BEGIN("camera3->configure_streams"); 1103 res = mHal3Device->ops->configure_streams(mHal3Device, &config); 1104 ATRACE_END(); 1105 1106 if (res != OK) { 1107 SET_ERR_L("Unable to configure streams with HAL: %s (%d)", 1108 strerror(-res), res); 1109 return res; 1110 } 1111 1112 // Finish all stream configuration immediately. 1113 // TODO: Try to relax this later back to lazy completion, which should be 1114 // faster 1115 1116 if (mInputStream != NULL && mInputStream->isConfiguring()) { 1117 res = mInputStream->finishConfiguration(mHal3Device); 1118 if (res != OK) { 1119 SET_ERR_L("Can't finish configuring input stream %d: %s (%d)", 1120 mInputStream->getId(), strerror(-res), res); 1121 return res; 1122 } 1123 } 1124 1125 for (size_t i = 0; i < mOutputStreams.size(); i++) { 1126 sp<Camera3OutputStreamInterface> outputStream = 1127 mOutputStreams.editValueAt(i); 1128 if (outputStream->isConfiguring()) { 1129 res = outputStream->finishConfiguration(mHal3Device); 1130 if (res != OK) { 1131 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)", 1132 outputStream->getId(), strerror(-res), res); 1133 return res; 1134 } 1135 } 1136 } 1137 1138 // Request thread needs to know to avoid using repeat-last-settings protocol 1139 // across configure_streams() calls 1140 mRequestThread->configurationComplete(); 1141 1142 // Finish configuring the streams lazily on first reference 1143 1144 mStatus = STATUS_ACTIVE; 1145 mNeedConfig = false; 1146 1147 return OK; 1148} 1149 1150void Camera3Device::setErrorState(const char *fmt, ...) { 1151 Mutex::Autolock l(mLock); 1152 va_list args; 1153 va_start(args, fmt); 1154 1155 setErrorStateLockedV(fmt, args); 1156 1157 va_end(args); 1158} 1159 1160void Camera3Device::setErrorStateV(const char *fmt, va_list args) { 1161 Mutex::Autolock l(mLock); 1162 setErrorStateLockedV(fmt, args); 1163} 1164 1165void Camera3Device::setErrorStateLocked(const char *fmt, ...) { 1166 va_list args; 1167 va_start(args, fmt); 1168 1169 setErrorStateLockedV(fmt, args); 1170 1171 va_end(args); 1172} 1173 1174void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) { 1175 // Print out all error messages to log 1176 String8 errorCause = String8::formatV(fmt, args); 1177 ALOGE("Camera %d: %s", mId, errorCause.string()); 1178 1179 // But only do error state transition steps for the first error 1180 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return; 1181 1182 mErrorCause = errorCause; 1183 1184 mRequestThread->setPaused(true); 1185 mStatus = STATUS_ERROR; 1186} 1187 1188/** 1189 * In-flight request management 1190 */ 1191 1192status_t Camera3Device::registerInFlight(int32_t frameNumber, 1193 int32_t numBuffers) { 1194 ATRACE_CALL(); 1195 Mutex::Autolock l(mInFlightLock); 1196 1197 ssize_t res; 1198 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers)); 1199 if (res < 0) return res; 1200 1201 return OK; 1202} 1203 1204/** 1205 * Camera HAL device callback methods 1206 */ 1207 1208void Camera3Device::processCaptureResult(const camera3_capture_result *result) { 1209 ATRACE_CALL(); 1210 1211 status_t res; 1212 1213 uint32_t frameNumber = result->frame_number; 1214 if (result->result == NULL && result->num_output_buffers == 0) { 1215 SET_ERR("No result data provided by HAL for frame %d", 1216 frameNumber); 1217 return; 1218 } 1219 1220 // Get capture timestamp from list of in-flight requests, where it was added 1221 // by the shutter notification for this frame. Then update the in-flight 1222 // status and remove the in-flight entry if all result data has been 1223 // received. 1224 nsecs_t timestamp = 0; 1225 { 1226 Mutex::Autolock l(mInFlightLock); 1227 ssize_t idx = mInFlightMap.indexOfKey(frameNumber); 1228 if (idx == NAME_NOT_FOUND) { 1229 SET_ERR("Unknown frame number for capture result: %d", 1230 frameNumber); 1231 return; 1232 } 1233 InFlightRequest &request = mInFlightMap.editValueAt(idx); 1234 timestamp = request.captureTimestamp; 1235 /** 1236 * One of the following must happen before it's legal to call process_capture_result: 1237 * - CAMERA3_MSG_SHUTTER (expected during normal operation) 1238 * - CAMERA3_MSG_ERROR (expected during flush) 1239 */ 1240 if (request.requestStatus == OK && timestamp == 0) { 1241 SET_ERR("Called before shutter notify for frame %d", 1242 frameNumber); 1243 return; 1244 } 1245 1246 if (result->result != NULL) { 1247 if (request.haveResultMetadata) { 1248 SET_ERR("Called multiple times with metadata for frame %d", 1249 frameNumber); 1250 return; 1251 } 1252 request.haveResultMetadata = true; 1253 } 1254 1255 request.numBuffersLeft -= result->num_output_buffers; 1256 1257 if (request.numBuffersLeft < 0) { 1258 SET_ERR("Too many buffers returned for frame %d", 1259 frameNumber); 1260 return; 1261 } 1262 1263 if (request.haveResultMetadata && request.numBuffersLeft == 0) { 1264 ATRACE_ASYNC_END("frame capture", frameNumber); 1265 mInFlightMap.removeItemsAt(idx, 1); 1266 } 1267 1268 // Sanity check - if we have too many in-flight frames, something has 1269 // likely gone wrong 1270 if (mInFlightMap.size() > kInFlightWarnLimit) { 1271 CLOGE("In-flight list too large: %d", mInFlightMap.size()); 1272 } 1273 1274 } 1275 1276 // Process the result metadata, if provided 1277 if (result->result != NULL) { 1278 Mutex::Autolock l(mOutputLock); 1279 1280 if (frameNumber != mNextResultFrameNumber) { 1281 SET_ERR("Out-of-order capture result metadata submitted! " 1282 "(got frame number %d, expecting %d)", 1283 frameNumber, mNextResultFrameNumber); 1284 return; 1285 } 1286 mNextResultFrameNumber++; 1287 1288 CameraMetadata &captureResult = 1289 *mResultQueue.insert(mResultQueue.end(), CameraMetadata()); 1290 1291 captureResult = result->result; 1292 if (captureResult.update(ANDROID_REQUEST_FRAME_COUNT, 1293 (int32_t*)&frameNumber, 1) != OK) { 1294 SET_ERR("Failed to set frame# in metadata (%d)", 1295 frameNumber); 1296 } else { 1297 ALOGVV("%s: Camera %d: Set frame# in metadata (%d)", 1298 __FUNCTION__, mId, frameNumber); 1299 } 1300 1301 // Check that there's a timestamp in the result metadata 1302 1303 camera_metadata_entry entry = 1304 captureResult.find(ANDROID_SENSOR_TIMESTAMP); 1305 if (entry.count == 0) { 1306 SET_ERR("No timestamp provided by HAL for frame %d!", 1307 frameNumber); 1308 } else if (timestamp != entry.data.i64[0]) { 1309 SET_ERR("Timestamp mismatch between shutter notify and result" 1310 " metadata for frame %d (%lld vs %lld respectively)", 1311 frameNumber, timestamp, entry.data.i64[0]); 1312 } 1313 } // scope for mOutputLock 1314 1315 // Return completed buffers to their streams with the timestamp 1316 1317 for (size_t i = 0; i < result->num_output_buffers; i++) { 1318 Camera3Stream *stream = 1319 Camera3Stream::cast(result->output_buffers[i].stream); 1320 res = stream->returnBuffer(result->output_buffers[i], timestamp); 1321 // Note: stream may be deallocated at this point, if this buffer was the 1322 // last reference to it. 1323 if (res != OK) { 1324 SET_ERR("Can't return buffer %d for frame %d to its stream: " 1325 " %s (%d)", i, frameNumber, strerror(-res), res); 1326 } 1327 } 1328 1329 // Finally, signal any waiters for new frames 1330 1331 if (result->result != NULL) { 1332 mResultSignal.signal(); 1333 } 1334 1335} 1336 1337 1338 1339void Camera3Device::notify(const camera3_notify_msg *msg) { 1340 ATRACE_CALL(); 1341 NotificationListener *listener; 1342 { 1343 Mutex::Autolock l(mOutputLock); 1344 listener = mListener; 1345 } 1346 1347 if (msg == NULL) { 1348 SET_ERR("HAL sent NULL notify message!"); 1349 return; 1350 } 1351 1352 switch (msg->type) { 1353 case CAMERA3_MSG_ERROR: { 1354 int streamId = 0; 1355 if (msg->message.error.error_stream != NULL) { 1356 Camera3Stream *stream = 1357 Camera3Stream::cast( 1358 msg->message.error.error_stream); 1359 streamId = stream->getId(); 1360 } 1361 ALOGV("Camera %d: %s: HAL error, frame %d, stream %d: %d", 1362 mId, __FUNCTION__, msg->message.error.frame_number, 1363 streamId, msg->message.error.error_code); 1364 1365 // Set request error status for the request in the in-flight tracking 1366 { 1367 Mutex::Autolock l(mInFlightLock); 1368 ssize_t idx = mInFlightMap.indexOfKey(msg->message.error.frame_number); 1369 if (idx >= 0) { 1370 mInFlightMap.editValueAt(idx).requestStatus = msg->message.error.error_code; 1371 } 1372 } 1373 1374 if (listener != NULL) { 1375 listener->notifyError(msg->message.error.error_code, 1376 msg->message.error.frame_number, streamId); 1377 } 1378 break; 1379 } 1380 case CAMERA3_MSG_SHUTTER: { 1381 ssize_t idx; 1382 uint32_t frameNumber = msg->message.shutter.frame_number; 1383 nsecs_t timestamp = msg->message.shutter.timestamp; 1384 // Verify ordering of shutter notifications 1385 { 1386 Mutex::Autolock l(mOutputLock); 1387 if (frameNumber != mNextShutterFrameNumber) { 1388 SET_ERR("Shutter notification out-of-order. Expected " 1389 "notification for frame %d, got frame %d", 1390 mNextShutterFrameNumber, frameNumber); 1391 break; 1392 } 1393 mNextShutterFrameNumber++; 1394 } 1395 1396 // Set timestamp for the request in the in-flight tracking 1397 { 1398 Mutex::Autolock l(mInFlightLock); 1399 idx = mInFlightMap.indexOfKey(frameNumber); 1400 if (idx >= 0) { 1401 mInFlightMap.editValueAt(idx).captureTimestamp = timestamp; 1402 } 1403 } 1404 if (idx < 0) { 1405 SET_ERR("Shutter notification for non-existent frame number %d", 1406 frameNumber); 1407 break; 1408 } 1409 ALOGVV("Camera %d: %s: Shutter fired for frame %d at %lld", 1410 mId, __FUNCTION__, frameNumber, timestamp); 1411 // Call listener, if any 1412 if (listener != NULL) { 1413 listener->notifyShutter(frameNumber, timestamp); 1414 } 1415 break; 1416 } 1417 default: 1418 SET_ERR("Unknown notify message from HAL: %d", 1419 msg->type); 1420 } 1421} 1422 1423CameraMetadata Camera3Device::getLatestRequest() { 1424 ALOGV("%s", __FUNCTION__); 1425 1426 bool locked = false; 1427 1428 /** 1429 * Why trylock instead of autolock? 1430 * 1431 * We want to be able to call this function from 1432 * dumpsys, which often happens during deadlocks. 1433 */ 1434 for (size_t i = 0; i < kDumpLockAttempts; ++i) { 1435 if (mLock.tryLock() == NO_ERROR) { 1436 locked = true; 1437 break; 1438 } else { 1439 usleep(kDumpSleepDuration); 1440 } 1441 } 1442 1443 if (!locked) { 1444 ALOGW("%s: Possible deadlock detected", __FUNCTION__); 1445 } 1446 1447 CameraMetadata retVal; 1448 1449 if (mRequestThread != NULL) { 1450 retVal = mRequestThread->getLatestRequest(); 1451 } 1452 1453 if (locked) { 1454 mLock.unlock(); 1455 } 1456 1457 return retVal; 1458} 1459 1460/** 1461 * RequestThread inner class methods 1462 */ 1463 1464Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent, 1465 camera3_device_t *hal3Device) : 1466 Thread(false), 1467 mParent(parent), 1468 mHal3Device(hal3Device), 1469 mId(getId(parent)), 1470 mReconfigured(false), 1471 mDoPause(false), 1472 mPaused(true), 1473 mFrameNumber(0), 1474 mLatestRequestId(NAME_NOT_FOUND) { 1475} 1476 1477void Camera3Device::RequestThread::configurationComplete() { 1478 Mutex::Autolock l(mRequestLock); 1479 mReconfigured = true; 1480} 1481 1482status_t Camera3Device::RequestThread::queueRequest( 1483 sp<CaptureRequest> request) { 1484 Mutex::Autolock l(mRequestLock); 1485 mRequestQueue.push_back(request); 1486 1487 unpauseForNewRequests(); 1488 1489 return OK; 1490} 1491 1492 1493status_t Camera3Device::RequestThread::queueTrigger( 1494 RequestTrigger trigger[], 1495 size_t count) { 1496 1497 Mutex::Autolock l(mTriggerMutex); 1498 status_t ret; 1499 1500 for (size_t i = 0; i < count; ++i) { 1501 ret = queueTriggerLocked(trigger[i]); 1502 1503 if (ret != OK) { 1504 return ret; 1505 } 1506 } 1507 1508 return OK; 1509} 1510 1511int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) { 1512 sp<Camera3Device> d = device.promote(); 1513 if (d != NULL) return d->mId; 1514 return 0; 1515} 1516 1517status_t Camera3Device::RequestThread::queueTriggerLocked( 1518 RequestTrigger trigger) { 1519 1520 uint32_t tag = trigger.metadataTag; 1521 ssize_t index = mTriggerMap.indexOfKey(tag); 1522 1523 switch (trigger.getTagType()) { 1524 case TYPE_BYTE: 1525 // fall-through 1526 case TYPE_INT32: 1527 break; 1528 default: 1529 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__, 1530 trigger.getTagType()); 1531 return INVALID_OPERATION; 1532 } 1533 1534 /** 1535 * Collect only the latest trigger, since we only have 1 field 1536 * in the request settings per trigger tag, and can't send more than 1 1537 * trigger per request. 1538 */ 1539 if (index != NAME_NOT_FOUND) { 1540 mTriggerMap.editValueAt(index) = trigger; 1541 } else { 1542 mTriggerMap.add(tag, trigger); 1543 } 1544 1545 return OK; 1546} 1547 1548status_t Camera3Device::RequestThread::setRepeatingRequests( 1549 const RequestList &requests) { 1550 Mutex::Autolock l(mRequestLock); 1551 mRepeatingRequests.clear(); 1552 mRepeatingRequests.insert(mRepeatingRequests.begin(), 1553 requests.begin(), requests.end()); 1554 1555 unpauseForNewRequests(); 1556 1557 return OK; 1558} 1559 1560status_t Camera3Device::RequestThread::clearRepeatingRequests() { 1561 Mutex::Autolock l(mRequestLock); 1562 mRepeatingRequests.clear(); 1563 return OK; 1564} 1565 1566status_t Camera3Device::RequestThread::clear() { 1567 Mutex::Autolock l(mRequestLock); 1568 mRepeatingRequests.clear(); 1569 mRequestQueue.clear(); 1570 mTriggerMap.clear(); 1571 return OK; 1572} 1573 1574void Camera3Device::RequestThread::setPaused(bool paused) { 1575 Mutex::Autolock l(mPauseLock); 1576 mDoPause = paused; 1577 mDoPauseSignal.signal(); 1578} 1579 1580status_t Camera3Device::RequestThread::waitUntilPaused(nsecs_t timeout) { 1581 ATRACE_CALL(); 1582 status_t res; 1583 Mutex::Autolock l(mPauseLock); 1584 while (!mPaused) { 1585 res = mPausedSignal.waitRelative(mPauseLock, timeout); 1586 if (res == TIMED_OUT) { 1587 return res; 1588 } 1589 } 1590 return OK; 1591} 1592 1593status_t Camera3Device::RequestThread::waitUntilRequestProcessed( 1594 int32_t requestId, nsecs_t timeout) { 1595 Mutex::Autolock l(mLatestRequestMutex); 1596 status_t res; 1597 while (mLatestRequestId != requestId) { 1598 nsecs_t startTime = systemTime(); 1599 1600 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout); 1601 if (res != OK) return res; 1602 1603 timeout -= (systemTime() - startTime); 1604 } 1605 1606 return OK; 1607} 1608 1609 1610 1611bool Camera3Device::RequestThread::threadLoop() { 1612 1613 status_t res; 1614 1615 // Handle paused state. 1616 if (waitIfPaused()) { 1617 return true; 1618 } 1619 1620 // Get work to do 1621 1622 sp<CaptureRequest> nextRequest = waitForNextRequest(); 1623 if (nextRequest == NULL) { 1624 return true; 1625 } 1626 1627 // Create request to HAL 1628 camera3_capture_request_t request = camera3_capture_request_t(); 1629 Vector<camera3_stream_buffer_t> outputBuffers; 1630 1631 // Insert any queued triggers (before metadata is locked) 1632 int32_t triggerCount; 1633 res = insertTriggers(nextRequest); 1634 if (res < 0) { 1635 SET_ERR("RequestThread: Unable to insert triggers " 1636 "(capture request %d, HAL device: %s (%d)", 1637 (mFrameNumber+1), strerror(-res), res); 1638 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1639 return false; 1640 } 1641 triggerCount = res; 1642 1643 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0); 1644 1645 // If the request is the same as last, or we had triggers last time 1646 if (mPrevRequest != nextRequest || triggersMixedIn) { 1647 /** 1648 * HAL workaround: 1649 * Insert a dummy trigger ID if a trigger is set but no trigger ID is 1650 */ 1651 res = addDummyTriggerIds(nextRequest); 1652 if (res != OK) { 1653 SET_ERR("RequestThread: Unable to insert dummy trigger IDs " 1654 "(capture request %d, HAL device: %s (%d)", 1655 (mFrameNumber+1), strerror(-res), res); 1656 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1657 return false; 1658 } 1659 1660 /** 1661 * The request should be presorted so accesses in HAL 1662 * are O(logn). Sidenote, sorting a sorted metadata is nop. 1663 */ 1664 nextRequest->mSettings.sort(); 1665 request.settings = nextRequest->mSettings.getAndLock(); 1666 mPrevRequest = nextRequest; 1667 ALOGVV("%s: Request settings are NEW", __FUNCTION__); 1668 1669 IF_ALOGV() { 1670 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t(); 1671 find_camera_metadata_ro_entry( 1672 request.settings, 1673 ANDROID_CONTROL_AF_TRIGGER, 1674 &e 1675 ); 1676 if (e.count > 0) { 1677 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x", 1678 __FUNCTION__, 1679 mFrameNumber+1, 1680 e.data.u8[0]); 1681 } 1682 } 1683 } else { 1684 // leave request.settings NULL to indicate 'reuse latest given' 1685 ALOGVV("%s: Request settings are REUSED", 1686 __FUNCTION__); 1687 } 1688 1689 camera3_stream_buffer_t inputBuffer; 1690 1691 // Fill in buffers 1692 1693 if (nextRequest->mInputStream != NULL) { 1694 request.input_buffer = &inputBuffer; 1695 res = nextRequest->mInputStream->getInputBuffer(&inputBuffer); 1696 if (res != OK) { 1697 SET_ERR("RequestThread: Can't get input buffer, skipping request:" 1698 " %s (%d)", strerror(-res), res); 1699 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1700 return true; 1701 } 1702 } else { 1703 request.input_buffer = NULL; 1704 } 1705 1706 outputBuffers.insertAt(camera3_stream_buffer_t(), 0, 1707 nextRequest->mOutputStreams.size()); 1708 request.output_buffers = outputBuffers.array(); 1709 for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) { 1710 res = nextRequest->mOutputStreams.editItemAt(i)-> 1711 getBuffer(&outputBuffers.editItemAt(i)); 1712 if (res != OK) { 1713 SET_ERR("RequestThread: Can't get output buffer, skipping request:" 1714 "%s (%d)", strerror(-res), res); 1715 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1716 return true; 1717 } 1718 request.num_output_buffers++; 1719 } 1720 1721 request.frame_number = mFrameNumber++; 1722 1723 // Log request in the in-flight queue 1724 sp<Camera3Device> parent = mParent.promote(); 1725 if (parent == NULL) { 1726 CLOGE("RequestThread: Parent is gone"); 1727 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1728 return false; 1729 } 1730 1731 res = parent->registerInFlight(request.frame_number, 1732 request.num_output_buffers); 1733 if (res != OK) { 1734 SET_ERR("RequestThread: Unable to register new in-flight request:" 1735 " %s (%d)", strerror(-res), res); 1736 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1737 return false; 1738 } 1739 1740 // Submit request and block until ready for next one 1741 ATRACE_ASYNC_BEGIN("frame capture", request.frame_number); 1742 ATRACE_BEGIN("camera3->process_capture_request"); 1743 res = mHal3Device->ops->process_capture_request(mHal3Device, &request); 1744 ATRACE_END(); 1745 1746 if (res != OK) { 1747 SET_ERR("RequestThread: Unable to submit capture request %d to HAL" 1748 " device: %s (%d)", request.frame_number, strerror(-res), res); 1749 cleanUpFailedRequest(request, nextRequest, outputBuffers); 1750 return false; 1751 } 1752 1753 // Update the latest request sent to HAL 1754 if (request.settings != NULL) { // Don't update them if they were unchanged 1755 Mutex::Autolock al(mLatestRequestMutex); 1756 1757 camera_metadata_t* cloned = clone_camera_metadata(request.settings); 1758 mLatestRequest.acquire(cloned); 1759 } 1760 1761 if (request.settings != NULL) { 1762 nextRequest->mSettings.unlock(request.settings); 1763 } 1764 1765 // Remove any previously queued triggers (after unlock) 1766 res = removeTriggers(mPrevRequest); 1767 if (res != OK) { 1768 SET_ERR("RequestThread: Unable to remove triggers " 1769 "(capture request %d, HAL device: %s (%d)", 1770 request.frame_number, strerror(-res), res); 1771 return false; 1772 } 1773 mPrevTriggers = triggerCount; 1774 1775 // Read android.request.id from the request settings metadata 1776 // - inform waitUntilRequestProcessed thread of a new request ID 1777 { 1778 Mutex::Autolock al(mLatestRequestMutex); 1779 1780 camera_metadata_entry_t requestIdEntry = 1781 nextRequest->mSettings.find(ANDROID_REQUEST_ID); 1782 if (requestIdEntry.count > 0) { 1783 mLatestRequestId = requestIdEntry.data.i32[0]; 1784 } else { 1785 ALOGW("%s: Did not have android.request.id set in the request", 1786 __FUNCTION__); 1787 mLatestRequestId = NAME_NOT_FOUND; 1788 } 1789 1790 mLatestRequestSignal.signal(); 1791 } 1792 1793 // Return input buffer back to framework 1794 if (request.input_buffer != NULL) { 1795 Camera3Stream *stream = 1796 Camera3Stream::cast(request.input_buffer->stream); 1797 res = stream->returnInputBuffer(*(request.input_buffer)); 1798 // Note: stream may be deallocated at this point, if this buffer was the 1799 // last reference to it. 1800 if (res != OK) { 1801 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to" 1802 " its stream:%s (%d)", __FUNCTION__, 1803 request.frame_number, strerror(-res), res); 1804 // TODO: Report error upstream 1805 } 1806 } 1807 1808 1809 1810 return true; 1811} 1812 1813CameraMetadata Camera3Device::RequestThread::getLatestRequest() const { 1814 Mutex::Autolock al(mLatestRequestMutex); 1815 1816 ALOGV("RequestThread::%s", __FUNCTION__); 1817 1818 return mLatestRequest; 1819} 1820 1821void Camera3Device::RequestThread::cleanUpFailedRequest( 1822 camera3_capture_request_t &request, 1823 sp<CaptureRequest> &nextRequest, 1824 Vector<camera3_stream_buffer_t> &outputBuffers) { 1825 1826 if (request.settings != NULL) { 1827 nextRequest->mSettings.unlock(request.settings); 1828 } 1829 if (request.input_buffer != NULL) { 1830 request.input_buffer->status = CAMERA3_BUFFER_STATUS_ERROR; 1831 nextRequest->mInputStream->returnInputBuffer(*(request.input_buffer)); 1832 } 1833 for (size_t i = 0; i < request.num_output_buffers; i++) { 1834 outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR; 1835 nextRequest->mOutputStreams.editItemAt(i)->returnBuffer( 1836 outputBuffers[i], 0); 1837 } 1838} 1839 1840sp<Camera3Device::CaptureRequest> 1841 Camera3Device::RequestThread::waitForNextRequest() { 1842 status_t res; 1843 sp<CaptureRequest> nextRequest; 1844 1845 // Optimized a bit for the simple steady-state case (single repeating 1846 // request), to avoid putting that request in the queue temporarily. 1847 Mutex::Autolock l(mRequestLock); 1848 1849 while (mRequestQueue.empty()) { 1850 if (!mRepeatingRequests.empty()) { 1851 // Always atomically enqueue all requests in a repeating request 1852 // list. Guarantees a complete in-sequence set of captures to 1853 // application. 1854 const RequestList &requests = mRepeatingRequests; 1855 RequestList::const_iterator firstRequest = 1856 requests.begin(); 1857 nextRequest = *firstRequest; 1858 mRequestQueue.insert(mRequestQueue.end(), 1859 ++firstRequest, 1860 requests.end()); 1861 // No need to wait any longer 1862 break; 1863 } 1864 1865 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout); 1866 1867 if (res == TIMED_OUT) { 1868 // Signal that we're paused by starvation 1869 Mutex::Autolock pl(mPauseLock); 1870 if (mPaused == false) { 1871 mPaused = true; 1872 mPausedSignal.signal(); 1873 } 1874 // Stop waiting for now and let thread management happen 1875 return NULL; 1876 } 1877 } 1878 1879 if (nextRequest == NULL) { 1880 // Don't have a repeating request already in hand, so queue 1881 // must have an entry now. 1882 RequestList::iterator firstRequest = 1883 mRequestQueue.begin(); 1884 nextRequest = *firstRequest; 1885 mRequestQueue.erase(firstRequest); 1886 } 1887 1888 // In case we've been unpaused by setPaused clearing mDoPause, need to 1889 // update internal pause state (capture/setRepeatingRequest unpause 1890 // directly). 1891 Mutex::Autolock pl(mPauseLock); 1892 mPaused = false; 1893 1894 // Check if we've reconfigured since last time, and reset the preview 1895 // request if so. Can't use 'NULL request == repeat' across configure calls. 1896 if (mReconfigured) { 1897 mPrevRequest.clear(); 1898 mReconfigured = false; 1899 } 1900 1901 return nextRequest; 1902} 1903 1904bool Camera3Device::RequestThread::waitIfPaused() { 1905 status_t res; 1906 Mutex::Autolock l(mPauseLock); 1907 while (mDoPause) { 1908 // Signal that we're paused by request 1909 if (mPaused == false) { 1910 mPaused = true; 1911 mPausedSignal.signal(); 1912 } 1913 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout); 1914 if (res == TIMED_OUT) { 1915 return true; 1916 } 1917 } 1918 // We don't set mPaused to false here, because waitForNextRequest needs 1919 // to further manage the paused state in case of starvation. 1920 return false; 1921} 1922 1923void Camera3Device::RequestThread::unpauseForNewRequests() { 1924 // With work to do, mark thread as unpaused. 1925 // If paused by request (setPaused), don't resume, to avoid 1926 // extra signaling/waiting overhead to waitUntilPaused 1927 Mutex::Autolock p(mPauseLock); 1928 if (!mDoPause) { 1929 mPaused = false; 1930 } 1931} 1932 1933void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) { 1934 sp<Camera3Device> parent = mParent.promote(); 1935 if (parent != NULL) { 1936 va_list args; 1937 va_start(args, fmt); 1938 1939 parent->setErrorStateV(fmt, args); 1940 1941 va_end(args); 1942 } 1943} 1944 1945status_t Camera3Device::RequestThread::insertTriggers( 1946 const sp<CaptureRequest> &request) { 1947 1948 Mutex::Autolock al(mTriggerMutex); 1949 1950 CameraMetadata &metadata = request->mSettings; 1951 size_t count = mTriggerMap.size(); 1952 1953 for (size_t i = 0; i < count; ++i) { 1954 RequestTrigger trigger = mTriggerMap.valueAt(i); 1955 1956 uint32_t tag = trigger.metadataTag; 1957 camera_metadata_entry entry = metadata.find(tag); 1958 1959 if (entry.count > 0) { 1960 /** 1961 * Already has an entry for this trigger in the request. 1962 * Rewrite it with our requested trigger value. 1963 */ 1964 RequestTrigger oldTrigger = trigger; 1965 1966 oldTrigger.entryValue = entry.data.u8[0]; 1967 1968 mTriggerReplacedMap.add(tag, oldTrigger); 1969 } else { 1970 /** 1971 * More typical, no trigger entry, so we just add it 1972 */ 1973 mTriggerRemovedMap.add(tag, trigger); 1974 } 1975 1976 status_t res; 1977 1978 switch (trigger.getTagType()) { 1979 case TYPE_BYTE: { 1980 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue); 1981 res = metadata.update(tag, 1982 &entryValue, 1983 /*count*/1); 1984 break; 1985 } 1986 case TYPE_INT32: 1987 res = metadata.update(tag, 1988 &trigger.entryValue, 1989 /*count*/1); 1990 break; 1991 default: 1992 ALOGE("%s: Type not supported: 0x%x", 1993 __FUNCTION__, 1994 trigger.getTagType()); 1995 return INVALID_OPERATION; 1996 } 1997 1998 if (res != OK) { 1999 ALOGE("%s: Failed to update request metadata with trigger tag %s" 2000 ", value %d", __FUNCTION__, trigger.getTagName(), 2001 trigger.entryValue); 2002 return res; 2003 } 2004 2005 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__, 2006 trigger.getTagName(), 2007 trigger.entryValue); 2008 } 2009 2010 mTriggerMap.clear(); 2011 2012 return count; 2013} 2014 2015status_t Camera3Device::RequestThread::removeTriggers( 2016 const sp<CaptureRequest> &request) { 2017 Mutex::Autolock al(mTriggerMutex); 2018 2019 CameraMetadata &metadata = request->mSettings; 2020 2021 /** 2022 * Replace all old entries with their old values. 2023 */ 2024 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) { 2025 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i); 2026 2027 status_t res; 2028 2029 uint32_t tag = trigger.metadataTag; 2030 switch (trigger.getTagType()) { 2031 case TYPE_BYTE: { 2032 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue); 2033 res = metadata.update(tag, 2034 &entryValue, 2035 /*count*/1); 2036 break; 2037 } 2038 case TYPE_INT32: 2039 res = metadata.update(tag, 2040 &trigger.entryValue, 2041 /*count*/1); 2042 break; 2043 default: 2044 ALOGE("%s: Type not supported: 0x%x", 2045 __FUNCTION__, 2046 trigger.getTagType()); 2047 return INVALID_OPERATION; 2048 } 2049 2050 if (res != OK) { 2051 ALOGE("%s: Failed to restore request metadata with trigger tag %s" 2052 ", trigger value %d", __FUNCTION__, 2053 trigger.getTagName(), trigger.entryValue); 2054 return res; 2055 } 2056 } 2057 mTriggerReplacedMap.clear(); 2058 2059 /** 2060 * Remove all new entries. 2061 */ 2062 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) { 2063 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i); 2064 status_t res = metadata.erase(trigger.metadataTag); 2065 2066 if (res != OK) { 2067 ALOGE("%s: Failed to erase metadata with trigger tag %s" 2068 ", trigger value %d", __FUNCTION__, 2069 trigger.getTagName(), trigger.entryValue); 2070 return res; 2071 } 2072 } 2073 mTriggerRemovedMap.clear(); 2074 2075 return OK; 2076} 2077 2078status_t Camera3Device::RequestThread::addDummyTriggerIds( 2079 const sp<CaptureRequest> &request) { 2080 // Trigger ID 0 has special meaning in the HAL2 spec, so avoid it here 2081 static const int32_t dummyTriggerId = 1; 2082 status_t res; 2083 2084 CameraMetadata &metadata = request->mSettings; 2085 2086 // If AF trigger is active, insert a dummy AF trigger ID if none already 2087 // exists 2088 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER); 2089 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID); 2090 if (afTrigger.count > 0 && 2091 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE && 2092 afId.count == 0) { 2093 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1); 2094 if (res != OK) return res; 2095 } 2096 2097 // If AE precapture trigger is active, insert a dummy precapture trigger ID 2098 // if none already exists 2099 camera_metadata_entry pcTrigger = 2100 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER); 2101 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID); 2102 if (pcTrigger.count > 0 && 2103 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE && 2104 pcId.count == 0) { 2105 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID, 2106 &dummyTriggerId, 1); 2107 if (res != OK) return res; 2108 } 2109 2110 return OK; 2111} 2112 2113 2114/** 2115 * Static callback forwarding methods from HAL to instance 2116 */ 2117 2118void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb, 2119 const camera3_capture_result *result) { 2120 Camera3Device *d = 2121 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb)); 2122 d->processCaptureResult(result); 2123} 2124 2125void Camera3Device::sNotify(const camera3_callback_ops *cb, 2126 const camera3_notify_msg *msg) { 2127 Camera3Device *d = 2128 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb)); 2129 d->notify(msg); 2130} 2131 2132}; // namespace android 2133