Home | History | Annotate | Download | only in device3
      1 /*
      2  * Copyright (C) 2013-2018 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 %s: %s: " fmt, mId.string(), __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 <utility>
     43 
     44 #include <utils/Log.h>
     45 #include <utils/Trace.h>
     46 #include <utils/Timers.h>
     47 #include <cutils/properties.h>
     48 
     49 #include <android/hardware/camera2/ICameraDeviceUser.h>
     50 
     51 #include "utils/CameraTraces.h"
     52 #include "mediautils/SchedulingPolicyService.h"
     53 #include "device3/Camera3Device.h"
     54 #include "device3/Camera3OutputStream.h"
     55 #include "device3/Camera3InputStream.h"
     56 #include "device3/Camera3DummyStream.h"
     57 #include "device3/Camera3SharedOutputStream.h"
     58 #include "CameraService.h"
     59 #include "utils/CameraThreadState.h"
     60 
     61 #include <tuple>
     62 
     63 using namespace android::camera3;
     64 using namespace android::hardware::camera;
     65 using namespace android::hardware::camera::device::V3_2;
     66 
     67 namespace android {
     68 
     69 Camera3Device::Camera3Device(const String8 &id):
     70         mId(id),
     71         mOperatingMode(NO_MODE),
     72         mIsConstrainedHighSpeedConfiguration(false),
     73         mStatus(STATUS_UNINITIALIZED),
     74         mStatusWaiters(0),
     75         mUsePartialResult(false),
     76         mNumPartialResults(1),
     77         mTimestampOffset(0),
     78         mNextResultFrameNumber(0),
     79         mNextReprocessResultFrameNumber(0),
     80         mNextZslStillResultFrameNumber(0),
     81         mNextShutterFrameNumber(0),
     82         mNextReprocessShutterFrameNumber(0),
     83         mNextZslStillShutterFrameNumber(0),
     84         mListener(NULL),
     85         mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
     86         mLastTemplateId(-1),
     87         mNeedFixupMonochromeTags(false)
     88 {
     89     ATRACE_CALL();
     90     ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
     91 }
     92 
     93 Camera3Device::~Camera3Device()
     94 {
     95     ATRACE_CALL();
     96     ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
     97     disconnectImpl();
     98 }
     99 
    100 const String8& Camera3Device::getId() const {
    101     return mId;
    102 }
    103 
    104 status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
    105     ATRACE_CALL();
    106     Mutex::Autolock il(mInterfaceLock);
    107     Mutex::Autolock l(mLock);
    108 
    109     ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
    110     if (mStatus != STATUS_UNINITIALIZED) {
    111         CLOGE("Already initialized!");
    112         return INVALID_OPERATION;
    113     }
    114     if (manager == nullptr) return INVALID_OPERATION;
    115 
    116     sp<ICameraDeviceSession> session;
    117     ATRACE_BEGIN("CameraHal::openSession");
    118     status_t res = manager->openSession(mId.string(), this,
    119             /*out*/ &session);
    120     ATRACE_END();
    121     if (res != OK) {
    122         SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
    123         return res;
    124     }
    125 
    126     res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
    127     if (res != OK) {
    128         SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
    129         session->close();
    130         return res;
    131     }
    132 
    133     std::vector<std::string> physicalCameraIds;
    134     bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
    135     if (isLogical) {
    136         for (auto& physicalId : physicalCameraIds) {
    137             res = manager->getCameraCharacteristics(
    138                     physicalId, &mPhysicalDeviceInfoMap[physicalId]);
    139             if (res != OK) {
    140                 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
    141                         physicalId.c_str(), strerror(-res), res);
    142                 session->close();
    143                 return res;
    144             }
    145 
    146             if (DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId])) {
    147                 mDistortionMappers[physicalId].setupStaticInfo(mPhysicalDeviceInfoMap[physicalId]);
    148                 if (res != OK) {
    149                     SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
    150                             "correction", physicalId.c_str());
    151                     session->close();
    152                     return res;
    153                 }
    154             }
    155         }
    156     }
    157 
    158     std::shared_ptr<RequestMetadataQueue> queue;
    159     auto requestQueueRet = session->getCaptureRequestMetadataQueue(
    160         [&queue](const auto& descriptor) {
    161             queue = std::make_shared<RequestMetadataQueue>(descriptor);
    162             if (!queue->isValid() || queue->availableToWrite() <= 0) {
    163                 ALOGE("HAL returns empty request metadata fmq, not use it");
    164                 queue = nullptr;
    165                 // don't use the queue onwards.
    166             }
    167         });
    168     if (!requestQueueRet.isOk()) {
    169         ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
    170                 requestQueueRet.description().c_str());
    171         return DEAD_OBJECT;
    172     }
    173 
    174     std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
    175     auto resultQueueRet = session->getCaptureResultMetadataQueue(
    176         [&resQueue](const auto& descriptor) {
    177             resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
    178             if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
    179                 ALOGE("HAL returns empty result metadata fmq, not use it");
    180                 resQueue = nullptr;
    181                 // Don't use the resQueue onwards.
    182             }
    183         });
    184     if (!resultQueueRet.isOk()) {
    185         ALOGE("Transaction error when getting result metadata queue from camera session: %s",
    186                 resultQueueRet.description().c_str());
    187         return DEAD_OBJECT;
    188     }
    189     IF_ALOGV() {
    190         session->interfaceChain([](
    191             ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
    192                 ALOGV("Session interface chain:");
    193                 for (const auto& iface : interfaceChain) {
    194                     ALOGV("  %s", iface.c_str());
    195                 }
    196             });
    197     }
    198 
    199     camera_metadata_entry bufMgrMode =
    200             mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
    201     if (bufMgrMode.count > 0) {
    202          mUseHalBufManager = (bufMgrMode.data.u8[0] ==
    203             ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
    204     }
    205 
    206     mInterface = new HalInterface(session, queue, mUseHalBufManager);
    207     std::string providerType;
    208     mVendorTagId = manager->getProviderTagIdLocked(mId.string());
    209     mTagMonitor.initialize(mVendorTagId);
    210     if (!monitorTags.isEmpty()) {
    211         mTagMonitor.parseTagsToMonitor(String8(monitorTags));
    212     }
    213 
    214     // Metadata tags needs fixup for monochrome camera device version less
    215     // than 3.5.
    216     hardware::hidl_version maxVersion{0,0};
    217     res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
    218     if (res != OK) {
    219         ALOGE("%s: Error in getting camera device version id: %s (%d)",
    220                 __FUNCTION__, strerror(-res), res);
    221         return res;
    222     }
    223     int deviceVersion = HARDWARE_DEVICE_API_VERSION(
    224             maxVersion.get_major(), maxVersion.get_minor());
    225 
    226     bool isMonochrome = false;
    227     camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
    228     for (size_t i = 0; i < entry.count; i++) {
    229         uint8_t capability = entry.data.u8[i];
    230         if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
    231             isMonochrome = true;
    232         }
    233     }
    234     mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
    235 
    236     return initializeCommonLocked();
    237 }
    238 
    239 status_t Camera3Device::initializeCommonLocked() {
    240 
    241     /** Start up status tracker thread */
    242     mStatusTracker = new StatusTracker(this);
    243     status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
    244     if (res != OK) {
    245         SET_ERR_L("Unable to start status tracking thread: %s (%d)",
    246                 strerror(-res), res);
    247         mInterface->close();
    248         mStatusTracker.clear();
    249         return res;
    250     }
    251 
    252     /** Register in-flight map to the status tracker */
    253     mInFlightStatusId = mStatusTracker->addComponent();
    254 
    255     if (mUseHalBufManager) {
    256         res = mRequestBufferSM.initialize(mStatusTracker);
    257         if (res != OK) {
    258             SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
    259                     strerror(-res), res);
    260             mInterface->close();
    261             mStatusTracker.clear();
    262             return res;
    263         }
    264     }
    265 
    266     /** Create buffer manager */
    267     mBufferManager = new Camera3BufferManager();
    268 
    269     Vector<int32_t> sessionParamKeys;
    270     camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
    271             ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
    272     if (sessionKeysEntry.count > 0) {
    273         sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
    274     }
    275 
    276     /** Start up request queue thread */
    277     mRequestThread = new RequestThread(
    278             this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
    279     res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
    280     if (res != OK) {
    281         SET_ERR_L("Unable to start request queue thread: %s (%d)",
    282                 strerror(-res), res);
    283         mInterface->close();
    284         mRequestThread.clear();
    285         return res;
    286     }
    287 
    288     mPreparerThread = new PreparerThread();
    289 
    290     internalUpdateStatusLocked(STATUS_UNCONFIGURED);
    291     mNextStreamId = 0;
    292     mDummyStreamId = NO_STREAM;
    293     mNeedConfig = true;
    294     mPauseStateNotify = false;
    295 
    296     // Measure the clock domain offset between camera and video/hw_composer
    297     camera_metadata_entry timestampSource =
    298             mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
    299     if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
    300             ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
    301         mTimestampOffset = getMonoToBoottimeOffset();
    302     }
    303 
    304     // Will the HAL be sending in early partial result metadata?
    305     camera_metadata_entry partialResultsCount =
    306             mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
    307     if (partialResultsCount.count > 0) {
    308         mNumPartialResults = partialResultsCount.data.i32[0];
    309         mUsePartialResult = (mNumPartialResults > 1);
    310     }
    311 
    312     camera_metadata_entry configs =
    313             mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
    314     for (uint32_t i = 0; i < configs.count; i += 4) {
    315         if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
    316                 configs.data.i32[i + 3] ==
    317                 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
    318             mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
    319                     configs.data.i32[i + 2]));
    320         }
    321     }
    322 
    323     if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
    324         res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
    325         if (res != OK) {
    326             SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
    327             return res;
    328         }
    329     }
    330     return OK;
    331 }
    332 
    333 status_t Camera3Device::disconnect() {
    334     return disconnectImpl();
    335 }
    336 
    337 status_t Camera3Device::disconnectImpl() {
    338     ATRACE_CALL();
    339     Mutex::Autolock il(mInterfaceLock);
    340 
    341     ALOGI("%s: E", __FUNCTION__);
    342 
    343     status_t res = OK;
    344     std::vector<wp<Camera3StreamInterface>> streams;
    345     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
    346     {
    347         Mutex::Autolock l(mLock);
    348         if (mStatus == STATUS_UNINITIALIZED) return res;
    349 
    350         if (mStatus == STATUS_ACTIVE ||
    351                 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
    352             res = mRequestThread->clearRepeatingRequests();
    353             if (res != OK) {
    354                 SET_ERR_L("Can't stop streaming");
    355                 // Continue to close device even in case of error
    356             } else {
    357                 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
    358                 if (res != OK) {
    359                     SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
    360                             maxExpectedDuration);
    361                     // Continue to close device even in case of error
    362                 }
    363             }
    364         }
    365 
    366         if (mStatus == STATUS_ERROR) {
    367             CLOGE("Shutting down in an error state");
    368         }
    369 
    370         if (mStatusTracker != NULL) {
    371             mStatusTracker->requestExit();
    372         }
    373 
    374         if (mRequestThread != NULL) {
    375             mRequestThread->requestExit();
    376         }
    377 
    378         streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
    379         for (size_t i = 0; i < mOutputStreams.size(); i++) {
    380             streams.push_back(mOutputStreams[i]);
    381         }
    382         if (mInputStream != nullptr) {
    383             streams.push_back(mInputStream);
    384         }
    385     }
    386 
    387     // Joining done without holding mLock, otherwise deadlocks may ensue
    388     // as the threads try to access parent state
    389     if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
    390         // HAL may be in a bad state, so waiting for request thread
    391         // (which may be stuck in the HAL processCaptureRequest call)
    392         // could be dangerous.
    393         mRequestThread->join();
    394     }
    395 
    396     if (mStatusTracker != NULL) {
    397         mStatusTracker->join();
    398     }
    399 
    400     HalInterface* interface;
    401     {
    402         Mutex::Autolock l(mLock);
    403         mRequestThread.clear();
    404         Mutex::Autolock stLock(mTrackerLock);
    405         mStatusTracker.clear();
    406         interface = mInterface.get();
    407     }
    408 
    409     // Call close without internal mutex held, as the HAL close may need to
    410     // wait on assorted callbacks,etc, to complete before it can return.
    411     interface->close();
    412 
    413     flushInflightRequests();
    414 
    415     {
    416         Mutex::Autolock l(mLock);
    417         mInterface->clear();
    418         mOutputStreams.clear();
    419         mInputStream.clear();
    420         mDeletedStreams.clear();
    421         mBufferManager.clear();
    422         internalUpdateStatusLocked(STATUS_UNINITIALIZED);
    423     }
    424 
    425     for (auto& weakStream : streams) {
    426         sp<Camera3StreamInterface> stream = weakStream.promote();
    427         if (stream != nullptr) {
    428             ALOGE("%s: Stream %d leaked! strong reference (%d)!",
    429                     __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
    430         }
    431     }
    432 
    433     ALOGI("%s: X", __FUNCTION__);
    434     return res;
    435 }
    436 
    437 // For dumping/debugging only -
    438 // try to acquire a lock a few times, eventually give up to proceed with
    439 // debug/dump operations
    440 bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
    441     bool gotLock = false;
    442     for (size_t i = 0; i < kDumpLockAttempts; ++i) {
    443         if (lock.tryLock() == NO_ERROR) {
    444             gotLock = true;
    445             break;
    446         } else {
    447             usleep(kDumpSleepDuration);
    448         }
    449     }
    450     return gotLock;
    451 }
    452 
    453 Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
    454     int32_t maxJpegWidth = 0, maxJpegHeight = 0;
    455     const int STREAM_CONFIGURATION_SIZE = 4;
    456     const int STREAM_FORMAT_OFFSET = 0;
    457     const int STREAM_WIDTH_OFFSET = 1;
    458     const int STREAM_HEIGHT_OFFSET = 2;
    459     const int STREAM_IS_INPUT_OFFSET = 3;
    460     camera_metadata_ro_entry_t availableStreamConfigs =
    461             mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
    462     if (availableStreamConfigs.count == 0 ||
    463             availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
    464         return Size(0, 0);
    465     }
    466 
    467     // Get max jpeg size (area-wise).
    468     for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
    469         int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
    470         int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
    471         int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
    472         int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
    473         if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
    474                 && format == HAL_PIXEL_FORMAT_BLOB &&
    475                 (width * height > maxJpegWidth * maxJpegHeight)) {
    476             maxJpegWidth = width;
    477             maxJpegHeight = height;
    478         }
    479     }
    480 
    481     return Size(maxJpegWidth, maxJpegHeight);
    482 }
    483 
    484 nsecs_t Camera3Device::getMonoToBoottimeOffset() {
    485     // try three times to get the clock offset, choose the one
    486     // with the minimum gap in measurements.
    487     const int tries = 3;
    488     nsecs_t bestGap, measured;
    489     for (int i = 0; i < tries; ++i) {
    490         const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
    491         const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
    492         const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
    493         const nsecs_t gap = tmono2 - tmono;
    494         if (i == 0 || gap < bestGap) {
    495             bestGap = gap;
    496             measured = tbase - ((tmono + tmono2) >> 1);
    497         }
    498     }
    499     return measured;
    500 }
    501 
    502 hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
    503         int frameworkFormat) {
    504     return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
    505 }
    506 
    507 DataspaceFlags Camera3Device::mapToHidlDataspace(
    508         android_dataspace dataSpace) {
    509     return dataSpace;
    510 }
    511 
    512 BufferUsageFlags Camera3Device::mapToConsumerUsage(
    513         uint64_t usage) {
    514     return usage;
    515 }
    516 
    517 StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
    518     switch (rotation) {
    519         case CAMERA3_STREAM_ROTATION_0:
    520             return StreamRotation::ROTATION_0;
    521         case CAMERA3_STREAM_ROTATION_90:
    522             return StreamRotation::ROTATION_90;
    523         case CAMERA3_STREAM_ROTATION_180:
    524             return StreamRotation::ROTATION_180;
    525         case CAMERA3_STREAM_ROTATION_270:
    526             return StreamRotation::ROTATION_270;
    527     }
    528     ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
    529     return StreamRotation::ROTATION_0;
    530 }
    531 
    532 status_t Camera3Device::mapToStreamConfigurationMode(
    533         camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
    534     if (mode == nullptr) return BAD_VALUE;
    535     if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
    536         switch(operationMode) {
    537             case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
    538                 *mode = StreamConfigurationMode::NORMAL_MODE;
    539                 break;
    540             case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
    541                 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
    542                 break;
    543             default:
    544                 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
    545                 return BAD_VALUE;
    546         }
    547     } else {
    548         *mode = static_cast<StreamConfigurationMode>(operationMode);
    549     }
    550     return OK;
    551 }
    552 
    553 camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
    554     switch (status) {
    555         case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
    556         case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
    557     }
    558     return CAMERA3_BUFFER_STATUS_ERROR;
    559 }
    560 
    561 int Camera3Device::mapToFrameworkFormat(
    562         hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
    563     return static_cast<uint32_t>(pixelFormat);
    564 }
    565 
    566 android_dataspace Camera3Device::mapToFrameworkDataspace(
    567         DataspaceFlags dataSpace) {
    568     return static_cast<android_dataspace>(dataSpace);
    569 }
    570 
    571 uint64_t Camera3Device::mapConsumerToFrameworkUsage(
    572         BufferUsageFlags usage) {
    573     return usage;
    574 }
    575 
    576 uint64_t Camera3Device::mapProducerToFrameworkUsage(
    577         BufferUsageFlags usage) {
    578     return usage;
    579 }
    580 
    581 ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
    582     // Get max jpeg size (area-wise).
    583     Size maxJpegResolution = getMaxJpegResolution();
    584     if (maxJpegResolution.width == 0) {
    585         ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
    586                 __FUNCTION__, mId.string());
    587         return BAD_VALUE;
    588     }
    589 
    590     // Get max jpeg buffer size
    591     ssize_t maxJpegBufferSize = 0;
    592     camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
    593     if (jpegBufMaxSize.count == 0) {
    594         ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
    595                 mId.string());
    596         return BAD_VALUE;
    597     }
    598     maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
    599     assert(kMinJpegBufferSize < maxJpegBufferSize);
    600 
    601     // Calculate final jpeg buffer size for the given resolution.
    602     float scaleFactor = ((float) (width * height)) /
    603             (maxJpegResolution.width * maxJpegResolution.height);
    604     ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
    605             kMinJpegBufferSize;
    606     if (jpegBufferSize > maxJpegBufferSize) {
    607         jpegBufferSize = maxJpegBufferSize;
    608     }
    609 
    610     return jpegBufferSize;
    611 }
    612 
    613 ssize_t Camera3Device::getPointCloudBufferSize() const {
    614     const int FLOATS_PER_POINT=4;
    615     camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
    616     if (maxPointCount.count == 0) {
    617         ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
    618                 __FUNCTION__, mId.string());
    619         return BAD_VALUE;
    620     }
    621     ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
    622             maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
    623     return maxBytesForPointCloud;
    624 }
    625 
    626 ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
    627     const int PER_CONFIGURATION_SIZE = 3;
    628     const int WIDTH_OFFSET = 0;
    629     const int HEIGHT_OFFSET = 1;
    630     const int SIZE_OFFSET = 2;
    631     camera_metadata_ro_entry rawOpaqueSizes =
    632         mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
    633     size_t count = rawOpaqueSizes.count;
    634     if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
    635         ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
    636                 __FUNCTION__, mId.string(), count);
    637         return BAD_VALUE;
    638     }
    639 
    640     for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
    641         if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
    642                 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
    643             return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
    644         }
    645     }
    646 
    647     ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
    648             __FUNCTION__, mId.string(), width, height);
    649     return BAD_VALUE;
    650 }
    651 
    652 status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
    653     ATRACE_CALL();
    654     (void)args;
    655 
    656     // Try to lock, but continue in case of failure (to avoid blocking in
    657     // deadlocks)
    658     bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
    659     bool gotLock = tryLockSpinRightRound(mLock);
    660 
    661     ALOGW_IF(!gotInterfaceLock,
    662             "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
    663             mId.string(), __FUNCTION__);
    664     ALOGW_IF(!gotLock,
    665             "Camera %s: %s: Unable to lock main lock, proceeding anyway",
    666             mId.string(), __FUNCTION__);
    667 
    668     bool dumpTemplates = false;
    669 
    670     String16 templatesOption("-t");
    671     int n = args.size();
    672     for (int i = 0; i < n; i++) {
    673         if (args[i] == templatesOption) {
    674             dumpTemplates = true;
    675         }
    676         if (args[i] == TagMonitor::kMonitorOption) {
    677             if (i + 1 < n) {
    678                 String8 monitorTags = String8(args[i + 1]);
    679                 if (monitorTags == "off") {
    680                     mTagMonitor.disableMonitoring();
    681                 } else {
    682                     mTagMonitor.parseTagsToMonitor(monitorTags);
    683                 }
    684             } else {
    685                 mTagMonitor.disableMonitoring();
    686             }
    687         }
    688     }
    689 
    690     String8 lines;
    691 
    692     const char *status =
    693             mStatus == STATUS_ERROR         ? "ERROR" :
    694             mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
    695             mStatus == STATUS_UNCONFIGURED  ? "UNCONFIGURED" :
    696             mStatus == STATUS_CONFIGURED    ? "CONFIGURED" :
    697             mStatus == STATUS_ACTIVE        ? "ACTIVE" :
    698             "Unknown";
    699 
    700     lines.appendFormat("    Device status: %s\n", status);
    701     if (mStatus == STATUS_ERROR) {
    702         lines.appendFormat("    Error cause: %s\n", mErrorCause.string());
    703     }
    704     lines.appendFormat("    Stream configuration:\n");
    705     const char *mode =
    706             mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
    707             mOperatingMode == static_cast<int>(
    708                 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
    709             "CUSTOM";
    710     lines.appendFormat("    Operation mode: %s (%d) \n", mode, mOperatingMode);
    711 
    712     if (mInputStream != NULL) {
    713         write(fd, lines.string(), lines.size());
    714         mInputStream->dump(fd, args);
    715     } else {
    716         lines.appendFormat("      No input stream.\n");
    717         write(fd, lines.string(), lines.size());
    718     }
    719     for (size_t i = 0; i < mOutputStreams.size(); i++) {
    720         mOutputStreams[i]->dump(fd,args);
    721     }
    722 
    723     if (mBufferManager != NULL) {
    724         lines = String8("    Camera3 Buffer Manager:\n");
    725         write(fd, lines.string(), lines.size());
    726         mBufferManager->dump(fd, args);
    727     }
    728 
    729     lines = String8("    In-flight requests:\n");
    730     if (mInFlightMap.size() == 0) {
    731         lines.append("      None\n");
    732     } else {
    733         for (size_t i = 0; i < mInFlightMap.size(); i++) {
    734             InFlightRequest r = mInFlightMap.valueAt(i);
    735             lines.appendFormat("      Frame %d |  Timestamp: %" PRId64 ", metadata"
    736                     " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
    737                     r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
    738                     r.numBuffersLeft);
    739         }
    740     }
    741     write(fd, lines.string(), lines.size());
    742 
    743     if (mRequestThread != NULL) {
    744         mRequestThread->dumpCaptureRequestLatency(fd,
    745                 "    ProcessCaptureRequest latency histogram:");
    746     }
    747 
    748     {
    749         lines = String8("    Last request sent:\n");
    750         write(fd, lines.string(), lines.size());
    751 
    752         CameraMetadata lastRequest = getLatestRequestLocked();
    753         lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
    754     }
    755 
    756     if (dumpTemplates) {
    757         const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
    758             "TEMPLATE_PREVIEW",
    759             "TEMPLATE_STILL_CAPTURE",
    760             "TEMPLATE_VIDEO_RECORD",
    761             "TEMPLATE_VIDEO_SNAPSHOT",
    762             "TEMPLATE_ZERO_SHUTTER_LAG",
    763             "TEMPLATE_MANUAL",
    764         };
    765 
    766         for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
    767             camera_metadata_t *templateRequest = nullptr;
    768             mInterface->constructDefaultRequestSettings(
    769                     (camera3_request_template_t) i, &templateRequest);
    770             lines = String8::format("    HAL Request %s:\n", templateNames[i-1]);
    771             if (templateRequest == nullptr) {
    772                 lines.append("       Not supported\n");
    773                 write(fd, lines.string(), lines.size());
    774             } else {
    775                 write(fd, lines.string(), lines.size());
    776                 dump_indented_camera_metadata(templateRequest,
    777                         fd, /*verbosity*/2, /*indentation*/8);
    778             }
    779             free_camera_metadata(templateRequest);
    780         }
    781     }
    782 
    783     mTagMonitor.dumpMonitoredMetadata(fd);
    784 
    785     if (mInterface->valid()) {
    786         lines = String8("     HAL device dump:\n");
    787         write(fd, lines.string(), lines.size());
    788         mInterface->dump(fd);
    789     }
    790 
    791     if (gotLock) mLock.unlock();
    792     if (gotInterfaceLock) mInterfaceLock.unlock();
    793 
    794     return OK;
    795 }
    796 
    797 const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
    798     ALOGVV("%s: E", __FUNCTION__);
    799     if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
    800                     mStatus == STATUS_ERROR)) {
    801         ALOGW("%s: Access to static info %s!", __FUNCTION__,
    802                 mStatus == STATUS_ERROR ?
    803                 "when in error state" : "before init");
    804     }
    805     if (physicalId.isEmpty()) {
    806         return mDeviceInfo;
    807     } else {
    808         std::string id(physicalId.c_str());
    809         if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
    810             return mPhysicalDeviceInfoMap.at(id);
    811         } else {
    812             ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
    813             return mDeviceInfo;
    814         }
    815     }
    816 }
    817 
    818 const CameraMetadata& Camera3Device::info() const {
    819     String8 emptyId;
    820     return info(emptyId);
    821 }
    822 
    823 status_t Camera3Device::checkStatusOkToCaptureLocked() {
    824     switch (mStatus) {
    825         case STATUS_ERROR:
    826             CLOGE("Device has encountered a serious error");
    827             return INVALID_OPERATION;
    828         case STATUS_UNINITIALIZED:
    829             CLOGE("Device not initialized");
    830             return INVALID_OPERATION;
    831         case STATUS_UNCONFIGURED:
    832         case STATUS_CONFIGURED:
    833         case STATUS_ACTIVE:
    834             // OK
    835             break;
    836         default:
    837             SET_ERR_L("Unexpected status: %d", mStatus);
    838             return INVALID_OPERATION;
    839     }
    840     return OK;
    841 }
    842 
    843 status_t Camera3Device::convertMetadataListToRequestListLocked(
    844         const List<const PhysicalCameraSettingsList> &metadataList,
    845         const std::list<const SurfaceMap> &surfaceMaps,
    846         bool repeating,
    847         RequestList *requestList) {
    848     if (requestList == NULL) {
    849         CLOGE("requestList cannot be NULL.");
    850         return BAD_VALUE;
    851     }
    852 
    853     int32_t burstId = 0;
    854     List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
    855     std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
    856     for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
    857             ++metadataIt, ++surfaceMapIt) {
    858         sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
    859         if (newRequest == 0) {
    860             CLOGE("Can't create capture request");
    861             return BAD_VALUE;
    862         }
    863 
    864         newRequest->mRepeating = repeating;
    865 
    866         // Setup burst Id and request Id
    867         newRequest->mResultExtras.burstId = burstId++;
    868         if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
    869             if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
    870                 CLOGE("RequestID entry exists; but must not be empty in metadata");
    871                 return BAD_VALUE;
    872             }
    873             newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
    874                     ANDROID_REQUEST_ID).data.i32[0];
    875         } else {
    876             CLOGE("RequestID does not exist in metadata");
    877             return BAD_VALUE;
    878         }
    879 
    880         requestList->push_back(newRequest);
    881 
    882         ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
    883     }
    884     if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
    885         ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
    886         return BAD_VALUE;
    887     }
    888 
    889     // Setup batch size if this is a high speed video recording request.
    890     if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
    891         auto firstRequest = requestList->begin();
    892         for (auto& outputStream : (*firstRequest)->mOutputStreams) {
    893             if (outputStream->isVideoStream()) {
    894                 (*firstRequest)->mBatchSize = requestList->size();
    895                 break;
    896             }
    897         }
    898     }
    899 
    900     return OK;
    901 }
    902 
    903 status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
    904     ATRACE_CALL();
    905 
    906     List<const PhysicalCameraSettingsList> requestsList;
    907     std::list<const SurfaceMap> surfaceMaps;
    908     convertToRequestList(requestsList, surfaceMaps, request);
    909 
    910     return captureList(requestsList, surfaceMaps, lastFrameNumber);
    911 }
    912 
    913 void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
    914         std::list<const SurfaceMap>& surfaceMaps,
    915         const CameraMetadata& request) {
    916     PhysicalCameraSettingsList requestList;
    917     requestList.push_back({std::string(getId().string()), request});
    918     requestsList.push_back(requestList);
    919 
    920     SurfaceMap surfaceMap;
    921     camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
    922     // With no surface list passed in, stream and surface will have 1-to-1
    923     // mapping. So the surface index is 0 for each stream in the surfaceMap.
    924     for (size_t i = 0; i < streams.count; i++) {
    925         surfaceMap[streams.data.i32[i]].push_back(0);
    926     }
    927     surfaceMaps.push_back(surfaceMap);
    928 }
    929 
    930 status_t Camera3Device::submitRequestsHelper(
    931         const List<const PhysicalCameraSettingsList> &requests,
    932         const std::list<const SurfaceMap> &surfaceMaps,
    933         bool repeating,
    934         /*out*/
    935         int64_t *lastFrameNumber) {
    936     ATRACE_CALL();
    937     Mutex::Autolock il(mInterfaceLock);
    938     Mutex::Autolock l(mLock);
    939 
    940     status_t res = checkStatusOkToCaptureLocked();
    941     if (res != OK) {
    942         // error logged by previous call
    943         return res;
    944     }
    945 
    946     RequestList requestList;
    947 
    948     res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
    949             repeating, /*out*/&requestList);
    950     if (res != OK) {
    951         // error logged by previous call
    952         return res;
    953     }
    954 
    955     if (repeating) {
    956         res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
    957     } else {
    958         res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
    959     }
    960 
    961     if (res == OK) {
    962         waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
    963         if (res != OK) {
    964             SET_ERR_L("Can't transition to active in %f seconds!",
    965                     kActiveTimeout/1e9);
    966         }
    967         ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
    968               (*(requestList.begin()))->mResultExtras.requestId);
    969     } else {
    970         CLOGE("Cannot queue request. Impossible.");
    971         return BAD_VALUE;
    972     }
    973 
    974     return res;
    975 }
    976 
    977 hardware::Return<void> Camera3Device::requestStreamBuffers(
    978         const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
    979         requestStreamBuffers_cb _hidl_cb) {
    980     using hardware::camera::device::V3_5::BufferRequestStatus;
    981     using hardware::camera::device::V3_5::StreamBufferRet;
    982     using hardware::camera::device::V3_5::StreamBufferRequestError;
    983 
    984     std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
    985 
    986     hardware::hidl_vec<StreamBufferRet> bufRets;
    987     if (!mUseHalBufManager) {
    988         ALOGE("%s: Camera %s does not support HAL buffer management",
    989                 __FUNCTION__, mId.string());
    990         _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
    991         return hardware::Void();
    992     }
    993 
    994     SortedVector<int32_t> streamIds;
    995     ssize_t sz = streamIds.setCapacity(bufReqs.size());
    996     if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
    997         ALOGE("%s: failed to allocate memory for %zu buffer requests",
    998                 __FUNCTION__, bufReqs.size());
    999         _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
   1000         return hardware::Void();
   1001     }
   1002 
   1003     if (bufReqs.size() > mOutputStreams.size()) {
   1004         ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
   1005                 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
   1006         _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
   1007         return hardware::Void();
   1008     }
   1009 
   1010     // Check for repeated streamId
   1011     for (const auto& bufReq : bufReqs) {
   1012         if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
   1013             ALOGE("%s: Stream %d appear multiple times in buffer requests",
   1014                     __FUNCTION__, bufReq.streamId);
   1015             _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
   1016             return hardware::Void();
   1017         }
   1018         streamIds.add(bufReq.streamId);
   1019     }
   1020 
   1021     if (!mRequestBufferSM.startRequestBuffer()) {
   1022         ALOGE("%s: request buffer disallowed while camera service is configuring",
   1023                 __FUNCTION__);
   1024         _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
   1025         return hardware::Void();
   1026     }
   1027 
   1028     bufRets.resize(bufReqs.size());
   1029 
   1030     bool allReqsSucceeds = true;
   1031     bool oneReqSucceeds = false;
   1032     for (size_t i = 0; i < bufReqs.size(); i++) {
   1033         const auto& bufReq = bufReqs[i];
   1034         auto& bufRet = bufRets[i];
   1035         int32_t streamId = bufReq.streamId;
   1036         sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
   1037         if (outputStream == nullptr) {
   1038             ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
   1039             hardware::hidl_vec<StreamBufferRet> emptyBufRets;
   1040             _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
   1041             mRequestBufferSM.endRequestBuffer();
   1042             return hardware::Void();
   1043         }
   1044 
   1045         if (outputStream->isAbandoned()) {
   1046             bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
   1047             allReqsSucceeds = false;
   1048             continue;
   1049         }
   1050 
   1051         bufRet.streamId = streamId;
   1052         size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
   1053         uint32_t numBuffersRequested = bufReq.numBuffersRequested;
   1054         size_t totalHandout = handOutBufferCount + numBuffersRequested;
   1055         uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
   1056         if (totalHandout > maxBuffers) {
   1057             // Not able to allocate enough buffer. Exit early for this stream
   1058             ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
   1059                     " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
   1060                     numBuffersRequested, maxBuffers);
   1061             bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
   1062             allReqsSucceeds = false;
   1063             continue;
   1064         }
   1065 
   1066         hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
   1067         bool currentReqSucceeds = true;
   1068         std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
   1069         size_t numAllocatedBuffers = 0;
   1070         size_t numPushedInflightBuffers = 0;
   1071         for (size_t b = 0; b < numBuffersRequested; b++) {
   1072             camera3_stream_buffer_t& sb = streamBuffers[b];
   1073             // Since this method can run concurrently with request thread
   1074             // We need to update the wait duration everytime we call getbuffer
   1075             nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
   1076             status_t res = outputStream->getBuffer(&sb, waitDuration);
   1077             if (res != OK) {
   1078                 if (res == NO_INIT || res == DEAD_OBJECT) {
   1079                     ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
   1080                             __FUNCTION__, streamId, strerror(-res), res);
   1081                     bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
   1082                 } else {
   1083                     ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
   1084                             __FUNCTION__, streamId, strerror(-res), res);
   1085                     if (res == TIMED_OUT || res == NO_MEMORY) {
   1086                         bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
   1087                     } else {
   1088                         bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
   1089                     }
   1090                 }
   1091                 currentReqSucceeds = false;
   1092                 break;
   1093             }
   1094             numAllocatedBuffers++;
   1095 
   1096             buffer_handle_t *buffer = sb.buffer;
   1097             auto pair = mInterface->getBufferId(*buffer, streamId);
   1098             bool isNewBuffer = pair.first;
   1099             uint64_t bufferId = pair.second;
   1100             StreamBuffer& hBuf = tmpRetBuffers[b];
   1101 
   1102             hBuf.streamId = streamId;
   1103             hBuf.bufferId = bufferId;
   1104             hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
   1105             hBuf.status = BufferStatus::OK;
   1106             hBuf.releaseFence = nullptr;
   1107 
   1108             native_handle_t *acquireFence = nullptr;
   1109             if (sb.acquire_fence != -1) {
   1110                 acquireFence = native_handle_create(1,0);
   1111                 acquireFence->data[0] = sb.acquire_fence;
   1112             }
   1113             hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
   1114             hBuf.releaseFence = nullptr;
   1115 
   1116             res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
   1117             if (res != OK) {
   1118                 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
   1119                         __FUNCTION__, streamId, strerror(-res), res);
   1120                 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
   1121                 currentReqSucceeds = false;
   1122                 break;
   1123             }
   1124             numPushedInflightBuffers++;
   1125         }
   1126         if (currentReqSucceeds) {
   1127             bufRet.val.buffers(std::move(tmpRetBuffers));
   1128             oneReqSucceeds = true;
   1129         } else {
   1130             allReqsSucceeds = false;
   1131             for (size_t b = 0; b < numPushedInflightBuffers; b++) {
   1132                 StreamBuffer& hBuf = tmpRetBuffers[b];
   1133                 buffer_handle_t* buffer;
   1134                 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
   1135                 if (res != OK) {
   1136                     SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
   1137                             __FUNCTION__, streamId, strerror(-res), res);
   1138                 }
   1139             }
   1140             for (size_t b = 0; b < numAllocatedBuffers; b++) {
   1141                 camera3_stream_buffer_t& sb = streamBuffers[b];
   1142                 sb.acquire_fence = -1;
   1143                 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
   1144             }
   1145             returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
   1146         }
   1147     }
   1148 
   1149     _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
   1150             oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
   1151                              BufferRequestStatus::FAILED_UNKNOWN,
   1152             bufRets);
   1153     mRequestBufferSM.endRequestBuffer();
   1154     return hardware::Void();
   1155 }
   1156 
   1157 hardware::Return<void> Camera3Device::returnStreamBuffers(
   1158         const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
   1159     if (!mUseHalBufManager) {
   1160         ALOGE("%s: Camera %s does not support HAL buffer managerment",
   1161                 __FUNCTION__, mId.string());
   1162         return hardware::Void();
   1163     }
   1164 
   1165     for (const auto& buf : buffers) {
   1166         if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
   1167             ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
   1168             continue;
   1169         }
   1170 
   1171         buffer_handle_t* buffer;
   1172         status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
   1173 
   1174         if (res != OK) {
   1175             ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
   1176                     __FUNCTION__, buf.bufferId, buf.streamId);
   1177             continue;
   1178         }
   1179 
   1180         camera3_stream_buffer_t streamBuffer;
   1181         streamBuffer.buffer = buffer;
   1182         streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
   1183         streamBuffer.acquire_fence = -1;
   1184         streamBuffer.release_fence = -1;
   1185 
   1186         if (buf.releaseFence == nullptr) {
   1187             streamBuffer.release_fence = -1;
   1188         } else if (buf.releaseFence->numFds == 1) {
   1189             streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
   1190         } else {
   1191             ALOGE("%s: Invalid release fence, fd count is %d, not 1",
   1192                     __FUNCTION__, buf.releaseFence->numFds);
   1193             continue;
   1194         }
   1195 
   1196         sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
   1197         if (stream == nullptr) {
   1198             ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
   1199             continue;
   1200         }
   1201         streamBuffer.stream = stream->asHalStream();
   1202         returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
   1203     }
   1204     return hardware::Void();
   1205 }
   1206 
   1207 hardware::Return<void> Camera3Device::processCaptureResult_3_4(
   1208         const hardware::hidl_vec<
   1209                 hardware::camera::device::V3_4::CaptureResult>& results) {
   1210     // Ideally we should grab mLock, but that can lead to deadlock, and
   1211     // it's not super important to get up to date value of mStatus for this
   1212     // warning print, hence skipping the lock here
   1213     if (mStatus == STATUS_ERROR) {
   1214         // Per API contract, HAL should act as closed after device error
   1215         // But mStatus can be set to error by framework as well, so just log
   1216         // a warning here.
   1217         ALOGW("%s: received capture result in error state.", __FUNCTION__);
   1218     }
   1219 
   1220     if (mProcessCaptureResultLock.tryLock() != OK) {
   1221         // This should never happen; it indicates a wrong client implementation
   1222         // that doesn't follow the contract. But, we can be tolerant here.
   1223         ALOGE("%s: callback overlapped! waiting 1s...",
   1224                 __FUNCTION__);
   1225         if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
   1226             ALOGE("%s: cannot acquire lock in 1s, dropping results",
   1227                     __FUNCTION__);
   1228             // really don't know what to do, so bail out.
   1229             return hardware::Void();
   1230         }
   1231     }
   1232     for (const auto& result : results) {
   1233         processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
   1234     }
   1235     mProcessCaptureResultLock.unlock();
   1236     return hardware::Void();
   1237 }
   1238 
   1239 // Only one processCaptureResult should be called at a time, so
   1240 // the locks won't block. The locks are present here simply to enforce this.
   1241 hardware::Return<void> Camera3Device::processCaptureResult(
   1242         const hardware::hidl_vec<
   1243                 hardware::camera::device::V3_2::CaptureResult>& results) {
   1244     hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
   1245 
   1246     // Ideally we should grab mLock, but that can lead to deadlock, and
   1247     // it's not super important to get up to date value of mStatus for this
   1248     // warning print, hence skipping the lock here
   1249     if (mStatus == STATUS_ERROR) {
   1250         // Per API contract, HAL should act as closed after device error
   1251         // But mStatus can be set to error by framework as well, so just log
   1252         // a warning here.
   1253         ALOGW("%s: received capture result in error state.", __FUNCTION__);
   1254     }
   1255 
   1256     if (mProcessCaptureResultLock.tryLock() != OK) {
   1257         // This should never happen; it indicates a wrong client implementation
   1258         // that doesn't follow the contract. But, we can be tolerant here.
   1259         ALOGE("%s: callback overlapped! waiting 1s...",
   1260                 __FUNCTION__);
   1261         if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
   1262             ALOGE("%s: cannot acquire lock in 1s, dropping results",
   1263                     __FUNCTION__);
   1264             // really don't know what to do, so bail out.
   1265             return hardware::Void();
   1266         }
   1267     }
   1268     for (const auto& result : results) {
   1269         processOneCaptureResultLocked(result, noPhysMetadata);
   1270     }
   1271     mProcessCaptureResultLock.unlock();
   1272     return hardware::Void();
   1273 }
   1274 
   1275 status_t Camera3Device::readOneCameraMetadataLocked(
   1276         uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
   1277         const hardware::camera::device::V3_2::CameraMetadata& result) {
   1278     if (fmqResultSize > 0) {
   1279         resultMetadata.resize(fmqResultSize);
   1280         if (mResultMetadataQueue == nullptr) {
   1281             return NO_MEMORY; // logged in initialize()
   1282         }
   1283         if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
   1284             ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
   1285                     __FUNCTION__, fmqResultSize);
   1286             return INVALID_OPERATION;
   1287         }
   1288     } else {
   1289         resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
   1290                 result.size());
   1291     }
   1292 
   1293     if (resultMetadata.size() != 0) {
   1294         status_t res;
   1295         const camera_metadata_t* metadata =
   1296                 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
   1297         size_t expected_metadata_size = resultMetadata.size();
   1298         if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
   1299             ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
   1300                     __FUNCTION__, strerror(-res), res);
   1301             return INVALID_OPERATION;
   1302         }
   1303     }
   1304 
   1305     return OK;
   1306 }
   1307 
   1308 void Camera3Device::processOneCaptureResultLocked(
   1309         const hardware::camera::device::V3_2::CaptureResult& result,
   1310         const hardware::hidl_vec<
   1311                 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
   1312     camera3_capture_result r;
   1313     status_t res;
   1314     r.frame_number = result.frameNumber;
   1315 
   1316     // Read and validate the result metadata.
   1317     hardware::camera::device::V3_2::CameraMetadata resultMetadata;
   1318     res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
   1319     if (res != OK) {
   1320         ALOGE("%s: Frame %d: Failed to read capture result metadata",
   1321                 __FUNCTION__, result.frameNumber);
   1322         return;
   1323     }
   1324     r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
   1325 
   1326     // Read and validate physical camera metadata
   1327     size_t physResultCount = physicalCameraMetadata.size();
   1328     std::vector<const char*> physCamIds(physResultCount);
   1329     std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
   1330     std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
   1331     physResultMetadata.resize(physResultCount);
   1332     for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
   1333         res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
   1334                 physResultMetadata[i], physicalCameraMetadata[i].metadata);
   1335         if (res != OK) {
   1336             ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
   1337                     __FUNCTION__, result.frameNumber,
   1338                     physicalCameraMetadata[i].physicalCameraId.c_str());
   1339             return;
   1340         }
   1341         physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
   1342         phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
   1343                 physResultMetadata[i].data());
   1344     }
   1345     r.num_physcam_metadata = physResultCount;
   1346     r.physcam_ids = physCamIds.data();
   1347     r.physcam_metadata = phyCamMetadatas.data();
   1348 
   1349     std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
   1350     std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
   1351     for (size_t i = 0; i < result.outputBuffers.size(); i++) {
   1352         auto& bDst = outputBuffers[i];
   1353         const StreamBuffer &bSrc = result.outputBuffers[i];
   1354 
   1355         sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
   1356         if (stream == nullptr) {
   1357             ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
   1358                     __FUNCTION__, result.frameNumber, i, bSrc.streamId);
   1359             return;
   1360         }
   1361         bDst.stream = stream->asHalStream();
   1362 
   1363         bool noBufferReturned = false;
   1364         buffer_handle_t *buffer = nullptr;
   1365         if (mUseHalBufManager) {
   1366             // This is suspicious most of the time but can be correct during flush where HAL
   1367             // has to return capture result before a buffer is requested
   1368             if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
   1369                 if (bSrc.status == BufferStatus::OK) {
   1370                     ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
   1371                             __FUNCTION__, result.frameNumber, i, bSrc.streamId);
   1372                     // Still proceeds so other buffers can be returned
   1373                 }
   1374                 noBufferReturned = true;
   1375             }
   1376             if (noBufferReturned) {
   1377                 res = OK;
   1378             } else {
   1379                 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
   1380             }
   1381         } else {
   1382             res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
   1383         }
   1384 
   1385         if (res != OK) {
   1386             ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
   1387                     __FUNCTION__, result.frameNumber, i, bSrc.streamId);
   1388             return;
   1389         }
   1390 
   1391         bDst.buffer = buffer;
   1392         bDst.status = mapHidlBufferStatus(bSrc.status);
   1393         bDst.acquire_fence = -1;
   1394         if (bSrc.releaseFence == nullptr) {
   1395             bDst.release_fence = -1;
   1396         } else if (bSrc.releaseFence->numFds == 1) {
   1397             if (noBufferReturned) {
   1398                 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
   1399             }
   1400             bDst.release_fence = dup(bSrc.releaseFence->data[0]);
   1401         } else {
   1402             ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
   1403                     __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
   1404             return;
   1405         }
   1406     }
   1407     r.num_output_buffers = outputBuffers.size();
   1408     r.output_buffers = outputBuffers.data();
   1409 
   1410     camera3_stream_buffer_t inputBuffer;
   1411     if (result.inputBuffer.streamId == -1) {
   1412         r.input_buffer = nullptr;
   1413     } else {
   1414         if (mInputStream->getId() != result.inputBuffer.streamId) {
   1415             ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
   1416                     result.frameNumber, result.inputBuffer.streamId);
   1417             return;
   1418         }
   1419         inputBuffer.stream = mInputStream->asHalStream();
   1420         buffer_handle_t *buffer;
   1421         res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
   1422                 &buffer);
   1423         if (res != OK) {
   1424             ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
   1425                     __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
   1426             return;
   1427         }
   1428         inputBuffer.buffer = buffer;
   1429         inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
   1430         inputBuffer.acquire_fence = -1;
   1431         if (result.inputBuffer.releaseFence == nullptr) {
   1432             inputBuffer.release_fence = -1;
   1433         } else if (result.inputBuffer.releaseFence->numFds == 1) {
   1434             inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
   1435         } else {
   1436             ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
   1437                     __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
   1438             return;
   1439         }
   1440         r.input_buffer = &inputBuffer;
   1441     }
   1442 
   1443     r.partial_result = result.partialResult;
   1444 
   1445     processCaptureResult(&r);
   1446 }
   1447 
   1448 hardware::Return<void> Camera3Device::notify(
   1449         const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
   1450     // Ideally we should grab mLock, but that can lead to deadlock, and
   1451     // it's not super important to get up to date value of mStatus for this
   1452     // warning print, hence skipping the lock here
   1453     if (mStatus == STATUS_ERROR) {
   1454         // Per API contract, HAL should act as closed after device error
   1455         // But mStatus can be set to error by framework as well, so just log
   1456         // a warning here.
   1457         ALOGW("%s: received notify message in error state.", __FUNCTION__);
   1458     }
   1459 
   1460     for (const auto& msg : msgs) {
   1461         notify(msg);
   1462     }
   1463     return hardware::Void();
   1464 }
   1465 
   1466 void Camera3Device::notify(
   1467         const hardware::camera::device::V3_2::NotifyMsg& msg) {
   1468 
   1469     camera3_notify_msg m;
   1470     switch (msg.type) {
   1471         case MsgType::ERROR:
   1472             m.type = CAMERA3_MSG_ERROR;
   1473             m.message.error.frame_number = msg.msg.error.frameNumber;
   1474             if (msg.msg.error.errorStreamId >= 0) {
   1475                 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
   1476                 if (stream == nullptr) {
   1477                     ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
   1478                             m.message.error.frame_number, msg.msg.error.errorStreamId);
   1479                     return;
   1480                 }
   1481                 m.message.error.error_stream = stream->asHalStream();
   1482             } else {
   1483                 m.message.error.error_stream = nullptr;
   1484             }
   1485             switch (msg.msg.error.errorCode) {
   1486                 case ErrorCode::ERROR_DEVICE:
   1487                     m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
   1488                     break;
   1489                 case ErrorCode::ERROR_REQUEST:
   1490                     m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
   1491                     break;
   1492                 case ErrorCode::ERROR_RESULT:
   1493                     m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
   1494                     break;
   1495                 case ErrorCode::ERROR_BUFFER:
   1496                     m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
   1497                     break;
   1498             }
   1499             break;
   1500         case MsgType::SHUTTER:
   1501             m.type = CAMERA3_MSG_SHUTTER;
   1502             m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
   1503             m.message.shutter.timestamp = msg.msg.shutter.timestamp;
   1504             break;
   1505     }
   1506     notify(&m);
   1507 }
   1508 
   1509 status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
   1510                                     const std::list<const SurfaceMap> &surfaceMaps,
   1511                                     int64_t *lastFrameNumber) {
   1512     ATRACE_CALL();
   1513 
   1514     return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
   1515 }
   1516 
   1517 status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
   1518                                             int64_t* /*lastFrameNumber*/) {
   1519     ATRACE_CALL();
   1520 
   1521     List<const PhysicalCameraSettingsList> requestsList;
   1522     std::list<const SurfaceMap> surfaceMaps;
   1523     convertToRequestList(requestsList, surfaceMaps, request);
   1524 
   1525     return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
   1526                                    /*lastFrameNumber*/NULL);
   1527 }
   1528 
   1529 status_t Camera3Device::setStreamingRequestList(
   1530         const List<const PhysicalCameraSettingsList> &requestsList,
   1531         const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
   1532     ATRACE_CALL();
   1533 
   1534     return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
   1535 }
   1536 
   1537 sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
   1538         const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
   1539     status_t res;
   1540 
   1541     if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
   1542         // This point should only be reached via API1 (API2 must explicitly call configureStreams)
   1543         // so unilaterally select normal operating mode.
   1544         res = filterParamsAndConfigureLocked(request.begin()->metadata,
   1545                 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
   1546         // Stream configuration failed. Client might try other configuraitons.
   1547         if (res != OK) {
   1548             CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
   1549             return NULL;
   1550         } else if (mStatus == STATUS_UNCONFIGURED) {
   1551             // Stream configuration successfully configure to empty stream configuration.
   1552             CLOGE("No streams configured");
   1553             return NULL;
   1554         }
   1555     }
   1556 
   1557     sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
   1558     return newRequest;
   1559 }
   1560 
   1561 status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
   1562     ATRACE_CALL();
   1563     Mutex::Autolock il(mInterfaceLock);
   1564     Mutex::Autolock l(mLock);
   1565 
   1566     switch (mStatus) {
   1567         case STATUS_ERROR:
   1568             CLOGE("Device has encountered a serious error");
   1569             return INVALID_OPERATION;
   1570         case STATUS_UNINITIALIZED:
   1571             CLOGE("Device not initialized");
   1572             return INVALID_OPERATION;
   1573         case STATUS_UNCONFIGURED:
   1574         case STATUS_CONFIGURED:
   1575         case STATUS_ACTIVE:
   1576             // OK
   1577             break;
   1578         default:
   1579             SET_ERR_L("Unexpected status: %d", mStatus);
   1580             return INVALID_OPERATION;
   1581     }
   1582     ALOGV("Camera %s: Clearing repeating request", mId.string());
   1583 
   1584     return mRequestThread->clearRepeatingRequests(lastFrameNumber);
   1585 }
   1586 
   1587 status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
   1588     ATRACE_CALL();
   1589     Mutex::Autolock il(mInterfaceLock);
   1590 
   1591     return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
   1592 }
   1593 
   1594 status_t Camera3Device::createInputStream(
   1595         uint32_t width, uint32_t height, int format, int *id) {
   1596     ATRACE_CALL();
   1597     Mutex::Autolock il(mInterfaceLock);
   1598     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
   1599     Mutex::Autolock l(mLock);
   1600     ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
   1601             mId.string(), mNextStreamId, width, height, format);
   1602 
   1603     status_t res;
   1604     bool wasActive = false;
   1605 
   1606     switch (mStatus) {
   1607         case STATUS_ERROR:
   1608             ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
   1609             return INVALID_OPERATION;
   1610         case STATUS_UNINITIALIZED:
   1611             ALOGE("%s: Device not initialized", __FUNCTION__);
   1612             return INVALID_OPERATION;
   1613         case STATUS_UNCONFIGURED:
   1614         case STATUS_CONFIGURED:
   1615             // OK
   1616             break;
   1617         case STATUS_ACTIVE:
   1618             ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
   1619             res = internalPauseAndWaitLocked(maxExpectedDuration);
   1620             if (res != OK) {
   1621                 SET_ERR_L("Can't pause captures to reconfigure streams!");
   1622                 return res;
   1623             }
   1624             wasActive = true;
   1625             break;
   1626         default:
   1627             SET_ERR_L("%s: Unexpected status: %d", mStatus);
   1628             return INVALID_OPERATION;
   1629     }
   1630     assert(mStatus != STATUS_ACTIVE);
   1631 
   1632     if (mInputStream != 0) {
   1633         ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
   1634         return INVALID_OPERATION;
   1635     }
   1636 
   1637     sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
   1638                 width, height, format);
   1639     newStream->setStatusTracker(mStatusTracker);
   1640 
   1641     mInputStream = newStream;
   1642 
   1643     *id = mNextStreamId++;
   1644 
   1645     // Continue captures if active at start
   1646     if (wasActive) {
   1647         ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
   1648         // Reuse current operating mode and session parameters for new stream config
   1649         res = configureStreamsLocked(mOperatingMode, mSessionParams);
   1650         if (res != OK) {
   1651             ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
   1652                     __FUNCTION__, mNextStreamId, strerror(-res), res);
   1653             return res;
   1654         }
   1655         internalResumeLocked();
   1656     }
   1657 
   1658     ALOGV("Camera %s: Created input stream", mId.string());
   1659     return OK;
   1660 }
   1661 
   1662 status_t Camera3Device::StreamSet::add(
   1663         int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
   1664     if (stream == nullptr) {
   1665         ALOGE("%s: cannot add null stream", __FUNCTION__);
   1666         return BAD_VALUE;
   1667     }
   1668     std::lock_guard<std::mutex> lock(mLock);
   1669     return mData.add(streamId, stream);
   1670 }
   1671 
   1672 ssize_t Camera3Device::StreamSet::remove(int streamId) {
   1673     std::lock_guard<std::mutex> lock(mLock);
   1674     return mData.removeItem(streamId);
   1675 }
   1676 
   1677 sp<camera3::Camera3OutputStreamInterface>
   1678 Camera3Device::StreamSet::get(int streamId) {
   1679     std::lock_guard<std::mutex> lock(mLock);
   1680     ssize_t idx = mData.indexOfKey(streamId);
   1681     if (idx == NAME_NOT_FOUND) {
   1682         return nullptr;
   1683     }
   1684     return mData.editValueAt(idx);
   1685 }
   1686 
   1687 sp<camera3::Camera3OutputStreamInterface>
   1688 Camera3Device::StreamSet::operator[] (size_t index) {
   1689     std::lock_guard<std::mutex> lock(mLock);
   1690     return mData.editValueAt(index);
   1691 }
   1692 
   1693 size_t Camera3Device::StreamSet::size() const {
   1694     std::lock_guard<std::mutex> lock(mLock);
   1695     return mData.size();
   1696 }
   1697 
   1698 void Camera3Device::StreamSet::clear() {
   1699     std::lock_guard<std::mutex> lock(mLock);
   1700     return mData.clear();
   1701 }
   1702 
   1703 std::vector<int> Camera3Device::StreamSet::getStreamIds() {
   1704     std::lock_guard<std::mutex> lock(mLock);
   1705     std::vector<int> streamIds(mData.size());
   1706     for (size_t i = 0; i < mData.size(); i++) {
   1707         streamIds[i] = mData.keyAt(i);
   1708     }
   1709     return streamIds;
   1710 }
   1711 
   1712 status_t Camera3Device::createStream(sp<Surface> consumer,
   1713             uint32_t width, uint32_t height, int format,
   1714             android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
   1715             const String8& physicalCameraId,
   1716             std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
   1717     ATRACE_CALL();
   1718 
   1719     if (consumer == nullptr) {
   1720         ALOGE("%s: consumer must not be null", __FUNCTION__);
   1721         return BAD_VALUE;
   1722     }
   1723 
   1724     std::vector<sp<Surface>> consumers;
   1725     consumers.push_back(consumer);
   1726 
   1727     return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
   1728             format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
   1729             isShared, consumerUsage);
   1730 }
   1731 
   1732 status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
   1733         bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
   1734         android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
   1735         const String8& physicalCameraId,
   1736         std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
   1737     ATRACE_CALL();
   1738 
   1739     Mutex::Autolock il(mInterfaceLock);
   1740     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
   1741     Mutex::Autolock l(mLock);
   1742     ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
   1743             " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
   1744             mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
   1745             physicalCameraId.string());
   1746 
   1747     status_t res;
   1748     bool wasActive = false;
   1749 
   1750     switch (mStatus) {
   1751         case STATUS_ERROR:
   1752             CLOGE("Device has encountered a serious error");
   1753             return INVALID_OPERATION;
   1754         case STATUS_UNINITIALIZED:
   1755             CLOGE("Device not initialized");
   1756             return INVALID_OPERATION;
   1757         case STATUS_UNCONFIGURED:
   1758         case STATUS_CONFIGURED:
   1759             // OK
   1760             break;
   1761         case STATUS_ACTIVE:
   1762             ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
   1763             res = internalPauseAndWaitLocked(maxExpectedDuration);
   1764             if (res != OK) {
   1765                 SET_ERR_L("Can't pause captures to reconfigure streams!");
   1766                 return res;
   1767             }
   1768             wasActive = true;
   1769             break;
   1770         default:
   1771             SET_ERR_L("Unexpected status: %d", mStatus);
   1772             return INVALID_OPERATION;
   1773     }
   1774     assert(mStatus != STATUS_ACTIVE);
   1775 
   1776     sp<Camera3OutputStream> newStream;
   1777 
   1778     if (consumers.size() == 0 && !hasDeferredConsumer) {
   1779         ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
   1780         return BAD_VALUE;
   1781     }
   1782 
   1783     if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
   1784         ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
   1785         return BAD_VALUE;
   1786     }
   1787 
   1788     if (format == HAL_PIXEL_FORMAT_BLOB) {
   1789         ssize_t blobBufferSize;
   1790         if (dataSpace == HAL_DATASPACE_DEPTH) {
   1791             blobBufferSize = getPointCloudBufferSize();
   1792             if (blobBufferSize <= 0) {
   1793                 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
   1794                 return BAD_VALUE;
   1795             }
   1796         } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
   1797             blobBufferSize = width * height;
   1798         } else {
   1799             blobBufferSize = getJpegBufferSize(width, height);
   1800             if (blobBufferSize <= 0) {
   1801                 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
   1802                 return BAD_VALUE;
   1803             }
   1804         }
   1805         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
   1806                 width, height, blobBufferSize, format, dataSpace, rotation,
   1807                 mTimestampOffset, physicalCameraId, streamSetId);
   1808     } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
   1809         ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
   1810         if (rawOpaqueBufferSize <= 0) {
   1811             SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
   1812             return BAD_VALUE;
   1813         }
   1814         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
   1815                 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
   1816                 mTimestampOffset, physicalCameraId, streamSetId);
   1817     } else if (isShared) {
   1818         newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
   1819                 width, height, format, consumerUsage, dataSpace, rotation,
   1820                 mTimestampOffset, physicalCameraId, streamSetId,
   1821                 mUseHalBufManager);
   1822     } else if (consumers.size() == 0 && hasDeferredConsumer) {
   1823         newStream = new Camera3OutputStream(mNextStreamId,
   1824                 width, height, format, consumerUsage, dataSpace, rotation,
   1825                 mTimestampOffset, physicalCameraId, streamSetId);
   1826     } else {
   1827         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
   1828                 width, height, format, dataSpace, rotation,
   1829                 mTimestampOffset, physicalCameraId, streamSetId);
   1830     }
   1831 
   1832     size_t consumerCount = consumers.size();
   1833     for (size_t i = 0; i < consumerCount; i++) {
   1834         int id = newStream->getSurfaceId(consumers[i]);
   1835         if (id < 0) {
   1836             SET_ERR_L("Invalid surface id");
   1837             return BAD_VALUE;
   1838         }
   1839         if (surfaceIds != nullptr) {
   1840             surfaceIds->push_back(id);
   1841         }
   1842     }
   1843 
   1844     newStream->setStatusTracker(mStatusTracker);
   1845 
   1846     newStream->setBufferManager(mBufferManager);
   1847 
   1848     res = mOutputStreams.add(mNextStreamId, newStream);
   1849     if (res < 0) {
   1850         SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
   1851         return res;
   1852     }
   1853 
   1854     *id = mNextStreamId++;
   1855     mNeedConfig = true;
   1856 
   1857     // Continue captures if active at start
   1858     if (wasActive) {
   1859         ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
   1860         // Reuse current operating mode and session parameters for new stream config
   1861         res = configureStreamsLocked(mOperatingMode, mSessionParams);
   1862         if (res != OK) {
   1863             CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
   1864                     mNextStreamId, strerror(-res), res);
   1865             return res;
   1866         }
   1867         internalResumeLocked();
   1868     }
   1869     ALOGV("Camera %s: Created new stream", mId.string());
   1870     return OK;
   1871 }
   1872 
   1873 status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
   1874     ATRACE_CALL();
   1875     if (nullptr == streamInfo) {
   1876         return BAD_VALUE;
   1877     }
   1878     Mutex::Autolock il(mInterfaceLock);
   1879     Mutex::Autolock l(mLock);
   1880 
   1881     switch (mStatus) {
   1882         case STATUS_ERROR:
   1883             CLOGE("Device has encountered a serious error");
   1884             return INVALID_OPERATION;
   1885         case STATUS_UNINITIALIZED:
   1886             CLOGE("Device not initialized!");
   1887             return INVALID_OPERATION;
   1888         case STATUS_UNCONFIGURED:
   1889         case STATUS_CONFIGURED:
   1890         case STATUS_ACTIVE:
   1891             // OK
   1892             break;
   1893         default:
   1894             SET_ERR_L("Unexpected status: %d", mStatus);
   1895             return INVALID_OPERATION;
   1896     }
   1897 
   1898     sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
   1899     if (stream == nullptr) {
   1900         CLOGE("Stream %d is unknown", id);
   1901         return BAD_VALUE;
   1902     }
   1903 
   1904     streamInfo->width  = stream->getWidth();
   1905     streamInfo->height = stream->getHeight();
   1906     streamInfo->format = stream->getFormat();
   1907     streamInfo->dataSpace = stream->getDataSpace();
   1908     streamInfo->formatOverridden = stream->isFormatOverridden();
   1909     streamInfo->originalFormat = stream->getOriginalFormat();
   1910     streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
   1911     streamInfo->originalDataSpace = stream->getOriginalDataSpace();
   1912     return OK;
   1913 }
   1914 
   1915 status_t Camera3Device::setStreamTransform(int id,
   1916         int transform) {
   1917     ATRACE_CALL();
   1918     Mutex::Autolock il(mInterfaceLock);
   1919     Mutex::Autolock l(mLock);
   1920 
   1921     switch (mStatus) {
   1922         case STATUS_ERROR:
   1923             CLOGE("Device has encountered a serious error");
   1924             return INVALID_OPERATION;
   1925         case STATUS_UNINITIALIZED:
   1926             CLOGE("Device not initialized");
   1927             return INVALID_OPERATION;
   1928         case STATUS_UNCONFIGURED:
   1929         case STATUS_CONFIGURED:
   1930         case STATUS_ACTIVE:
   1931             // OK
   1932             break;
   1933         default:
   1934             SET_ERR_L("Unexpected status: %d", mStatus);
   1935             return INVALID_OPERATION;
   1936     }
   1937 
   1938     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
   1939     if (stream == nullptr) {
   1940         CLOGE("Stream %d does not exist", id);
   1941         return BAD_VALUE;
   1942     }
   1943     return stream->setTransform(transform);
   1944 }
   1945 
   1946 status_t Camera3Device::deleteStream(int id) {
   1947     ATRACE_CALL();
   1948     Mutex::Autolock il(mInterfaceLock);
   1949     Mutex::Autolock l(mLock);
   1950     status_t res;
   1951 
   1952     ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
   1953 
   1954     // CameraDevice semantics require device to already be idle before
   1955     // deleteStream is called, unlike for createStream.
   1956     if (mStatus == STATUS_ACTIVE) {
   1957         ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
   1958         return -EBUSY;
   1959     }
   1960 
   1961     if (mStatus == STATUS_ERROR) {
   1962         ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
   1963                 __FUNCTION__, mId.string());
   1964         return -EBUSY;
   1965     }
   1966 
   1967     sp<Camera3StreamInterface> deletedStream;
   1968     sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
   1969     if (mInputStream != NULL && id == mInputStream->getId()) {
   1970         deletedStream = mInputStream;
   1971         mInputStream.clear();
   1972     } else {
   1973         if (stream == nullptr) {
   1974             CLOGE("Stream %d does not exist", id);
   1975             return BAD_VALUE;
   1976         }
   1977     }
   1978 
   1979     // Delete output stream or the output part of a bi-directional stream.
   1980     if (stream != nullptr) {
   1981         deletedStream = stream;
   1982         mOutputStreams.remove(id);
   1983     }
   1984 
   1985     // Free up the stream endpoint so that it can be used by some other stream
   1986     res = deletedStream->disconnect();
   1987     if (res != OK) {
   1988         SET_ERR_L("Can't disconnect deleted stream %d", id);
   1989         // fall through since we want to still list the stream as deleted.
   1990     }
   1991     mDeletedStreams.add(deletedStream);
   1992     mNeedConfig = true;
   1993 
   1994     return res;
   1995 }
   1996 
   1997 status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
   1998     ATRACE_CALL();
   1999     ALOGV("%s: E", __FUNCTION__);
   2000 
   2001     Mutex::Autolock il(mInterfaceLock);
   2002     Mutex::Autolock l(mLock);
   2003 
   2004     // In case the client doesn't include any session parameter, try a
   2005     // speculative configuration using the values from the last cached
   2006     // default request.
   2007     if (sessionParams.isEmpty() &&
   2008             ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
   2009             (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
   2010         ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
   2011                 mLastTemplateId);
   2012         return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
   2013                 operatingMode);
   2014     }
   2015 
   2016     return filterParamsAndConfigureLocked(sessionParams, operatingMode);
   2017 }
   2018 
   2019 status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
   2020         int operatingMode) {
   2021     //Filter out any incoming session parameters
   2022     const CameraMetadata params(sessionParams);
   2023     camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
   2024             ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
   2025     CameraMetadata filteredParams(availableSessionKeys.count);
   2026     camera_metadata_t *meta = const_cast<camera_metadata_t *>(
   2027             filteredParams.getAndLock());
   2028     set_camera_metadata_vendor_id(meta, mVendorTagId);
   2029     filteredParams.unlock(meta);
   2030     if (availableSessionKeys.count > 0) {
   2031         for (size_t i = 0; i < availableSessionKeys.count; i++) {
   2032             camera_metadata_ro_entry entry = params.find(
   2033                     availableSessionKeys.data.i32[i]);
   2034             if (entry.count > 0) {
   2035                 filteredParams.update(entry);
   2036             }
   2037         }
   2038     }
   2039 
   2040     return configureStreamsLocked(operatingMode, filteredParams);
   2041 }
   2042 
   2043 status_t Camera3Device::getInputBufferProducer(
   2044         sp<IGraphicBufferProducer> *producer) {
   2045     ATRACE_CALL();
   2046     Mutex::Autolock il(mInterfaceLock);
   2047     Mutex::Autolock l(mLock);
   2048 
   2049     if (producer == NULL) {
   2050         return BAD_VALUE;
   2051     } else if (mInputStream == NULL) {
   2052         return INVALID_OPERATION;
   2053     }
   2054 
   2055     return mInputStream->getInputBufferProducer(producer);
   2056 }
   2057 
   2058 status_t Camera3Device::createDefaultRequest(int templateId,
   2059         CameraMetadata *request) {
   2060     ATRACE_CALL();
   2061     ALOGV("%s: for template %d", __FUNCTION__, templateId);
   2062 
   2063     if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
   2064         android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
   2065                 CameraThreadState::getCallingUid(), nullptr, 0);
   2066         return BAD_VALUE;
   2067     }
   2068 
   2069     Mutex::Autolock il(mInterfaceLock);
   2070 
   2071     {
   2072         Mutex::Autolock l(mLock);
   2073         switch (mStatus) {
   2074             case STATUS_ERROR:
   2075                 CLOGE("Device has encountered a serious error");
   2076                 return INVALID_OPERATION;
   2077             case STATUS_UNINITIALIZED:
   2078                 CLOGE("Device is not initialized!");
   2079                 return INVALID_OPERATION;
   2080             case STATUS_UNCONFIGURED:
   2081             case STATUS_CONFIGURED:
   2082             case STATUS_ACTIVE:
   2083                 // OK
   2084                 break;
   2085             default:
   2086                 SET_ERR_L("Unexpected status: %d", mStatus);
   2087                 return INVALID_OPERATION;
   2088         }
   2089 
   2090         if (!mRequestTemplateCache[templateId].isEmpty()) {
   2091             *request = mRequestTemplateCache[templateId];
   2092             mLastTemplateId = templateId;
   2093             return OK;
   2094         }
   2095     }
   2096 
   2097     camera_metadata_t *rawRequest;
   2098     status_t res = mInterface->constructDefaultRequestSettings(
   2099             (camera3_request_template_t) templateId, &rawRequest);
   2100 
   2101     {
   2102         Mutex::Autolock l(mLock);
   2103         if (res == BAD_VALUE) {
   2104             ALOGI("%s: template %d is not supported on this camera device",
   2105                   __FUNCTION__, templateId);
   2106             return res;
   2107         } else if (res != OK) {
   2108             CLOGE("Unable to construct request template %d: %s (%d)",
   2109                     templateId, strerror(-res), res);
   2110             return res;
   2111         }
   2112 
   2113         set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
   2114         mRequestTemplateCache[templateId].acquire(rawRequest);
   2115 
   2116         *request = mRequestTemplateCache[templateId];
   2117         mLastTemplateId = templateId;
   2118     }
   2119     return OK;
   2120 }
   2121 
   2122 status_t Camera3Device::waitUntilDrained() {
   2123     ATRACE_CALL();
   2124     Mutex::Autolock il(mInterfaceLock);
   2125     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
   2126     Mutex::Autolock l(mLock);
   2127 
   2128     return waitUntilDrainedLocked(maxExpectedDuration);
   2129 }
   2130 
   2131 status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
   2132     switch (mStatus) {
   2133         case STATUS_UNINITIALIZED:
   2134         case STATUS_UNCONFIGURED:
   2135             ALOGV("%s: Already idle", __FUNCTION__);
   2136             return OK;
   2137         case STATUS_CONFIGURED:
   2138             // To avoid race conditions, check with tracker to be sure
   2139         case STATUS_ERROR:
   2140         case STATUS_ACTIVE:
   2141             // Need to verify shut down
   2142             break;
   2143         default:
   2144             SET_ERR_L("Unexpected status: %d",mStatus);
   2145             return INVALID_OPERATION;
   2146     }
   2147     ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
   2148             maxExpectedDuration);
   2149     status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
   2150     if (res != OK) {
   2151         SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
   2152                 res);
   2153     }
   2154     return res;
   2155 }
   2156 
   2157 
   2158 void Camera3Device::internalUpdateStatusLocked(Status status) {
   2159     mStatus = status;
   2160     mRecentStatusUpdates.add(mStatus);
   2161     mStatusChanged.broadcast();
   2162 }
   2163 
   2164 void Camera3Device::pauseStateNotify(bool enable) {
   2165     Mutex::Autolock il(mInterfaceLock);
   2166     Mutex::Autolock l(mLock);
   2167 
   2168     mPauseStateNotify = enable;
   2169 }
   2170 
   2171 // Pause to reconfigure
   2172 status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
   2173     if (mRequestThread.get() != nullptr) {
   2174         mRequestThread->setPaused(true);
   2175     } else {
   2176         return NO_INIT;
   2177     }
   2178 
   2179     ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
   2180           maxExpectedDuration);
   2181     status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
   2182     if (res != OK) {
   2183         SET_ERR_L("Can't idle device in %f seconds!",
   2184                 maxExpectedDuration/1e9);
   2185     }
   2186 
   2187     return res;
   2188 }
   2189 
   2190 // Resume after internalPauseAndWaitLocked
   2191 status_t Camera3Device::internalResumeLocked() {
   2192     status_t res;
   2193 
   2194     mRequestThread->setPaused(false);
   2195 
   2196     ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
   2197             kActiveTimeout);
   2198     res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
   2199     if (res != OK) {
   2200         SET_ERR_L("Can't transition to active in %f seconds!",
   2201                 kActiveTimeout/1e9);
   2202     }
   2203     mPauseStateNotify = false;
   2204     return OK;
   2205 }
   2206 
   2207 status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
   2208     status_t res = OK;
   2209 
   2210     size_t startIndex = 0;
   2211     if (mStatusWaiters == 0) {
   2212         // Clear the list of recent statuses if there are no existing threads waiting on updates to
   2213         // this status list
   2214         mRecentStatusUpdates.clear();
   2215     } else {
   2216         // If other threads are waiting on updates to this status list, set the position of the
   2217         // first element that this list will check rather than clearing the list.
   2218         startIndex = mRecentStatusUpdates.size();
   2219     }
   2220 
   2221     mStatusWaiters++;
   2222 
   2223     if (!active && mUseHalBufManager) {
   2224         auto streamIds = mOutputStreams.getStreamIds();
   2225         if (mStatus == STATUS_ACTIVE) {
   2226             mRequestThread->signalPipelineDrain(streamIds);
   2227         }
   2228         mRequestBufferSM.onWaitUntilIdle();
   2229     }
   2230 
   2231     bool stateSeen = false;
   2232     do {
   2233         if (active == (mStatus == STATUS_ACTIVE)) {
   2234             // Desired state is current
   2235             break;
   2236         }
   2237 
   2238         res = mStatusChanged.waitRelative(mLock, timeout);
   2239         if (res != OK) break;
   2240 
   2241         // This is impossible, but if not, could result in subtle deadlocks and invalid state
   2242         // transitions.
   2243         LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
   2244                 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
   2245                 __FUNCTION__);
   2246 
   2247         // Encountered desired state since we began waiting
   2248         for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
   2249             if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
   2250                 stateSeen = true;
   2251                 break;
   2252             }
   2253         }
   2254     } while (!stateSeen);
   2255 
   2256     mStatusWaiters--;
   2257 
   2258     return res;
   2259 }
   2260 
   2261 
   2262 status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
   2263     ATRACE_CALL();
   2264     Mutex::Autolock l(mOutputLock);
   2265 
   2266     if (listener != NULL && mListener != NULL) {
   2267         ALOGW("%s: Replacing old callback listener", __FUNCTION__);
   2268     }
   2269     mListener = listener;
   2270     mRequestThread->setNotificationListener(listener);
   2271     mPreparerThread->setNotificationListener(listener);
   2272 
   2273     return OK;
   2274 }
   2275 
   2276 bool Camera3Device::willNotify3A() {
   2277     return false;
   2278 }
   2279 
   2280 status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
   2281     ATRACE_CALL();
   2282     status_t res;
   2283     Mutex::Autolock l(mOutputLock);
   2284 
   2285     while (mResultQueue.empty()) {
   2286         res = mResultSignal.waitRelative(mOutputLock, timeout);
   2287         if (res == TIMED_OUT) {
   2288             return res;
   2289         } else if (res != OK) {
   2290             ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
   2291                     __FUNCTION__, mId.string(), timeout, strerror(-res), res);
   2292             return res;
   2293         }
   2294     }
   2295     return OK;
   2296 }
   2297 
   2298 status_t Camera3Device::getNextResult(CaptureResult *frame) {
   2299     ATRACE_CALL();
   2300     Mutex::Autolock l(mOutputLock);
   2301 
   2302     if (mResultQueue.empty()) {
   2303         return NOT_ENOUGH_DATA;
   2304     }
   2305 
   2306     if (frame == NULL) {
   2307         ALOGE("%s: argument cannot be NULL", __FUNCTION__);
   2308         return BAD_VALUE;
   2309     }
   2310 
   2311     CaptureResult &result = *(mResultQueue.begin());
   2312     frame->mResultExtras = result.mResultExtras;
   2313     frame->mMetadata.acquire(result.mMetadata);
   2314     frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
   2315     mResultQueue.erase(mResultQueue.begin());
   2316 
   2317     return OK;
   2318 }
   2319 
   2320 status_t Camera3Device::triggerAutofocus(uint32_t id) {
   2321     ATRACE_CALL();
   2322     Mutex::Autolock il(mInterfaceLock);
   2323 
   2324     ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
   2325     // Mix-in this trigger into the next request and only the next request.
   2326     RequestTrigger trigger[] = {
   2327         {
   2328             ANDROID_CONTROL_AF_TRIGGER,
   2329             ANDROID_CONTROL_AF_TRIGGER_START
   2330         },
   2331         {
   2332             ANDROID_CONTROL_AF_TRIGGER_ID,
   2333             static_cast<int32_t>(id)
   2334         }
   2335     };
   2336 
   2337     return mRequestThread->queueTrigger(trigger,
   2338                                         sizeof(trigger)/sizeof(trigger[0]));
   2339 }
   2340 
   2341 status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
   2342     ATRACE_CALL();
   2343     Mutex::Autolock il(mInterfaceLock);
   2344 
   2345     ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
   2346     // Mix-in this trigger into the next request and only the next request.
   2347     RequestTrigger trigger[] = {
   2348         {
   2349             ANDROID_CONTROL_AF_TRIGGER,
   2350             ANDROID_CONTROL_AF_TRIGGER_CANCEL
   2351         },
   2352         {
   2353             ANDROID_CONTROL_AF_TRIGGER_ID,
   2354             static_cast<int32_t>(id)
   2355         }
   2356     };
   2357 
   2358     return mRequestThread->queueTrigger(trigger,
   2359                                         sizeof(trigger)/sizeof(trigger[0]));
   2360 }
   2361 
   2362 status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
   2363     ATRACE_CALL();
   2364     Mutex::Autolock il(mInterfaceLock);
   2365 
   2366     ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
   2367     // Mix-in this trigger into the next request and only the next request.
   2368     RequestTrigger trigger[] = {
   2369         {
   2370             ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
   2371             ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
   2372         },
   2373         {
   2374             ANDROID_CONTROL_AE_PRECAPTURE_ID,
   2375             static_cast<int32_t>(id)
   2376         }
   2377     };
   2378 
   2379     return mRequestThread->queueTrigger(trigger,
   2380                                         sizeof(trigger)/sizeof(trigger[0]));
   2381 }
   2382 
   2383 status_t Camera3Device::flush(int64_t *frameNumber) {
   2384     ATRACE_CALL();
   2385     ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
   2386     Mutex::Autolock il(mInterfaceLock);
   2387 
   2388     {
   2389         Mutex::Autolock l(mLock);
   2390 
   2391         // b/116514106 "disconnect()" can get called twice for the same device. The
   2392         // camera device will not be initialized during the second run.
   2393         if (mStatus == STATUS_UNINITIALIZED) {
   2394             return OK;
   2395         }
   2396 
   2397         mRequestThread->clear(/*out*/frameNumber);
   2398     }
   2399 
   2400     return mRequestThread->flush();
   2401 }
   2402 
   2403 status_t Camera3Device::prepare(int streamId) {
   2404     return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
   2405 }
   2406 
   2407 status_t Camera3Device::prepare(int maxCount, int streamId) {
   2408     ATRACE_CALL();
   2409     ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
   2410     Mutex::Autolock il(mInterfaceLock);
   2411     Mutex::Autolock l(mLock);
   2412 
   2413     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
   2414     if (stream == nullptr) {
   2415         CLOGE("Stream %d does not exist", streamId);
   2416         return BAD_VALUE;
   2417     }
   2418 
   2419     if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
   2420         CLOGE("Stream %d has already been a request target", streamId);
   2421         return BAD_VALUE;
   2422     }
   2423 
   2424     if (mRequestThread->isStreamPending(stream)) {
   2425         CLOGE("Stream %d is already a target in a pending request", streamId);
   2426         return BAD_VALUE;
   2427     }
   2428 
   2429     return mPreparerThread->prepare(maxCount, stream);
   2430 }
   2431 
   2432 status_t Camera3Device::tearDown(int streamId) {
   2433     ATRACE_CALL();
   2434     ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
   2435     Mutex::Autolock il(mInterfaceLock);
   2436     Mutex::Autolock l(mLock);
   2437 
   2438     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
   2439     if (stream == nullptr) {
   2440         CLOGE("Stream %d does not exist", streamId);
   2441         return BAD_VALUE;
   2442     }
   2443 
   2444     if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
   2445         CLOGE("Stream %d is a target of a in-progress request", streamId);
   2446         return BAD_VALUE;
   2447     }
   2448 
   2449     return stream->tearDown();
   2450 }
   2451 
   2452 status_t Camera3Device::addBufferListenerForStream(int streamId,
   2453         wp<Camera3StreamBufferListener> listener) {
   2454     ATRACE_CALL();
   2455     ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
   2456     Mutex::Autolock il(mInterfaceLock);
   2457     Mutex::Autolock l(mLock);
   2458 
   2459     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
   2460     if (stream == nullptr) {
   2461         CLOGE("Stream %d does not exist", streamId);
   2462         return BAD_VALUE;
   2463     }
   2464     stream->addBufferListener(listener);
   2465 
   2466     return OK;
   2467 }
   2468 
   2469 /**
   2470  * Methods called by subclasses
   2471  */
   2472 
   2473 void Camera3Device::notifyStatus(bool idle) {
   2474     ATRACE_CALL();
   2475     {
   2476         // Need mLock to safely update state and synchronize to current
   2477         // state of methods in flight.
   2478         Mutex::Autolock l(mLock);
   2479         // We can get various system-idle notices from the status tracker
   2480         // while starting up. Only care about them if we've actually sent
   2481         // in some requests recently.
   2482         if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
   2483             return;
   2484         }
   2485         ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
   2486                 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
   2487         internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
   2488 
   2489         // Skip notifying listener if we're doing some user-transparent
   2490         // state changes
   2491         if (mPauseStateNotify) return;
   2492     }
   2493 
   2494     sp<NotificationListener> listener;
   2495     {
   2496         Mutex::Autolock l(mOutputLock);
   2497         listener = mListener.promote();
   2498     }
   2499     if (idle && listener != NULL) {
   2500         listener->notifyIdle();
   2501     }
   2502 }
   2503 
   2504 status_t Camera3Device::setConsumerSurfaces(int streamId,
   2505         const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
   2506     ATRACE_CALL();
   2507     ALOGV("%s: Camera %s: set consumer surface for stream %d",
   2508             __FUNCTION__, mId.string(), streamId);
   2509 
   2510     if (surfaceIds == nullptr) {
   2511         return BAD_VALUE;
   2512     }
   2513 
   2514     Mutex::Autolock il(mInterfaceLock);
   2515     Mutex::Autolock l(mLock);
   2516 
   2517     if (consumers.size() == 0) {
   2518         CLOGE("No consumer is passed!");
   2519         return BAD_VALUE;
   2520     }
   2521 
   2522     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
   2523     if (stream == nullptr) {
   2524         CLOGE("Stream %d is unknown", streamId);
   2525         return BAD_VALUE;
   2526     }
   2527 
   2528     // isConsumerConfigurationDeferred will be off after setConsumers
   2529     bool isDeferred = stream->isConsumerConfigurationDeferred();
   2530     status_t res = stream->setConsumers(consumers);
   2531     if (res != OK) {
   2532         CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
   2533         return res;
   2534     }
   2535 
   2536     for (auto &consumer : consumers) {
   2537         int id = stream->getSurfaceId(consumer);
   2538         if (id < 0) {
   2539             CLOGE("Invalid surface id!");
   2540             return BAD_VALUE;
   2541         }
   2542         surfaceIds->push_back(id);
   2543     }
   2544 
   2545     if (isDeferred) {
   2546         if (!stream->isConfiguring()) {
   2547             CLOGE("Stream %d was already fully configured.", streamId);
   2548             return INVALID_OPERATION;
   2549         }
   2550 
   2551         res = stream->finishConfiguration();
   2552         if (res != OK) {
   2553             // If finishConfiguration fails due to abandoned surface, do not set
   2554             // device to error state.
   2555             bool isSurfaceAbandoned =
   2556                     (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
   2557             if (!isSurfaceAbandoned) {
   2558                 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
   2559                         stream->getId(), strerror(-res), res);
   2560             }
   2561             return res;
   2562         }
   2563     }
   2564 
   2565     return OK;
   2566 }
   2567 
   2568 status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
   2569         const std::vector<OutputStreamInfo> &outputInfo,
   2570         const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
   2571     Mutex::Autolock il(mInterfaceLock);
   2572     Mutex::Autolock l(mLock);
   2573 
   2574     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
   2575     if (stream == nullptr) {
   2576         CLOGE("Stream %d is unknown", streamId);
   2577         return BAD_VALUE;
   2578     }
   2579 
   2580     for (const auto &it : removedSurfaceIds) {
   2581         if (mRequestThread->isOutputSurfacePending(streamId, it)) {
   2582             CLOGE("Shared surface still part of a pending request!");
   2583             return -EBUSY;
   2584         }
   2585     }
   2586 
   2587     status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
   2588     if (res != OK) {
   2589         CLOGE("Stream %d failed to update stream (error %d %s) ",
   2590               streamId, res, strerror(-res));
   2591         if (res == UNKNOWN_ERROR) {
   2592             SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
   2593                     __FUNCTION__);
   2594         }
   2595         return res;
   2596     }
   2597 
   2598     return res;
   2599 }
   2600 
   2601 status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
   2602     Mutex::Autolock il(mInterfaceLock);
   2603     Mutex::Autolock l(mLock);
   2604 
   2605     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
   2606     if (stream == nullptr) {
   2607         ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
   2608         return BAD_VALUE;
   2609     }
   2610     return stream->dropBuffers(dropping);
   2611 }
   2612 
   2613 /**
   2614  * Camera3Device private methods
   2615  */
   2616 
   2617 sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
   2618         const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
   2619     ATRACE_CALL();
   2620 
   2621     sp<CaptureRequest> newRequest = new CaptureRequest;
   2622     newRequest->mSettingsList = request;
   2623 
   2624     camera_metadata_entry_t inputStreams =
   2625             newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
   2626     if (inputStreams.count > 0) {
   2627         if (mInputStream == NULL ||
   2628                 mInputStream->getId() != inputStreams.data.i32[0]) {
   2629             CLOGE("Request references unknown input stream %d",
   2630                     inputStreams.data.u8[0]);
   2631             return NULL;
   2632         }
   2633 
   2634         if (mInputStream->isConfiguring()) {
   2635             SET_ERR_L("%s: input stream %d is not configured!",
   2636                     __FUNCTION__, mInputStream->getId());
   2637             return NULL;
   2638         }
   2639         // Check if stream prepare is blocking requests.
   2640         if (mInputStream->isBlockedByPrepare()) {
   2641             CLOGE("Request references an input stream that's being prepared!");
   2642             return NULL;
   2643         }
   2644 
   2645         newRequest->mInputStream = mInputStream;
   2646         newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
   2647     }
   2648 
   2649     camera_metadata_entry_t streams =
   2650             newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
   2651     if (streams.count == 0) {
   2652         CLOGE("Zero output streams specified!");
   2653         return NULL;
   2654     }
   2655 
   2656     for (size_t i = 0; i < streams.count; i++) {
   2657         sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
   2658         if (stream == nullptr) {
   2659             CLOGE("Request references unknown stream %d",
   2660                     streams.data.i32[i]);
   2661             return NULL;
   2662         }
   2663         // It is illegal to include a deferred consumer output stream into a request
   2664         auto iter = surfaceMap.find(streams.data.i32[i]);
   2665         if (iter != surfaceMap.end()) {
   2666             const std::vector<size_t>& surfaces = iter->second;
   2667             for (const auto& surface : surfaces) {
   2668                 if (stream->isConsumerConfigurationDeferred(surface)) {
   2669                     CLOGE("Stream %d surface %zu hasn't finished configuration yet "
   2670                           "due to deferred consumer", stream->getId(), surface);
   2671                     return NULL;
   2672                 }
   2673             }
   2674             newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
   2675         }
   2676 
   2677         if (stream->isConfiguring()) {
   2678             SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
   2679             return NULL;
   2680         }
   2681         // Check if stream prepare is blocking requests.
   2682         if (stream->isBlockedByPrepare()) {
   2683             CLOGE("Request references an output stream that's being prepared!");
   2684             return NULL;
   2685         }
   2686 
   2687         newRequest->mOutputStreams.push(stream);
   2688     }
   2689     newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
   2690     newRequest->mBatchSize = 1;
   2691 
   2692     return newRequest;
   2693 }
   2694 
   2695 bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
   2696     for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
   2697         Size size = mSupportedOpaqueInputSizes[i];
   2698         if (size.width == width && size.height == height) {
   2699             return true;
   2700         }
   2701     }
   2702 
   2703     return false;
   2704 }
   2705 
   2706 void Camera3Device::cancelStreamsConfigurationLocked() {
   2707     int res = OK;
   2708     if (mInputStream != NULL && mInputStream->isConfiguring()) {
   2709         res = mInputStream->cancelConfiguration();
   2710         if (res != OK) {
   2711             CLOGE("Can't cancel configuring input stream %d: %s (%d)",
   2712                     mInputStream->getId(), strerror(-res), res);
   2713         }
   2714     }
   2715 
   2716     for (size_t i = 0; i < mOutputStreams.size(); i++) {
   2717         sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
   2718         if (outputStream->isConfiguring()) {
   2719             res = outputStream->cancelConfiguration();
   2720             if (res != OK) {
   2721                 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
   2722                         outputStream->getId(), strerror(-res), res);
   2723             }
   2724         }
   2725     }
   2726 
   2727     // Return state to that at start of call, so that future configures
   2728     // properly clean things up
   2729     internalUpdateStatusLocked(STATUS_UNCONFIGURED);
   2730     mNeedConfig = true;
   2731 
   2732     res = mPreparerThread->resume();
   2733     if (res != OK) {
   2734         ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
   2735     }
   2736 }
   2737 
   2738 bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
   2739     ATRACE_CALL();
   2740     bool ret = false;
   2741 
   2742     Mutex::Autolock il(mInterfaceLock);
   2743     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
   2744 
   2745     Mutex::Autolock l(mLock);
   2746     auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
   2747     if (rc == NO_ERROR) {
   2748         mNeedConfig = true;
   2749         rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
   2750         if (rc == NO_ERROR) {
   2751             ret = true;
   2752             mPauseStateNotify = false;
   2753             //Moving to active state while holding 'mLock' is important.
   2754             //There could be pending calls to 'create-/deleteStream' which
   2755             //will trigger another stream configuration while the already
   2756             //present streams end up with outstanding buffers that will
   2757             //not get drained.
   2758             internalUpdateStatusLocked(STATUS_ACTIVE);
   2759         } else if (rc == DEAD_OBJECT) {
   2760             // DEAD_OBJECT can be returned if either the consumer surface is
   2761             // abandoned, or the HAL has died.
   2762             // - If the HAL has died, configureStreamsLocked call will set
   2763             // device to error state,
   2764             // - If surface is abandoned, we should not set device to error
   2765             // state.
   2766             ALOGE("Failed to re-configure camera due to abandoned surface");
   2767         } else {
   2768             SET_ERR_L("Failed to re-configure camera: %d", rc);
   2769         }
   2770     } else {
   2771         ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
   2772     }
   2773 
   2774     return ret;
   2775 }
   2776 
   2777 status_t Camera3Device::configureStreamsLocked(int operatingMode,
   2778         const CameraMetadata& sessionParams, bool notifyRequestThread) {
   2779     ATRACE_CALL();
   2780     status_t res;
   2781 
   2782     if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
   2783         CLOGE("Not idle");
   2784         return INVALID_OPERATION;
   2785     }
   2786 
   2787     if (operatingMode < 0) {
   2788         CLOGE("Invalid operating mode: %d", operatingMode);
   2789         return BAD_VALUE;
   2790     }
   2791 
   2792     bool isConstrainedHighSpeed =
   2793             static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
   2794             operatingMode;
   2795 
   2796     if (mOperatingMode != operatingMode) {
   2797         mNeedConfig = true;
   2798         mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
   2799         mOperatingMode = operatingMode;
   2800     }
   2801 
   2802     if (!mNeedConfig) {
   2803         ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
   2804         return OK;
   2805     }
   2806 
   2807     // Workaround for device HALv3.2 or older spec bug - zero streams requires
   2808     // adding a dummy stream instead.
   2809     // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
   2810     if (mOutputStreams.size() == 0) {
   2811         addDummyStreamLocked();
   2812     } else {
   2813         tryRemoveDummyStreamLocked();
   2814     }
   2815 
   2816     // Start configuring the streams
   2817     ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
   2818 
   2819     mPreparerThread->pause();
   2820 
   2821     camera3_stream_configuration config;
   2822     config.operation_mode = mOperatingMode;
   2823     config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
   2824 
   2825     Vector<camera3_stream_t*> streams;
   2826     streams.setCapacity(config.num_streams);
   2827     std::vector<uint32_t> bufferSizes(config.num_streams, 0);
   2828 
   2829 
   2830     if (mInputStream != NULL) {
   2831         camera3_stream_t *inputStream;
   2832         inputStream = mInputStream->startConfiguration();
   2833         if (inputStream == NULL) {
   2834             CLOGE("Can't start input stream configuration");
   2835             cancelStreamsConfigurationLocked();
   2836             return INVALID_OPERATION;
   2837         }
   2838         streams.add(inputStream);
   2839     }
   2840 
   2841     for (size_t i = 0; i < mOutputStreams.size(); i++) {
   2842 
   2843         // Don't configure bidi streams twice, nor add them twice to the list
   2844         if (mOutputStreams[i].get() ==
   2845             static_cast<Camera3StreamInterface*>(mInputStream.get())) {
   2846 
   2847             config.num_streams--;
   2848             continue;
   2849         }
   2850 
   2851         camera3_stream_t *outputStream;
   2852         outputStream = mOutputStreams[i]->startConfiguration();
   2853         if (outputStream == NULL) {
   2854             CLOGE("Can't start output stream configuration");
   2855             cancelStreamsConfigurationLocked();
   2856             return INVALID_OPERATION;
   2857         }
   2858         streams.add(outputStream);
   2859 
   2860         if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
   2861             size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
   2862                                                                 // always occupy the initial entry.
   2863             if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
   2864                 bufferSizes[k] = static_cast<uint32_t>(
   2865                         getJpegBufferSize(outputStream->width, outputStream->height));
   2866             } else if (outputStream->data_space ==
   2867                     static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
   2868                 bufferSizes[k] = outputStream->width * outputStream->height;
   2869             } else {
   2870                 ALOGW("%s: Blob dataSpace %d not supported",
   2871                         __FUNCTION__, outputStream->data_space);
   2872             }
   2873         }
   2874     }
   2875 
   2876     config.streams = streams.editArray();
   2877 
   2878     // Do the HAL configuration; will potentially touch stream
   2879     // max_buffers, usage, and priv fields, as well as data_space and format
   2880     // fields for IMPLEMENTATION_DEFINED formats.
   2881 
   2882     const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
   2883     res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
   2884     sessionParams.unlock(sessionBuffer);
   2885 
   2886     if (res == BAD_VALUE) {
   2887         // HAL rejected this set of streams as unsupported, clean up config
   2888         // attempt and return to unconfigured state
   2889         CLOGE("Set of requested inputs/outputs not supported by HAL");
   2890         cancelStreamsConfigurationLocked();
   2891         return BAD_VALUE;
   2892     } else if (res != OK) {
   2893         // Some other kind of error from configure_streams - this is not
   2894         // expected
   2895         SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
   2896                 strerror(-res), res);
   2897         return res;
   2898     }
   2899 
   2900     // Finish all stream configuration immediately.
   2901     // TODO: Try to relax this later back to lazy completion, which should be
   2902     // faster
   2903 
   2904     if (mInputStream != NULL && mInputStream->isConfiguring()) {
   2905         bool streamReConfigured = false;
   2906         res = mInputStream->finishConfiguration(&streamReConfigured);
   2907         if (res != OK) {
   2908             CLOGE("Can't finish configuring input stream %d: %s (%d)",
   2909                     mInputStream->getId(), strerror(-res), res);
   2910             cancelStreamsConfigurationLocked();
   2911             if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
   2912                 return DEAD_OBJECT;
   2913             }
   2914             return BAD_VALUE;
   2915         }
   2916         if (streamReConfigured) {
   2917             mInterface->onStreamReConfigured(mInputStream->getId());
   2918         }
   2919     }
   2920 
   2921     for (size_t i = 0; i < mOutputStreams.size(); i++) {
   2922         sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
   2923         if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
   2924             bool streamReConfigured = false;
   2925             res = outputStream->finishConfiguration(&streamReConfigured);
   2926             if (res != OK) {
   2927                 CLOGE("Can't finish configuring output stream %d: %s (%d)",
   2928                         outputStream->getId(), strerror(-res), res);
   2929                 cancelStreamsConfigurationLocked();
   2930                 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
   2931                     return DEAD_OBJECT;
   2932                 }
   2933                 return BAD_VALUE;
   2934             }
   2935             if (streamReConfigured) {
   2936                 mInterface->onStreamReConfigured(outputStream->getId());
   2937             }
   2938         }
   2939     }
   2940 
   2941     // Request thread needs to know to avoid using repeat-last-settings protocol
   2942     // across configure_streams() calls
   2943     if (notifyRequestThread) {
   2944         mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
   2945     }
   2946 
   2947     char value[PROPERTY_VALUE_MAX];
   2948     property_get("camera.fifo.disable", value, "0");
   2949     int32_t disableFifo = atoi(value);
   2950     if (disableFifo != 1) {
   2951         // Boost priority of request thread to SCHED_FIFO.
   2952         pid_t requestThreadTid = mRequestThread->getTid();
   2953         res = requestPriority(getpid(), requestThreadTid,
   2954                 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
   2955         if (res != OK) {
   2956             ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
   2957                     strerror(-res), res);
   2958         } else {
   2959             ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
   2960         }
   2961     }
   2962 
   2963     // Update device state
   2964     const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
   2965     const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
   2966     bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
   2967     sessionParams.unlock(newSessionParams);
   2968     mSessionParams.unlock(currentSessionParams);
   2969     if (updateSessionParams)  {
   2970         mSessionParams = sessionParams;
   2971     }
   2972 
   2973     mNeedConfig = false;
   2974 
   2975     internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
   2976             STATUS_CONFIGURED : STATUS_UNCONFIGURED);
   2977 
   2978     ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
   2979 
   2980     // tear down the deleted streams after configure streams.
   2981     mDeletedStreams.clear();
   2982 
   2983     auto rc = mPreparerThread->resume();
   2984     if (rc != OK) {
   2985         SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
   2986         return rc;
   2987     }
   2988 
   2989     if (mDummyStreamId == NO_STREAM) {
   2990         mRequestBufferSM.onStreamsConfigured();
   2991     }
   2992 
   2993     return OK;
   2994 }
   2995 
   2996 status_t Camera3Device::addDummyStreamLocked() {
   2997     ATRACE_CALL();
   2998     status_t res;
   2999 
   3000     if (mDummyStreamId != NO_STREAM) {
   3001         // Should never be adding a second dummy stream when one is already
   3002         // active
   3003         SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
   3004                 __FUNCTION__, mId.string());
   3005         return INVALID_OPERATION;
   3006     }
   3007 
   3008     ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
   3009 
   3010     sp<Camera3OutputStreamInterface> dummyStream =
   3011             new Camera3DummyStream(mNextStreamId);
   3012 
   3013     res = mOutputStreams.add(mNextStreamId, dummyStream);
   3014     if (res < 0) {
   3015         SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
   3016         return res;
   3017     }
   3018 
   3019     mDummyStreamId = mNextStreamId;
   3020     mNextStreamId++;
   3021 
   3022     return OK;
   3023 }
   3024 
   3025 status_t Camera3Device::tryRemoveDummyStreamLocked() {
   3026     ATRACE_CALL();
   3027     status_t res;
   3028 
   3029     if (mDummyStreamId == NO_STREAM) return OK;
   3030     if (mOutputStreams.size() == 1) return OK;
   3031 
   3032     ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
   3033 
   3034     // Ok, have a dummy stream and there's at least one other output stream,
   3035     // so remove the dummy
   3036 
   3037     sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
   3038     if (deletedStream == nullptr) {
   3039         SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
   3040         return INVALID_OPERATION;
   3041     }
   3042     mOutputStreams.remove(mDummyStreamId);
   3043 
   3044     // Free up the stream endpoint so that it can be used by some other stream
   3045     res = deletedStream->disconnect();
   3046     if (res != OK) {
   3047         SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
   3048         // fall through since we want to still list the stream as deleted.
   3049     }
   3050     mDeletedStreams.add(deletedStream);
   3051     mDummyStreamId = NO_STREAM;
   3052 
   3053     return res;
   3054 }
   3055 
   3056 void Camera3Device::setErrorState(const char *fmt, ...) {
   3057     ATRACE_CALL();
   3058     Mutex::Autolock l(mLock);
   3059     va_list args;
   3060     va_start(args, fmt);
   3061 
   3062     setErrorStateLockedV(fmt, args);
   3063 
   3064     va_end(args);
   3065 }
   3066 
   3067 void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
   3068     ATRACE_CALL();
   3069     Mutex::Autolock l(mLock);
   3070     setErrorStateLockedV(fmt, args);
   3071 }
   3072 
   3073 void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
   3074     va_list args;
   3075     va_start(args, fmt);
   3076 
   3077     setErrorStateLockedV(fmt, args);
   3078 
   3079     va_end(args);
   3080 }
   3081 
   3082 void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
   3083     // Print out all error messages to log
   3084     String8 errorCause = String8::formatV(fmt, args);
   3085     ALOGE("Camera %s: %s", mId.string(), errorCause.string());
   3086 
   3087     // But only do error state transition steps for the first error
   3088     if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
   3089 
   3090     mErrorCause = errorCause;
   3091 
   3092     if (mRequestThread != nullptr) {
   3093         mRequestThread->setPaused(true);
   3094     }
   3095     internalUpdateStatusLocked(STATUS_ERROR);
   3096 
   3097     // Notify upstream about a device error
   3098     sp<NotificationListener> listener = mListener.promote();
   3099     if (listener != NULL) {
   3100         listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
   3101                 CaptureResultExtras());
   3102     }
   3103 
   3104     // Save stack trace. View by dumping it later.
   3105     CameraTraces::saveTrace();
   3106     // TODO: consider adding errorCause and client pid/procname
   3107 }
   3108 
   3109 /**
   3110  * In-flight request management
   3111  */
   3112 
   3113 status_t Camera3Device::registerInFlight(uint32_t frameNumber,
   3114         int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
   3115         bool hasAppCallback, nsecs_t maxExpectedDuration,
   3116         std::set<String8>& physicalCameraIds, bool isStillCapture,
   3117         bool isZslCapture, const SurfaceMap& outputSurfaces) {
   3118     ATRACE_CALL();
   3119     Mutex::Autolock l(mInFlightLock);
   3120 
   3121     ssize_t res;
   3122     res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
   3123             hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
   3124             outputSurfaces));
   3125     if (res < 0) return res;
   3126 
   3127     if (mInFlightMap.size() == 1) {
   3128         // Hold a separate dedicated tracker lock to prevent race with disconnect and also
   3129         // avoid a deadlock during reprocess requests.
   3130         Mutex::Autolock l(mTrackerLock);
   3131         if (mStatusTracker != nullptr) {
   3132             mStatusTracker->markComponentActive(mInFlightStatusId);
   3133         }
   3134     }
   3135 
   3136     mExpectedInflightDuration += maxExpectedDuration;
   3137     return OK;
   3138 }
   3139 
   3140 void Camera3Device::returnOutputBuffers(
   3141         const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
   3142         nsecs_t timestamp, bool timestampIncreasing,
   3143         const SurfaceMap& outputSurfaces,
   3144         const CaptureResultExtras &inResultExtras) {
   3145 
   3146     for (size_t i = 0; i < numBuffers; i++)
   3147     {
   3148         if (outputBuffers[i].buffer == nullptr) {
   3149             if (!mUseHalBufManager) {
   3150                 // With HAL buffer management API, HAL sometimes will have to return buffers that
   3151                 // has not got a output buffer handle filled yet. This is though illegal if HAL
   3152                 // buffer management API is not being used.
   3153                 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
   3154             }
   3155             continue;
   3156         }
   3157 
   3158         Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
   3159         int streamId = stream->getId();
   3160         const auto& it = outputSurfaces.find(streamId);
   3161         status_t res = OK;
   3162         if (it != outputSurfaces.end()) {
   3163             res = stream->returnBuffer(
   3164                     outputBuffers[i], timestamp, timestampIncreasing, it->second,
   3165                     inResultExtras.frameNumber);
   3166         } else {
   3167             res = stream->returnBuffer(
   3168                     outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
   3169                     inResultExtras.frameNumber);
   3170         }
   3171 
   3172         // Note: stream may be deallocated at this point, if this buffer was
   3173         // the last reference to it.
   3174         if (res == NO_INIT || res == DEAD_OBJECT) {
   3175             ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
   3176         } else if (res != OK) {
   3177             ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
   3178         }
   3179 
   3180         // Long processing consumers can cause returnBuffer timeout for shared stream
   3181         // If that happens, cancel the buffer and send a buffer error to client
   3182         if (it != outputSurfaces.end() && res == TIMED_OUT &&
   3183                 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
   3184             // cancel the buffer
   3185             camera3_stream_buffer_t sb = outputBuffers[i];
   3186             sb.status = CAMERA3_BUFFER_STATUS_ERROR;
   3187             stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
   3188                     inResultExtras.frameNumber);
   3189 
   3190             // notify client buffer error
   3191             sp<NotificationListener> listener;
   3192             {
   3193                 Mutex::Autolock l(mOutputLock);
   3194                 listener = mListener.promote();
   3195             }
   3196 
   3197             if (listener != nullptr) {
   3198                 CaptureResultExtras extras = inResultExtras;
   3199                 extras.errorStreamId = streamId;
   3200                 listener->notifyError(
   3201                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
   3202                         extras);
   3203             }
   3204         }
   3205     }
   3206 }
   3207 
   3208 void Camera3Device::removeInFlightMapEntryLocked(int idx) {
   3209     ATRACE_CALL();
   3210     nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
   3211     mInFlightMap.removeItemsAt(idx, 1);
   3212 
   3213     // Indicate idle inFlightMap to the status tracker
   3214     if (mInFlightMap.size() == 0) {
   3215         mRequestBufferSM.onInflightMapEmpty();
   3216         // Hold a separate dedicated tracker lock to prevent race with disconnect and also
   3217         // avoid a deadlock during reprocess requests.
   3218         Mutex::Autolock l(mTrackerLock);
   3219         if (mStatusTracker != nullptr) {
   3220             mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
   3221         }
   3222     }
   3223     mExpectedInflightDuration -= duration;
   3224 }
   3225 
   3226 void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
   3227 
   3228     const InFlightRequest &request = mInFlightMap.valueAt(idx);
   3229     const uint32_t frameNumber = mInFlightMap.keyAt(idx);
   3230 
   3231     nsecs_t sensorTimestamp = request.sensorTimestamp;
   3232     nsecs_t shutterTimestamp = request.shutterTimestamp;
   3233 
   3234     // Check if it's okay to remove the request from InFlightMap:
   3235     // In the case of a successful request:
   3236     //      all input and output buffers, all result metadata, shutter callback
   3237     //      arrived.
   3238     // In the case of a unsuccessful request:
   3239     //      all input and output buffers arrived.
   3240     if (request.numBuffersLeft == 0 &&
   3241             (request.skipResultMetadata ||
   3242             (request.haveResultMetadata && shutterTimestamp != 0))) {
   3243         if (request.stillCapture) {
   3244             ATRACE_ASYNC_END("still capture", frameNumber);
   3245         }
   3246 
   3247         ATRACE_ASYNC_END("frame capture", frameNumber);
   3248 
   3249         // Sanity check - if sensor timestamp matches shutter timestamp in the
   3250         // case of request having callback.
   3251         if (request.hasCallback && request.requestStatus == OK &&
   3252                 sensorTimestamp != shutterTimestamp) {
   3253             SET_ERR("sensor timestamp (%" PRId64
   3254                 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
   3255                 sensorTimestamp, frameNumber, shutterTimestamp);
   3256         }
   3257 
   3258         // for an unsuccessful request, it may have pending output buffers to
   3259         // return.
   3260         assert(request.requestStatus != OK ||
   3261                request.pendingOutputBuffers.size() == 0);
   3262         returnOutputBuffers(request.pendingOutputBuffers.array(),
   3263             request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
   3264             request.outputSurfaces, request.resultExtras);
   3265 
   3266         removeInFlightMapEntryLocked(idx);
   3267         ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
   3268      }
   3269 
   3270     // Sanity check - if we have too many in-flight frames, something has
   3271     // likely gone wrong
   3272     if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
   3273         CLOGE("In-flight list too large: %zu", mInFlightMap.size());
   3274     } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
   3275             kInFlightWarnLimitHighSpeed) {
   3276         CLOGE("In-flight list too large for high speed configuration: %zu",
   3277                 mInFlightMap.size());
   3278     }
   3279 }
   3280 
   3281 void Camera3Device::flushInflightRequests() {
   3282     ATRACE_CALL();
   3283     { // First return buffers cached in mInFlightMap
   3284         Mutex::Autolock l(mInFlightLock);
   3285         for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
   3286             const InFlightRequest &request = mInFlightMap.valueAt(idx);
   3287             returnOutputBuffers(request.pendingOutputBuffers.array(),
   3288                 request.pendingOutputBuffers.size(), 0,
   3289                 /*timestampIncreasing*/true, request.outputSurfaces,
   3290                 request.resultExtras);
   3291         }
   3292         mInFlightMap.clear();
   3293         mExpectedInflightDuration = 0;
   3294     }
   3295 
   3296     // Then return all inflight buffers not returned by HAL
   3297     std::vector<std::pair<int32_t, int32_t>> inflightKeys;
   3298     mInterface->getInflightBufferKeys(&inflightKeys);
   3299 
   3300     // Inflight buffers for HAL buffer manager
   3301     std::vector<uint64_t> inflightRequestBufferKeys;
   3302     mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
   3303 
   3304     // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
   3305     // frameNumber will be -1 for buffers from HAL buffer manager
   3306     std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
   3307     inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
   3308 
   3309     for (auto& pair : inflightKeys) {
   3310         int32_t frameNumber = pair.first;
   3311         int32_t streamId = pair.second;
   3312         buffer_handle_t* buffer;
   3313         status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
   3314         if (res != OK) {
   3315             ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
   3316                     __FUNCTION__, frameNumber, streamId);
   3317             continue;
   3318         }
   3319         inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
   3320     }
   3321 
   3322     for (auto& bufferId : inflightRequestBufferKeys) {
   3323         int32_t streamId = -1;
   3324         buffer_handle_t* buffer = nullptr;
   3325         status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
   3326         if (res != OK) {
   3327             ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
   3328             continue;
   3329         }
   3330         inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
   3331     }
   3332 
   3333     int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
   3334     for (auto& tuple : inflightBuffers) {
   3335         status_t res = OK;
   3336         int32_t streamId = std::get<0>(tuple);
   3337         int32_t frameNumber = std::get<1>(tuple);
   3338         buffer_handle_t* buffer = std::get<2>(tuple);
   3339 
   3340         camera3_stream_buffer_t streamBuffer;
   3341         streamBuffer.buffer = buffer;
   3342         streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
   3343         streamBuffer.acquire_fence = -1;
   3344         streamBuffer.release_fence = -1;
   3345 
   3346         // First check if the buffer belongs to deleted stream
   3347         bool streamDeleted = false;
   3348         for (auto& stream : mDeletedStreams) {
   3349             if (streamId == stream->getId()) {
   3350                 streamDeleted = true;
   3351                 // Return buffer to deleted stream
   3352                 camera3_stream* halStream = stream->asHalStream();
   3353                 streamBuffer.stream = halStream;
   3354                 switch (halStream->stream_type) {
   3355                     case CAMERA3_STREAM_OUTPUT:
   3356                         res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
   3357                                 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
   3358                         if (res != OK) {
   3359                             ALOGE("%s: Can't return output buffer for frame %d to"
   3360                                   " stream %d: %s (%d)",  __FUNCTION__,
   3361                                   frameNumber, streamId, strerror(-res), res);
   3362                         }
   3363                         break;
   3364                     case CAMERA3_STREAM_INPUT:
   3365                         res = stream->returnInputBuffer(streamBuffer);
   3366                         if (res != OK) {
   3367                             ALOGE("%s: Can't return input buffer for frame %d to"
   3368                                   " stream %d: %s (%d)",  __FUNCTION__,
   3369                                   frameNumber, streamId, strerror(-res), res);
   3370                         }
   3371                         break;
   3372                     default: // Bi-direcitonal stream is deprecated
   3373                         ALOGE("%s: stream %d has unknown stream type %d",
   3374                                 __FUNCTION__, streamId, halStream->stream_type);
   3375                         break;
   3376                 }
   3377                 break;
   3378             }
   3379         }
   3380         if (streamDeleted) {
   3381             continue;
   3382         }
   3383 
   3384         // Then check against configured streams
   3385         if (streamId == inputStreamId) {
   3386             streamBuffer.stream = mInputStream->asHalStream();
   3387             res = mInputStream->returnInputBuffer(streamBuffer);
   3388             if (res != OK) {
   3389                 ALOGE("%s: Can't return input buffer for frame %d to"
   3390                       " stream %d: %s (%d)",  __FUNCTION__,
   3391                       frameNumber, streamId, strerror(-res), res);
   3392             }
   3393         } else {
   3394             sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
   3395             if (stream == nullptr) {
   3396                 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
   3397                 continue;
   3398             }
   3399             streamBuffer.stream = stream->asHalStream();
   3400             returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
   3401         }
   3402     }
   3403 }
   3404 
   3405 void Camera3Device::insertResultLocked(CaptureResult *result,
   3406         uint32_t frameNumber) {
   3407     if (result == nullptr) return;
   3408 
   3409     camera_metadata_t *meta = const_cast<camera_metadata_t *>(
   3410             result->mMetadata.getAndLock());
   3411     set_camera_metadata_vendor_id(meta, mVendorTagId);
   3412     result->mMetadata.unlock(meta);
   3413 
   3414     if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
   3415             (int32_t*)&frameNumber, 1) != OK) {
   3416         SET_ERR("Failed to set frame number %d in metadata", frameNumber);
   3417         return;
   3418     }
   3419 
   3420     if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
   3421         SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
   3422         return;
   3423     }
   3424 
   3425     // Update vendor tag id for physical metadata
   3426     for (auto& physicalMetadata : result->mPhysicalMetadatas) {
   3427         camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
   3428                 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
   3429         set_camera_metadata_vendor_id(pmeta, mVendorTagId);
   3430         physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
   3431     }
   3432 
   3433     // Valid result, insert into queue
   3434     List<CaptureResult>::iterator queuedResult =
   3435             mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
   3436     ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
   3437            ", burstId = %" PRId32, __FUNCTION__,
   3438            queuedResult->mResultExtras.requestId,
   3439            queuedResult->mResultExtras.frameNumber,
   3440            queuedResult->mResultExtras.burstId);
   3441 
   3442     mResultSignal.signal();
   3443 }
   3444 
   3445 
   3446 void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
   3447         const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
   3448     ATRACE_CALL();
   3449     Mutex::Autolock l(mOutputLock);
   3450 
   3451     CaptureResult captureResult;
   3452     captureResult.mResultExtras = resultExtras;
   3453     captureResult.mMetadata = partialResult;
   3454 
   3455     // Fix up result metadata for monochrome camera.
   3456     status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
   3457     if (res != OK) {
   3458         SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
   3459         return;
   3460     }
   3461 
   3462     insertResultLocked(&captureResult, frameNumber);
   3463 }
   3464 
   3465 
   3466 void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
   3467         CaptureResultExtras &resultExtras,
   3468         CameraMetadata &collectedPartialResult,
   3469         uint32_t frameNumber,
   3470         bool reprocess, bool zslStillCapture,
   3471         const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
   3472     ATRACE_CALL();
   3473     if (pendingMetadata.isEmpty())
   3474         return;
   3475 
   3476     Mutex::Autolock l(mOutputLock);
   3477 
   3478     // TODO: need to track errors for tighter bounds on expected frame number
   3479     if (reprocess) {
   3480         if (frameNumber < mNextReprocessResultFrameNumber) {
   3481             SET_ERR("Out-of-order reprocess capture result metadata submitted! "
   3482                 "(got frame number %d, expecting %d)",
   3483                 frameNumber, mNextReprocessResultFrameNumber);
   3484             return;
   3485         }
   3486         mNextReprocessResultFrameNumber = frameNumber + 1;
   3487     } else if (zslStillCapture) {
   3488         if (frameNumber < mNextZslStillResultFrameNumber) {
   3489             SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
   3490                 "(got frame number %d, expecting %d)",
   3491                 frameNumber, mNextZslStillResultFrameNumber);
   3492             return;
   3493         }
   3494         mNextZslStillResultFrameNumber = frameNumber + 1;
   3495     } else {
   3496         if (frameNumber < mNextResultFrameNumber) {
   3497             SET_ERR("Out-of-order capture result metadata submitted! "
   3498                     "(got frame number %d, expecting %d)",
   3499                     frameNumber, mNextResultFrameNumber);
   3500             return;
   3501         }
   3502         mNextResultFrameNumber = frameNumber + 1;
   3503     }
   3504 
   3505     CaptureResult captureResult;
   3506     captureResult.mResultExtras = resultExtras;
   3507     captureResult.mMetadata = pendingMetadata;
   3508     captureResult.mPhysicalMetadatas = physicalMetadatas;
   3509 
   3510     // Append any previous partials to form a complete result
   3511     if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
   3512         captureResult.mMetadata.append(collectedPartialResult);
   3513     }
   3514 
   3515     captureResult.mMetadata.sort();
   3516 
   3517     // Check that there's a timestamp in the result metadata
   3518     camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
   3519     if (timestamp.count == 0) {
   3520         SET_ERR("No timestamp provided by HAL for frame %d!",
   3521                 frameNumber);
   3522         return;
   3523     }
   3524     for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
   3525         camera_metadata_entry timestamp =
   3526                 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
   3527         if (timestamp.count == 0) {
   3528             SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
   3529                     String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
   3530             return;
   3531         }
   3532     }
   3533 
   3534     // Fix up some result metadata to account for HAL-level distortion correction
   3535     status_t res =
   3536             mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
   3537     if (res != OK) {
   3538         SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
   3539                 frameNumber, strerror(res), res);
   3540         return;
   3541     }
   3542     for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
   3543         String8 cameraId8(physicalMetadata.mPhysicalCameraId);
   3544         if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
   3545             continue;
   3546         }
   3547         res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
   3548                 &physicalMetadata.mPhysicalCameraMetadata);
   3549         if (res != OK) {
   3550             SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
   3551                     frameNumber, strerror(res), res);
   3552             return;
   3553         }
   3554     }
   3555 
   3556     // Fix up result metadata for monochrome camera.
   3557     res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
   3558     if (res != OK) {
   3559         SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
   3560         return;
   3561     }
   3562     for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
   3563         String8 cameraId8(physicalMetadata.mPhysicalCameraId);
   3564         res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
   3565                 physicalMetadata.mPhysicalCameraMetadata);
   3566         if (res != OK) {
   3567             SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
   3568             return;
   3569         }
   3570     }
   3571 
   3572     std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
   3573     for (auto& m : physicalMetadatas) {
   3574         monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
   3575                 CameraMetadata(m.mPhysicalCameraMetadata));
   3576     }
   3577     mTagMonitor.monitorMetadata(TagMonitor::RESULT,
   3578             frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
   3579             monitoredPhysicalMetadata);
   3580 
   3581     insertResultLocked(&captureResult, frameNumber);
   3582 }
   3583 
   3584 /**
   3585  * Camera HAL device callback methods
   3586  */
   3587 
   3588 void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
   3589     ATRACE_CALL();
   3590 
   3591     status_t res;
   3592 
   3593     uint32_t frameNumber = result->frame_number;
   3594     if (result->result == NULL && result->num_output_buffers == 0 &&
   3595             result->input_buffer == NULL) {
   3596         SET_ERR("No result data provided by HAL for frame %d",
   3597                 frameNumber);
   3598         return;
   3599     }
   3600 
   3601     if (!mUsePartialResult &&
   3602             result->result != NULL &&
   3603             result->partial_result != 1) {
   3604         SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
   3605                 " if partial result is not supported",
   3606                 frameNumber, result->partial_result);
   3607         return;
   3608     }
   3609 
   3610     bool isPartialResult = false;
   3611     CameraMetadata collectedPartialResult;
   3612     bool hasInputBufferInRequest = false;
   3613 
   3614     // Get shutter timestamp and resultExtras from list of in-flight requests,
   3615     // where it was added by the shutter notification for this frame. If the
   3616     // shutter timestamp isn't received yet, append the output buffers to the
   3617     // in-flight request and they will be returned when the shutter timestamp
   3618     // arrives. Update the in-flight status and remove the in-flight entry if
   3619     // all result data and shutter timestamp have been received.
   3620     nsecs_t shutterTimestamp = 0;
   3621 
   3622     {
   3623         Mutex::Autolock l(mInFlightLock);
   3624         ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
   3625         if (idx == NAME_NOT_FOUND) {
   3626             SET_ERR("Unknown frame number for capture result: %d",
   3627                     frameNumber);
   3628             return;
   3629         }
   3630         InFlightRequest &request = mInFlightMap.editValueAt(idx);
   3631         ALOGVV("%s: got InFlightRequest requestId = %" PRId32
   3632                 ", frameNumber = %" PRId64 ", burstId = %" PRId32
   3633                 ", partialResultCount = %d, hasCallback = %d",
   3634                 __FUNCTION__, request.resultExtras.requestId,
   3635                 request.resultExtras.frameNumber, request.resultExtras.burstId,
   3636                 result->partial_result, request.hasCallback);
   3637         // Always update the partial count to the latest one if it's not 0
   3638         // (buffers only). When framework aggregates adjacent partial results
   3639         // into one, the latest partial count will be used.
   3640         if (result->partial_result != 0)
   3641             request.resultExtras.partialResultCount = result->partial_result;
   3642 
   3643         // Check if this result carries only partial metadata
   3644         if (mUsePartialResult && result->result != NULL) {
   3645             if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
   3646                 SET_ERR("Result is malformed for frame %d: partial_result %u must be  in"
   3647                         " the range of [1, %d] when metadata is included in the result",
   3648                         frameNumber, result->partial_result, mNumPartialResults);
   3649                 return;
   3650             }
   3651             isPartialResult = (result->partial_result < mNumPartialResults);
   3652             if (isPartialResult && result->num_physcam_metadata) {
   3653                 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
   3654                         " physical camera result", frameNumber);
   3655                 return;
   3656             }
   3657             if (isPartialResult) {
   3658                 request.collectedPartialResult.append(result->result);
   3659             }
   3660 
   3661             if (isPartialResult && request.hasCallback) {
   3662                 // Send partial capture result
   3663                 sendPartialCaptureResult(result->result, request.resultExtras,
   3664                         frameNumber);
   3665             }
   3666         }
   3667 
   3668         shutterTimestamp = request.shutterTimestamp;
   3669         hasInputBufferInRequest = request.hasInputBuffer;
   3670 
   3671         // Did we get the (final) result metadata for this capture?
   3672         if (result->result != NULL && !isPartialResult) {
   3673             if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
   3674                 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
   3675                         request.physicalCameraIds.size(), result->num_physcam_metadata);
   3676                 return;
   3677             }
   3678             if (request.haveResultMetadata) {
   3679                 SET_ERR("Called multiple times with metadata for frame %d",
   3680                         frameNumber);
   3681                 return;
   3682             }
   3683             for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
   3684                 String8 physicalId(result->physcam_ids[i]);
   3685                 std::set<String8>::iterator cameraIdIter =
   3686                         request.physicalCameraIds.find(physicalId);
   3687                 if (cameraIdIter != request.physicalCameraIds.end()) {
   3688                     request.physicalCameraIds.erase(cameraIdIter);
   3689                 } else {
   3690                     SET_ERR("Total result for frame %d has already returned for camera %s",
   3691                             frameNumber, physicalId.c_str());
   3692                     return;
   3693                 }
   3694             }
   3695             if (mUsePartialResult &&
   3696                     !request.collectedPartialResult.isEmpty()) {
   3697                 collectedPartialResult.acquire(
   3698                     request.collectedPartialResult);
   3699             }
   3700             request.haveResultMetadata = true;
   3701         }
   3702 
   3703         uint32_t numBuffersReturned = result->num_output_buffers;
   3704         if (result->input_buffer != NULL) {
   3705             if (hasInputBufferInRequest) {
   3706                 numBuffersReturned += 1;
   3707             } else {
   3708                 ALOGW("%s: Input buffer should be NULL if there is no input"
   3709                         " buffer sent in the request",
   3710                         __FUNCTION__);
   3711             }
   3712         }
   3713         request.numBuffersLeft -= numBuffersReturned;
   3714         if (request.numBuffersLeft < 0) {
   3715             SET_ERR("Too many buffers returned for frame %d",
   3716                     frameNumber);
   3717             return;
   3718         }
   3719 
   3720         camera_metadata_ro_entry_t entry;
   3721         res = find_camera_metadata_ro_entry(result->result,
   3722                 ANDROID_SENSOR_TIMESTAMP, &entry);
   3723         if (res == OK && entry.count == 1) {
   3724             request.sensorTimestamp = entry.data.i64[0];
   3725         }
   3726 
   3727         // If shutter event isn't received yet, append the output buffers to
   3728         // the in-flight request. Otherwise, return the output buffers to
   3729         // streams.
   3730         if (shutterTimestamp == 0) {
   3731             request.pendingOutputBuffers.appendArray(result->output_buffers,
   3732                 result->num_output_buffers);
   3733         } else {
   3734             bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
   3735             returnOutputBuffers(result->output_buffers,
   3736                 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
   3737                 request.outputSurfaces, request.resultExtras);
   3738         }
   3739 
   3740         if (result->result != NULL && !isPartialResult) {
   3741             for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
   3742                 CameraMetadata physicalMetadata;
   3743                 physicalMetadata.append(result->physcam_metadata[i]);
   3744                 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
   3745                         physicalMetadata});
   3746             }
   3747             if (shutterTimestamp == 0) {
   3748                 request.pendingMetadata = result->result;
   3749                 request.collectedPartialResult = collectedPartialResult;
   3750             } else if (request.hasCallback) {
   3751                 CameraMetadata metadata;
   3752                 metadata = result->result;
   3753                 sendCaptureResult(metadata, request.resultExtras,
   3754                     collectedPartialResult, frameNumber,
   3755                     hasInputBufferInRequest, request.zslCapture && request.stillCapture,
   3756                     request.physicalMetadatas);
   3757             }
   3758         }
   3759 
   3760         removeInFlightRequestIfReadyLocked(idx);
   3761     } // scope for mInFlightLock
   3762 
   3763     if (result->input_buffer != NULL) {
   3764         if (hasInputBufferInRequest) {
   3765             Camera3Stream *stream =
   3766                 Camera3Stream::cast(result->input_buffer->stream);
   3767             res = stream->returnInputBuffer(*(result->input_buffer));
   3768             // Note: stream may be deallocated at this point, if this buffer was the
   3769             // last reference to it.
   3770             if (res != OK) {
   3771                 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
   3772                       "  its stream:%s (%d)",  __FUNCTION__,
   3773                       frameNumber, strerror(-res), res);
   3774             }
   3775         } else {
   3776             ALOGW("%s: Input buffer should be NULL if there is no input"
   3777                     " buffer sent in the request, skipping input buffer return.",
   3778                     __FUNCTION__);
   3779         }
   3780     }
   3781 }
   3782 
   3783 void Camera3Device::notify(const camera3_notify_msg *msg) {
   3784     ATRACE_CALL();
   3785     sp<NotificationListener> listener;
   3786     {
   3787         Mutex::Autolock l(mOutputLock);
   3788         listener = mListener.promote();
   3789     }
   3790 
   3791     if (msg == NULL) {
   3792         SET_ERR("HAL sent NULL notify message!");
   3793         return;
   3794     }
   3795 
   3796     switch (msg->type) {
   3797         case CAMERA3_MSG_ERROR: {
   3798             notifyError(msg->message.error, listener);
   3799             break;
   3800         }
   3801         case CAMERA3_MSG_SHUTTER: {
   3802             notifyShutter(msg->message.shutter, listener);
   3803             break;
   3804         }
   3805         default:
   3806             SET_ERR("Unknown notify message from HAL: %d",
   3807                     msg->type);
   3808     }
   3809 }
   3810 
   3811 void Camera3Device::notifyError(const camera3_error_msg_t &msg,
   3812         sp<NotificationListener> listener) {
   3813     ATRACE_CALL();
   3814     // Map camera HAL error codes to ICameraDeviceCallback error codes
   3815     // Index into this with the HAL error code
   3816     static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
   3817         // 0 = Unused error code
   3818         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
   3819         // 1 = CAMERA3_MSG_ERROR_DEVICE
   3820         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
   3821         // 2 = CAMERA3_MSG_ERROR_REQUEST
   3822         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
   3823         // 3 = CAMERA3_MSG_ERROR_RESULT
   3824         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
   3825         // 4 = CAMERA3_MSG_ERROR_BUFFER
   3826         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
   3827     };
   3828 
   3829     int32_t errorCode =
   3830             ((msg.error_code >= 0) &&
   3831                     (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
   3832             halErrorMap[msg.error_code] :
   3833             hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
   3834 
   3835     int streamId = 0;
   3836     String16 physicalCameraId;
   3837     if (msg.error_stream != NULL) {
   3838         Camera3Stream *stream =
   3839                 Camera3Stream::cast(msg.error_stream);
   3840         streamId = stream->getId();
   3841         physicalCameraId = String16(stream->physicalCameraId());
   3842     }
   3843     ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
   3844             mId.string(), __FUNCTION__, msg.frame_number,
   3845             streamId, msg.error_code);
   3846 
   3847     CaptureResultExtras resultExtras;
   3848     switch (errorCode) {
   3849         case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
   3850             // SET_ERR calls notifyError
   3851             SET_ERR("Camera HAL reported serious device error");
   3852             break;
   3853         case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
   3854         case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
   3855         case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
   3856             {
   3857                 Mutex::Autolock l(mInFlightLock);
   3858                 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
   3859                 if (idx >= 0) {
   3860                     InFlightRequest &r = mInFlightMap.editValueAt(idx);
   3861                     r.requestStatus = msg.error_code;
   3862                     resultExtras = r.resultExtras;
   3863                     bool logicalDeviceResultError = false;
   3864                     if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
   3865                             errorCode) {
   3866                         if (physicalCameraId.size() > 0) {
   3867                             String8 cameraId(physicalCameraId);
   3868                             if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
   3869                                 ALOGE("%s: Reported result failure for physical camera device: %s "
   3870                                         " which is not part of the respective request!",
   3871                                         __FUNCTION__, cameraId.string());
   3872                                 break;
   3873                             }
   3874                             resultExtras.errorPhysicalCameraId = physicalCameraId;
   3875                         } else {
   3876                             logicalDeviceResultError = true;
   3877                         }
   3878                     }
   3879 
   3880                     if (logicalDeviceResultError
   3881                             ||  hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
   3882                             errorCode) {
   3883                         r.skipResultMetadata = true;
   3884                     }
   3885                     if (logicalDeviceResultError) {
   3886                         // In case of missing result check whether the buffers
   3887                         // returned. If they returned, then remove inflight
   3888                         // request.
   3889                         // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
   3890                         //       otherwise we are depending on HAL to send the buffers back after
   3891                         //       calling notifyError. Not sure if that's in the spec.
   3892                         removeInFlightRequestIfReadyLocked(idx);
   3893                     }
   3894                 } else {
   3895                     resultExtras.frameNumber = msg.frame_number;
   3896                     ALOGE("Camera %s: %s: cannot find in-flight request on "
   3897                             "frame %" PRId64 " error", mId.string(), __FUNCTION__,
   3898                             resultExtras.frameNumber);
   3899                 }
   3900             }
   3901             resultExtras.errorStreamId = streamId;
   3902             if (listener != NULL) {
   3903                 listener->notifyError(errorCode, resultExtras);
   3904             } else {
   3905                 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
   3906             }
   3907             break;
   3908         default:
   3909             // SET_ERR calls notifyError
   3910             SET_ERR("Unknown error message from HAL: %d", msg.error_code);
   3911             break;
   3912     }
   3913 }
   3914 
   3915 void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
   3916         sp<NotificationListener> listener) {
   3917     ATRACE_CALL();
   3918     ssize_t idx;
   3919 
   3920     // Set timestamp for the request in the in-flight tracking
   3921     // and get the request ID to send upstream
   3922     {
   3923         Mutex::Autolock l(mInFlightLock);
   3924         idx = mInFlightMap.indexOfKey(msg.frame_number);
   3925         if (idx >= 0) {
   3926             InFlightRequest &r = mInFlightMap.editValueAt(idx);
   3927 
   3928             // Verify ordering of shutter notifications
   3929             {
   3930                 Mutex::Autolock l(mOutputLock);
   3931                 // TODO: need to track errors for tighter bounds on expected frame number.
   3932                 if (r.hasInputBuffer) {
   3933                     if (msg.frame_number < mNextReprocessShutterFrameNumber) {
   3934                         SET_ERR("Reprocess shutter notification out-of-order. Expected "
   3935                                 "notification for frame %d, got frame %d",
   3936                                 mNextReprocessShutterFrameNumber, msg.frame_number);
   3937                         return;
   3938                     }
   3939                     mNextReprocessShutterFrameNumber = msg.frame_number + 1;
   3940                 } else if (r.zslCapture && r.stillCapture) {
   3941                     if (msg.frame_number < mNextZslStillShutterFrameNumber) {
   3942                         SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
   3943                                 "notification for frame %d, got frame %d",
   3944                                 mNextZslStillShutterFrameNumber, msg.frame_number);
   3945                         return;
   3946                     }
   3947                     mNextZslStillShutterFrameNumber = msg.frame_number + 1;
   3948                 } else {
   3949                     if (msg.frame_number < mNextShutterFrameNumber) {
   3950                         SET_ERR("Shutter notification out-of-order. Expected "
   3951                                 "notification for frame %d, got frame %d",
   3952                                 mNextShutterFrameNumber, msg.frame_number);
   3953                         return;
   3954                     }
   3955                     mNextShutterFrameNumber = msg.frame_number + 1;
   3956                 }
   3957             }
   3958 
   3959             r.shutterTimestamp = msg.timestamp;
   3960             if (r.hasCallback) {
   3961                 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
   3962                     mId.string(), __FUNCTION__,
   3963                     msg.frame_number, r.resultExtras.requestId, msg.timestamp);
   3964                 // Call listener, if any
   3965                 if (listener != NULL) {
   3966                     listener->notifyShutter(r.resultExtras, msg.timestamp);
   3967                 }
   3968                 // send pending result and buffers
   3969                 sendCaptureResult(r.pendingMetadata, r.resultExtras,
   3970                     r.collectedPartialResult, msg.frame_number,
   3971                     r.hasInputBuffer, r.zslCapture && r.stillCapture,
   3972                     r.physicalMetadatas);
   3973             }
   3974             bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
   3975             returnOutputBuffers(r.pendingOutputBuffers.array(),
   3976                     r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
   3977                     r.outputSurfaces, r.resultExtras);
   3978             r.pendingOutputBuffers.clear();
   3979 
   3980             removeInFlightRequestIfReadyLocked(idx);
   3981         }
   3982     }
   3983     if (idx < 0) {
   3984         SET_ERR("Shutter notification for non-existent frame number %d",
   3985                 msg.frame_number);
   3986     }
   3987 }
   3988 
   3989 CameraMetadata Camera3Device::getLatestRequestLocked() {
   3990     ALOGV("%s", __FUNCTION__);
   3991 
   3992     CameraMetadata retVal;
   3993 
   3994     if (mRequestThread != NULL) {
   3995         retVal = mRequestThread->getLatestRequest();
   3996     }
   3997 
   3998     return retVal;
   3999 }
   4000 
   4001 
   4002 void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
   4003         int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
   4004         const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
   4005 
   4006     mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
   4007             physicalMetadata);
   4008 }
   4009 
   4010 /**
   4011  * HalInterface inner class methods
   4012  */
   4013 
   4014 Camera3Device::HalInterface::HalInterface(
   4015             sp<ICameraDeviceSession> &session,
   4016             std::shared_ptr<RequestMetadataQueue> queue,
   4017             bool useHalBufManager) :
   4018         mHidlSession(session),
   4019         mRequestMetadataQueue(queue),
   4020         mUseHalBufManager(useHalBufManager),
   4021         mIsReconfigurationQuerySupported(true) {
   4022     // Check with hardware service manager if we can downcast these interfaces
   4023     // Somewhat expensive, so cache the results at startup
   4024     auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
   4025     if (castResult_3_5.isOk()) {
   4026         mHidlSession_3_5 = castResult_3_5;
   4027     }
   4028     auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
   4029     if (castResult_3_4.isOk()) {
   4030         mHidlSession_3_4 = castResult_3_4;
   4031     }
   4032     auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
   4033     if (castResult_3_3.isOk()) {
   4034         mHidlSession_3_3 = castResult_3_3;
   4035     }
   4036 }
   4037 
   4038 Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
   4039 
   4040 Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
   4041         mHidlSession(other.mHidlSession),
   4042         mRequestMetadataQueue(other.mRequestMetadataQueue),
   4043         mUseHalBufManager(other.mUseHalBufManager) {}
   4044 
   4045 bool Camera3Device::HalInterface::valid() {
   4046     return (mHidlSession != nullptr);
   4047 }
   4048 
   4049 void Camera3Device::HalInterface::clear() {
   4050     mHidlSession_3_5.clear();
   4051     mHidlSession_3_4.clear();
   4052     mHidlSession_3_3.clear();
   4053     mHidlSession.clear();
   4054 }
   4055 
   4056 status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
   4057         camera3_request_template_t templateId,
   4058         /*out*/ camera_metadata_t **requestTemplate) {
   4059     ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
   4060     if (!valid()) return INVALID_OPERATION;
   4061     status_t res = OK;
   4062 
   4063     common::V1_0::Status status;
   4064 
   4065     auto requestCallback = [&status, &requestTemplate]
   4066             (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
   4067             status = s;
   4068             if (status == common::V1_0::Status::OK) {
   4069                 const camera_metadata *r =
   4070                         reinterpret_cast<const camera_metadata_t*>(request.data());
   4071                 size_t expectedSize = request.size();
   4072                 int ret = validate_camera_metadata_structure(r, &expectedSize);
   4073                 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
   4074                     *requestTemplate = clone_camera_metadata(r);
   4075                     if (*requestTemplate == nullptr) {
   4076                         ALOGE("%s: Unable to clone camera metadata received from HAL",
   4077                                 __FUNCTION__);
   4078                         status = common::V1_0::Status::INTERNAL_ERROR;
   4079                     }
   4080                 } else {
   4081                     ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
   4082                     status = common::V1_0::Status::INTERNAL_ERROR;
   4083                 }
   4084             }
   4085         };
   4086     hardware::Return<void> err;
   4087     RequestTemplate id;
   4088     switch (templateId) {
   4089         case CAMERA3_TEMPLATE_PREVIEW:
   4090             id = RequestTemplate::PREVIEW;
   4091             break;
   4092         case CAMERA3_TEMPLATE_STILL_CAPTURE:
   4093             id = RequestTemplate::STILL_CAPTURE;
   4094             break;
   4095         case CAMERA3_TEMPLATE_VIDEO_RECORD:
   4096             id = RequestTemplate::VIDEO_RECORD;
   4097             break;
   4098         case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
   4099             id = RequestTemplate::VIDEO_SNAPSHOT;
   4100             break;
   4101         case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
   4102             id = RequestTemplate::ZERO_SHUTTER_LAG;
   4103             break;
   4104         case CAMERA3_TEMPLATE_MANUAL:
   4105             id = RequestTemplate::MANUAL;
   4106             break;
   4107         default:
   4108             // Unknown template ID, or this HAL is too old to support it
   4109             return BAD_VALUE;
   4110     }
   4111     err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
   4112 
   4113     if (!err.isOk()) {
   4114         ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4115         res = DEAD_OBJECT;
   4116     } else {
   4117         res = CameraProviderManager::mapToStatusT(status);
   4118     }
   4119 
   4120     return res;
   4121 }
   4122 
   4123 bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
   4124         CameraMetadata& newSessionParams) {
   4125     // We do reconfiguration by default;
   4126     bool ret = true;
   4127     if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
   4128         android::hardware::hidl_vec<uint8_t> oldParams, newParams;
   4129         camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
   4130                 oldSessionParams.getAndLock());
   4131         camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
   4132                 newSessionParams.getAndLock());
   4133         oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
   4134                 get_camera_metadata_size(oldSessioMeta));
   4135         newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
   4136                 get_camera_metadata_size(newSessioMeta));
   4137         hardware::camera::common::V1_0::Status callStatus;
   4138         bool required;
   4139         auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
   4140                 bool requiredFlag) {
   4141             callStatus = s;
   4142             required = requiredFlag;
   4143         };
   4144         auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
   4145         oldSessionParams.unlock(oldSessioMeta);
   4146         newSessionParams.unlock(newSessioMeta);
   4147         if (err.isOk()) {
   4148             switch (callStatus) {
   4149                 case hardware::camera::common::V1_0::Status::OK:
   4150                     ret = required;
   4151                     break;
   4152                 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
   4153                     mIsReconfigurationQuerySupported = false;
   4154                     ret = true;
   4155                     break;
   4156                 default:
   4157                     ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
   4158                     ret = true;
   4159             }
   4160         } else {
   4161             ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
   4162             ret = true;
   4163         }
   4164     }
   4165 
   4166     return ret;
   4167 }
   4168 
   4169 status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
   4170         camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
   4171     ATRACE_NAME("CameraHal::configureStreams");
   4172     if (!valid()) return INVALID_OPERATION;
   4173     status_t res = OK;
   4174 
   4175     // Convert stream config to HIDL
   4176     std::set<int> activeStreams;
   4177     device::V3_2::StreamConfiguration requestedConfiguration3_2;
   4178     device::V3_4::StreamConfiguration requestedConfiguration3_4;
   4179     requestedConfiguration3_2.streams.resize(config->num_streams);
   4180     requestedConfiguration3_4.streams.resize(config->num_streams);
   4181     for (size_t i = 0; i < config->num_streams; i++) {
   4182         device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
   4183         device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
   4184         camera3_stream_t *src = config->streams[i];
   4185 
   4186         Camera3Stream* cam3stream = Camera3Stream::cast(src);
   4187         cam3stream->setBufferFreedListener(this);
   4188         int streamId = cam3stream->getId();
   4189         StreamType streamType;
   4190         switch (src->stream_type) {
   4191             case CAMERA3_STREAM_OUTPUT:
   4192                 streamType = StreamType::OUTPUT;
   4193                 break;
   4194             case CAMERA3_STREAM_INPUT:
   4195                 streamType = StreamType::INPUT;
   4196                 break;
   4197             default:
   4198                 ALOGE("%s: Stream %d: Unsupported stream type %d",
   4199                         __FUNCTION__, streamId, config->streams[i]->stream_type);
   4200                 return BAD_VALUE;
   4201         }
   4202         dst3_2.id = streamId;
   4203         dst3_2.streamType = streamType;
   4204         dst3_2.width = src->width;
   4205         dst3_2.height = src->height;
   4206         dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
   4207         dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
   4208         // For HidlSession version 3.5 or newer, the format and dataSpace sent
   4209         // to HAL are original, not the overriden ones.
   4210         if (mHidlSession_3_5 != nullptr) {
   4211             dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
   4212                     cam3stream->getOriginalFormat() : src->format);
   4213             dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
   4214                     cam3stream->getOriginalDataSpace() : src->data_space);
   4215         } else {
   4216             dst3_2.format = mapToPixelFormat(src->format);
   4217             dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
   4218         }
   4219         dst3_4.v3_2 = dst3_2;
   4220         dst3_4.bufferSize = bufferSizes[i];
   4221         if (src->physical_camera_id != nullptr) {
   4222             dst3_4.physicalCameraId = src->physical_camera_id;
   4223         }
   4224 
   4225         activeStreams.insert(streamId);
   4226         // Create Buffer ID map if necessary
   4227         if (mBufferIdMaps.count(streamId) == 0) {
   4228             mBufferIdMaps.emplace(streamId, BufferIdMap{});
   4229         }
   4230     }
   4231     // remove BufferIdMap for deleted streams
   4232     for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
   4233         int streamId = it->first;
   4234         bool active = activeStreams.count(streamId) > 0;
   4235         if (!active) {
   4236             it = mBufferIdMaps.erase(it);
   4237         } else {
   4238             ++it;
   4239         }
   4240     }
   4241 
   4242     StreamConfigurationMode operationMode;
   4243     res = mapToStreamConfigurationMode(
   4244             (camera3_stream_configuration_mode_t) config->operation_mode,
   4245             /*out*/ &operationMode);
   4246     if (res != OK) {
   4247         return res;
   4248     }
   4249     requestedConfiguration3_2.operationMode = operationMode;
   4250     requestedConfiguration3_4.operationMode = operationMode;
   4251     requestedConfiguration3_4.sessionParams.setToExternal(
   4252             reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
   4253             get_camera_metadata_size(sessionParams));
   4254 
   4255     // Invoke configureStreams
   4256     device::V3_3::HalStreamConfiguration finalConfiguration;
   4257     device::V3_4::HalStreamConfiguration finalConfiguration3_4;
   4258     common::V1_0::Status status;
   4259 
   4260     auto configStream34Cb = [&status, &finalConfiguration3_4]
   4261             (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
   4262                 finalConfiguration3_4 = halConfiguration;
   4263                 status = s;
   4264             };
   4265 
   4266     auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
   4267             (hardware::Return<void>& err) -> status_t {
   4268                 if (!err.isOk()) {
   4269                     ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4270                     return DEAD_OBJECT;
   4271                 }
   4272                 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
   4273                 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
   4274                     finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
   4275                 }
   4276                 return OK;
   4277             };
   4278 
   4279     // See which version of HAL we have
   4280     if (mHidlSession_3_5 != nullptr) {
   4281         ALOGV("%s: v3.5 device found", __FUNCTION__);
   4282         device::V3_5::StreamConfiguration requestedConfiguration3_5;
   4283         requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
   4284         requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
   4285         auto err = mHidlSession_3_5->configureStreams_3_5(
   4286                 requestedConfiguration3_5, configStream34Cb);
   4287         res = postprocConfigStream34(err);
   4288         if (res != OK) {
   4289             return res;
   4290         }
   4291     } else if (mHidlSession_3_4 != nullptr) {
   4292         // We do; use v3.4 for the call
   4293         ALOGV("%s: v3.4 device found", __FUNCTION__);
   4294         auto err = mHidlSession_3_4->configureStreams_3_4(
   4295                 requestedConfiguration3_4, configStream34Cb);
   4296         res = postprocConfigStream34(err);
   4297         if (res != OK) {
   4298             return res;
   4299         }
   4300     } else if (mHidlSession_3_3 != nullptr) {
   4301         // We do; use v3.3 for the call
   4302         ALOGV("%s: v3.3 device found", __FUNCTION__);
   4303         auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
   4304             [&status, &finalConfiguration]
   4305             (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
   4306                 finalConfiguration = halConfiguration;
   4307                 status = s;
   4308             });
   4309         if (!err.isOk()) {
   4310             ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4311             return DEAD_OBJECT;
   4312         }
   4313     } else {
   4314         // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
   4315         ALOGV("%s: v3.2 device found", __FUNCTION__);
   4316         HalStreamConfiguration finalConfiguration_3_2;
   4317         auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
   4318                 [&status, &finalConfiguration_3_2]
   4319                 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
   4320                     finalConfiguration_3_2 = halConfiguration;
   4321                     status = s;
   4322                 });
   4323         if (!err.isOk()) {
   4324             ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4325             return DEAD_OBJECT;
   4326         }
   4327         finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
   4328         for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
   4329             finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
   4330             finalConfiguration.streams[i].overrideDataSpace =
   4331                     requestedConfiguration3_2.streams[i].dataSpace;
   4332         }
   4333     }
   4334 
   4335     if (status != common::V1_0::Status::OK ) {
   4336         return CameraProviderManager::mapToStatusT(status);
   4337     }
   4338 
   4339     // And convert output stream configuration from HIDL
   4340 
   4341     for (size_t i = 0; i < config->num_streams; i++) {
   4342         camera3_stream_t *dst = config->streams[i];
   4343         int streamId = Camera3Stream::cast(dst)->getId();
   4344 
   4345         // Start scan at i, with the assumption that the stream order matches
   4346         size_t realIdx = i;
   4347         bool found = false;
   4348         size_t halStreamCount = finalConfiguration.streams.size();
   4349         for (size_t idx = 0; idx < halStreamCount; idx++) {
   4350             if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
   4351                 found = true;
   4352                 break;
   4353             }
   4354             realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
   4355         }
   4356         if (!found) {
   4357             ALOGE("%s: Stream %d not found in stream configuration response from HAL",
   4358                     __FUNCTION__, streamId);
   4359             return INVALID_OPERATION;
   4360         }
   4361         device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
   4362 
   4363         Camera3Stream* dstStream = Camera3Stream::cast(dst);
   4364         int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
   4365         android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
   4366 
   4367         if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
   4368             dstStream->setFormatOverride(false);
   4369             dstStream->setDataSpaceOverride(false);
   4370             if (dst->format != overrideFormat) {
   4371                 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
   4372                         streamId, dst->format);
   4373             }
   4374             if (dst->data_space != overrideDataSpace) {
   4375                 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
   4376                         streamId, dst->format);
   4377             }
   4378         } else {
   4379             bool needFormatOverride =
   4380                     requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
   4381             bool needDataspaceOverride =
   4382                     requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
   4383             // Override allowed with IMPLEMENTATION_DEFINED
   4384             dstStream->setFormatOverride(needFormatOverride);
   4385             dstStream->setDataSpaceOverride(needDataspaceOverride);
   4386             dst->format = overrideFormat;
   4387             dst->data_space = overrideDataSpace;
   4388         }
   4389 
   4390         if (dst->stream_type == CAMERA3_STREAM_INPUT) {
   4391             if (src.v3_2.producerUsage != 0) {
   4392                 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
   4393                         __FUNCTION__, streamId);
   4394                 return INVALID_OPERATION;
   4395             }
   4396             dstStream->setUsage(
   4397                     mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
   4398         } else {
   4399             // OUTPUT
   4400             if (src.v3_2.consumerUsage != 0) {
   4401                 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
   4402                         __FUNCTION__, streamId);
   4403                 return INVALID_OPERATION;
   4404             }
   4405             dstStream->setUsage(
   4406                     mapProducerToFrameworkUsage(src.v3_2.producerUsage));
   4407         }
   4408         dst->max_buffers = src.v3_2.maxBuffers;
   4409     }
   4410 
   4411     return res;
   4412 }
   4413 
   4414 status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
   4415         /*out*/device::V3_2::CaptureRequest* captureRequest,
   4416         /*out*/std::vector<native_handle_t*>* handlesCreated,
   4417         /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
   4418     ATRACE_CALL();
   4419     if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
   4420         ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
   4421                 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
   4422         return BAD_VALUE;
   4423     }
   4424 
   4425     captureRequest->frameNumber = request->frame_number;
   4426 
   4427     captureRequest->fmqSettingsSize = 0;
   4428 
   4429     {
   4430         std::lock_guard<std::mutex> lock(mInflightLock);
   4431         if (request->input_buffer != nullptr) {
   4432             int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
   4433             buffer_handle_t buf = *(request->input_buffer->buffer);
   4434             auto pair = getBufferId(buf, streamId);
   4435             bool isNewBuffer = pair.first;
   4436             uint64_t bufferId = pair.second;
   4437             captureRequest->inputBuffer.streamId = streamId;
   4438             captureRequest->inputBuffer.bufferId = bufferId;
   4439             captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
   4440             captureRequest->inputBuffer.status = BufferStatus::OK;
   4441             native_handle_t *acquireFence = nullptr;
   4442             if (request->input_buffer->acquire_fence != -1) {
   4443                 acquireFence = native_handle_create(1,0);
   4444                 acquireFence->data[0] = request->input_buffer->acquire_fence;
   4445                 handlesCreated->push_back(acquireFence);
   4446             }
   4447             captureRequest->inputBuffer.acquireFence = acquireFence;
   4448             captureRequest->inputBuffer.releaseFence = nullptr;
   4449 
   4450             pushInflightBufferLocked(captureRequest->frameNumber, streamId,
   4451                     request->input_buffer->buffer);
   4452             inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
   4453         } else {
   4454             captureRequest->inputBuffer.streamId = -1;
   4455             captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
   4456         }
   4457 
   4458         captureRequest->outputBuffers.resize(request->num_output_buffers);
   4459         for (size_t i = 0; i < request->num_output_buffers; i++) {
   4460             const camera3_stream_buffer_t *src = request->output_buffers + i;
   4461             StreamBuffer &dst = captureRequest->outputBuffers[i];
   4462             int32_t streamId = Camera3Stream::cast(src->stream)->getId();
   4463             if (src->buffer != nullptr) {
   4464                 buffer_handle_t buf = *(src->buffer);
   4465                 auto pair = getBufferId(buf, streamId);
   4466                 bool isNewBuffer = pair.first;
   4467                 dst.bufferId = pair.second;
   4468                 dst.buffer = isNewBuffer ? buf : nullptr;
   4469                 native_handle_t *acquireFence = nullptr;
   4470                 if (src->acquire_fence != -1) {
   4471                     acquireFence = native_handle_create(1,0);
   4472                     acquireFence->data[0] = src->acquire_fence;
   4473                     handlesCreated->push_back(acquireFence);
   4474                 }
   4475                 dst.acquireFence = acquireFence;
   4476             } else if (mUseHalBufManager) {
   4477                 // HAL buffer management path
   4478                 dst.bufferId = BUFFER_ID_NO_BUFFER;
   4479                 dst.buffer = nullptr;
   4480                 dst.acquireFence = nullptr;
   4481             } else {
   4482                 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
   4483                 return BAD_VALUE;
   4484             }
   4485             dst.streamId = streamId;
   4486             dst.status = BufferStatus::OK;
   4487             dst.releaseFence = nullptr;
   4488 
   4489             // Output buffers are empty when using HAL buffer manager
   4490             if (!mUseHalBufManager) {
   4491                 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
   4492                 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
   4493             }
   4494         }
   4495     }
   4496     return OK;
   4497 }
   4498 
   4499 void Camera3Device::HalInterface::cleanupNativeHandles(
   4500         std::vector<native_handle_t*> *handles, bool closeFd) {
   4501     if (handles == nullptr) {
   4502         return;
   4503     }
   4504     if (closeFd) {
   4505         for (auto& handle : *handles) {
   4506             native_handle_close(handle);
   4507         }
   4508     }
   4509     for (auto& handle : *handles) {
   4510         native_handle_delete(handle);
   4511     }
   4512     handles->clear();
   4513     return;
   4514 }
   4515 
   4516 status_t Camera3Device::HalInterface::processBatchCaptureRequests(
   4517         std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
   4518     ATRACE_NAME("CameraHal::processBatchCaptureRequests");
   4519     if (!valid()) return INVALID_OPERATION;
   4520 
   4521     sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
   4522     auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
   4523     if (castResult_3_4.isOk()) {
   4524         hidlSession_3_4 = castResult_3_4;
   4525     }
   4526 
   4527     hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
   4528     hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
   4529     size_t batchSize = requests.size();
   4530     if (hidlSession_3_4 != nullptr) {
   4531         captureRequests_3_4.resize(batchSize);
   4532     } else {
   4533         captureRequests.resize(batchSize);
   4534     }
   4535     std::vector<native_handle_t*> handlesCreated;
   4536     std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
   4537 
   4538     status_t res = OK;
   4539     for (size_t i = 0; i < batchSize; i++) {
   4540         if (hidlSession_3_4 != nullptr) {
   4541             res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
   4542                     /*out*/&handlesCreated, /*out*/&inflightBuffers);
   4543         } else {
   4544             res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
   4545                     /*out*/&handlesCreated, /*out*/&inflightBuffers);
   4546         }
   4547         if (res != OK) {
   4548             popInflightBuffers(inflightBuffers);
   4549             cleanupNativeHandles(&handlesCreated);
   4550             return res;
   4551         }
   4552     }
   4553 
   4554     std::vector<device::V3_2::BufferCache> cachesToRemove;
   4555     {
   4556         std::lock_guard<std::mutex> lock(mBufferIdMapLock);
   4557         for (auto& pair : mFreedBuffers) {
   4558             // The stream might have been removed since onBufferFreed
   4559             if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
   4560                 cachesToRemove.push_back({pair.first, pair.second});
   4561             }
   4562         }
   4563         mFreedBuffers.clear();
   4564     }
   4565 
   4566     common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
   4567     *numRequestProcessed = 0;
   4568 
   4569     // Write metadata to FMQ.
   4570     for (size_t i = 0; i < batchSize; i++) {
   4571         camera3_capture_request_t* request = requests[i];
   4572         device::V3_2::CaptureRequest* captureRequest;
   4573         if (hidlSession_3_4 != nullptr) {
   4574             captureRequest = &captureRequests_3_4[i].v3_2;
   4575         } else {
   4576             captureRequest = &captureRequests[i];
   4577         }
   4578 
   4579         if (request->settings != nullptr) {
   4580             size_t settingsSize = get_camera_metadata_size(request->settings);
   4581             if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
   4582                     reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
   4583                 captureRequest->settings.resize(0);
   4584                 captureRequest->fmqSettingsSize = settingsSize;
   4585             } else {
   4586                 if (mRequestMetadataQueue != nullptr) {
   4587                     ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
   4588                 }
   4589                 captureRequest->settings.setToExternal(
   4590                         reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
   4591                         get_camera_metadata_size(request->settings));
   4592                 captureRequest->fmqSettingsSize = 0u;
   4593             }
   4594         } else {
   4595             // A null request settings maps to a size-0 CameraMetadata
   4596             captureRequest->settings.resize(0);
   4597             captureRequest->fmqSettingsSize = 0u;
   4598         }
   4599 
   4600         if (hidlSession_3_4 != nullptr) {
   4601             captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
   4602             for (size_t j = 0; j < request->num_physcam_settings; j++) {
   4603                 if (request->physcam_settings != nullptr) {
   4604                     size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
   4605                     if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
   4606                                 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
   4607                                 settingsSize)) {
   4608                         captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
   4609                         captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
   4610                             settingsSize;
   4611                     } else {
   4612                         if (mRequestMetadataQueue != nullptr) {
   4613                             ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
   4614                         }
   4615                         captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
   4616                                 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
   4617                                         request->physcam_settings[j])),
   4618                                 get_camera_metadata_size(request->physcam_settings[j]));
   4619                         captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
   4620                     }
   4621                 } else {
   4622                     captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
   4623                     captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
   4624                 }
   4625                 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
   4626                     request->physcam_id[j];
   4627             }
   4628         }
   4629     }
   4630 
   4631     hardware::details::return_status err;
   4632     auto resultCallback =
   4633         [&status, &numRequestProcessed] (auto s, uint32_t n) {
   4634                 status = s;
   4635                 *numRequestProcessed = n;
   4636         };
   4637     if (hidlSession_3_4 != nullptr) {
   4638         err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
   4639                                                          resultCallback);
   4640     } else {
   4641         err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
   4642                                                   resultCallback);
   4643     }
   4644     if (!err.isOk()) {
   4645         ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4646         status = common::V1_0::Status::CAMERA_DISCONNECTED;
   4647     }
   4648 
   4649     if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
   4650         ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
   4651                 __FUNCTION__, *numRequestProcessed, batchSize);
   4652         status = common::V1_0::Status::INTERNAL_ERROR;
   4653     }
   4654 
   4655     res = CameraProviderManager::mapToStatusT(status);
   4656     if (res == OK) {
   4657         if (mHidlSession->isRemote()) {
   4658             // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
   4659             // sent to camera HAL processes)
   4660             cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
   4661         } else {
   4662             // In passthrough mode the FDs are now owned by HAL
   4663             cleanupNativeHandles(&handlesCreated);
   4664         }
   4665     } else {
   4666         popInflightBuffers(inflightBuffers);
   4667         cleanupNativeHandles(&handlesCreated);
   4668     }
   4669     return res;
   4670 }
   4671 
   4672 status_t Camera3Device::HalInterface::flush() {
   4673     ATRACE_NAME("CameraHal::flush");
   4674     if (!valid()) return INVALID_OPERATION;
   4675     status_t res = OK;
   4676 
   4677     auto err = mHidlSession->flush();
   4678     if (!err.isOk()) {
   4679         ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4680         res = DEAD_OBJECT;
   4681     } else {
   4682         res = CameraProviderManager::mapToStatusT(err);
   4683     }
   4684 
   4685     return res;
   4686 }
   4687 
   4688 status_t Camera3Device::HalInterface::dump(int /*fd*/) {
   4689     ATRACE_NAME("CameraHal::dump");
   4690     if (!valid()) return INVALID_OPERATION;
   4691 
   4692     // Handled by CameraProviderManager::dump
   4693 
   4694     return OK;
   4695 }
   4696 
   4697 status_t Camera3Device::HalInterface::close() {
   4698     ATRACE_NAME("CameraHal::close()");
   4699     if (!valid()) return INVALID_OPERATION;
   4700     status_t res = OK;
   4701 
   4702     auto err = mHidlSession->close();
   4703     // Interface will be dead shortly anyway, so don't log errors
   4704     if (!err.isOk()) {
   4705         res = DEAD_OBJECT;
   4706     }
   4707 
   4708     return res;
   4709 }
   4710 
   4711 void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
   4712     ATRACE_NAME("CameraHal::signalPipelineDrain");
   4713     if (!valid() || mHidlSession_3_5 == nullptr) {
   4714         ALOGE("%s called on invalid camera!", __FUNCTION__);
   4715         return;
   4716     }
   4717 
   4718     auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
   4719     if (!err.isOk()) {
   4720         ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
   4721         return;
   4722     }
   4723 }
   4724 
   4725 void Camera3Device::HalInterface::getInflightBufferKeys(
   4726         std::vector<std::pair<int32_t, int32_t>>* out) {
   4727     std::lock_guard<std::mutex> lock(mInflightLock);
   4728     out->clear();
   4729     out->reserve(mInflightBufferMap.size());
   4730     for (auto& pair : mInflightBufferMap) {
   4731         uint64_t key = pair.first;
   4732         int32_t streamId = key & 0xFFFFFFFF;
   4733         int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
   4734         out->push_back(std::make_pair(frameNumber, streamId));
   4735     }
   4736     return;
   4737 }
   4738 
   4739 void Camera3Device::HalInterface::getInflightRequestBufferKeys(
   4740         std::vector<uint64_t>* out) {
   4741     std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
   4742     out->clear();
   4743     out->reserve(mRequestedBuffers.size());
   4744     for (auto& pair : mRequestedBuffers) {
   4745         out->push_back(pair.first);
   4746     }
   4747     return;
   4748 }
   4749 
   4750 status_t Camera3Device::HalInterface::pushInflightBufferLocked(
   4751         int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
   4752     uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
   4753     mInflightBufferMap[key] = buffer;
   4754     return OK;
   4755 }
   4756 
   4757 status_t Camera3Device::HalInterface::popInflightBuffer(
   4758         int32_t frameNumber, int32_t streamId,
   4759         /*out*/ buffer_handle_t **buffer) {
   4760     std::lock_guard<std::mutex> lock(mInflightLock);
   4761 
   4762     uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
   4763     auto it = mInflightBufferMap.find(key);
   4764     if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
   4765     if (buffer != nullptr) {
   4766         *buffer = it->second;
   4767     }
   4768     mInflightBufferMap.erase(it);
   4769     return OK;
   4770 }
   4771 
   4772 void Camera3Device::HalInterface::popInflightBuffers(
   4773         const std::vector<std::pair<int32_t, int32_t>>& buffers) {
   4774     for (const auto& pair : buffers) {
   4775         int32_t frameNumber = pair.first;
   4776         int32_t streamId = pair.second;
   4777         popInflightBuffer(frameNumber, streamId, nullptr);
   4778     }
   4779 }
   4780 
   4781 status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
   4782         uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
   4783     std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
   4784     auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
   4785     if (!pair.second) {
   4786         ALOGE("%s: bufId %" PRIu64 " is already inflight!",
   4787                 __FUNCTION__, bufferId);
   4788         return BAD_VALUE;
   4789     }
   4790     return OK;
   4791 }
   4792 
   4793 // Find and pop a buffer_handle_t based on bufferId
   4794 status_t Camera3Device::HalInterface::popInflightRequestBuffer(
   4795         uint64_t bufferId,
   4796         /*out*/ buffer_handle_t** buffer,
   4797         /*optional out*/ int32_t* streamId) {
   4798     if (buffer == nullptr) {
   4799         ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
   4800         return BAD_VALUE;
   4801     }
   4802     std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
   4803     auto it = mRequestedBuffers.find(bufferId);
   4804     if (it == mRequestedBuffers.end()) {
   4805         ALOGE("%s: bufId %" PRIu64 " is not inflight!",
   4806                 __FUNCTION__, bufferId);
   4807         return BAD_VALUE;
   4808     }
   4809     *buffer = it->second.second;
   4810     if (streamId != nullptr) {
   4811         *streamId = it->second.first;
   4812     }
   4813     mRequestedBuffers.erase(it);
   4814     return OK;
   4815 }
   4816 
   4817 std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
   4818         const buffer_handle_t& buf, int streamId) {
   4819     std::lock_guard<std::mutex> lock(mBufferIdMapLock);
   4820 
   4821     BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
   4822     auto it = bIdMap.find(buf);
   4823     if (it == bIdMap.end()) {
   4824         bIdMap[buf] = mNextBufferId++;
   4825         ALOGV("stream %d now have %zu buffer caches, buf %p",
   4826                 streamId, bIdMap.size(), buf);
   4827         return std::make_pair(true, mNextBufferId - 1);
   4828     } else {
   4829         return std::make_pair(false, it->second);
   4830     }
   4831 }
   4832 
   4833 void Camera3Device::HalInterface::onBufferFreed(
   4834         int streamId, const native_handle_t* handle) {
   4835     std::lock_guard<std::mutex> lock(mBufferIdMapLock);
   4836     uint64_t bufferId = BUFFER_ID_NO_BUFFER;
   4837     auto mapIt = mBufferIdMaps.find(streamId);
   4838     if (mapIt == mBufferIdMaps.end()) {
   4839         // streamId might be from a deleted stream here
   4840         ALOGI("%s: stream %d has been removed",
   4841                 __FUNCTION__, streamId);
   4842         return;
   4843     }
   4844     BufferIdMap& bIdMap = mapIt->second;
   4845     auto it = bIdMap.find(handle);
   4846     if (it == bIdMap.end()) {
   4847         ALOGW("%s: cannot find buffer %p in stream %d",
   4848                 __FUNCTION__, handle, streamId);
   4849         return;
   4850     } else {
   4851         bufferId = it->second;
   4852         bIdMap.erase(it);
   4853         ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
   4854                 __FUNCTION__, streamId, bIdMap.size(), handle);
   4855     }
   4856     mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
   4857 }
   4858 
   4859 void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
   4860     std::lock_guard<std::mutex> lock(mBufferIdMapLock);
   4861     auto mapIt = mBufferIdMaps.find(streamId);
   4862     if (mapIt == mBufferIdMaps.end()) {
   4863         ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
   4864         return;
   4865     }
   4866 
   4867     BufferIdMap& bIdMap = mapIt->second;
   4868     for (const auto& it : bIdMap) {
   4869         uint64_t bufferId = it.second;
   4870         mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
   4871     }
   4872     bIdMap.clear();
   4873 }
   4874 
   4875 /**
   4876  * RequestThread inner class methods
   4877  */
   4878 
   4879 Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
   4880         sp<StatusTracker> statusTracker,
   4881         sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
   4882         bool useHalBufManager) :
   4883         Thread(/*canCallJava*/false),
   4884         mParent(parent),
   4885         mStatusTracker(statusTracker),
   4886         mInterface(interface),
   4887         mListener(nullptr),
   4888         mId(getId(parent)),
   4889         mReconfigured(false),
   4890         mDoPause(false),
   4891         mPaused(true),
   4892         mNotifyPipelineDrain(false),
   4893         mFrameNumber(0),
   4894         mLatestRequestId(NAME_NOT_FOUND),
   4895         mCurrentAfTriggerId(0),
   4896         mCurrentPreCaptureTriggerId(0),
   4897         mRepeatingLastFrameNumber(
   4898             hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
   4899         mPrepareVideoStream(false),
   4900         mConstrainedMode(false),
   4901         mRequestLatency(kRequestLatencyBinSize),
   4902         mSessionParamKeys(sessionParamKeys),
   4903         mLatestSessionParams(sessionParamKeys.size()),
   4904         mUseHalBufManager(useHalBufManager) {
   4905     mStatusId = statusTracker->addComponent();
   4906 }
   4907 
   4908 Camera3Device::RequestThread::~RequestThread() {}
   4909 
   4910 void Camera3Device::RequestThread::setNotificationListener(
   4911         wp<NotificationListener> listener) {
   4912     ATRACE_CALL();
   4913     Mutex::Autolock l(mRequestLock);
   4914     mListener = listener;
   4915 }
   4916 
   4917 void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
   4918         const CameraMetadata& sessionParams) {
   4919     ATRACE_CALL();
   4920     Mutex::Autolock l(mRequestLock);
   4921     mReconfigured = true;
   4922     mLatestSessionParams = sessionParams;
   4923     // Prepare video stream for high speed recording.
   4924     mPrepareVideoStream = isConstrainedHighSpeed;
   4925     mConstrainedMode = isConstrainedHighSpeed;
   4926 }
   4927 
   4928 status_t Camera3Device::RequestThread::queueRequestList(
   4929         List<sp<CaptureRequest> > &requests,
   4930         /*out*/
   4931         int64_t *lastFrameNumber) {
   4932     ATRACE_CALL();
   4933     Mutex::Autolock l(mRequestLock);
   4934     for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
   4935             ++it) {
   4936         mRequestQueue.push_back(*it);
   4937     }
   4938 
   4939     if (lastFrameNumber != NULL) {
   4940         *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
   4941         ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
   4942               __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
   4943               *lastFrameNumber);
   4944     }
   4945 
   4946     unpauseForNewRequests();
   4947 
   4948     return OK;
   4949 }
   4950 
   4951 
   4952 status_t Camera3Device::RequestThread::queueTrigger(
   4953         RequestTrigger trigger[],
   4954         size_t count) {
   4955     ATRACE_CALL();
   4956     Mutex::Autolock l(mTriggerMutex);
   4957     status_t ret;
   4958 
   4959     for (size_t i = 0; i < count; ++i) {
   4960         ret = queueTriggerLocked(trigger[i]);
   4961 
   4962         if (ret != OK) {
   4963             return ret;
   4964         }
   4965     }
   4966 
   4967     return OK;
   4968 }
   4969 
   4970 const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
   4971     static String8 deadId("<DeadDevice>");
   4972     sp<Camera3Device> d = device.promote();
   4973     if (d != nullptr) return d->mId;
   4974     return deadId;
   4975 }
   4976 
   4977 status_t Camera3Device::RequestThread::queueTriggerLocked(
   4978         RequestTrigger trigger) {
   4979 
   4980     uint32_t tag = trigger.metadataTag;
   4981     ssize_t index = mTriggerMap.indexOfKey(tag);
   4982 
   4983     switch (trigger.getTagType()) {
   4984         case TYPE_BYTE:
   4985         // fall-through
   4986         case TYPE_INT32:
   4987             break;
   4988         default:
   4989             ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
   4990                     trigger.getTagType());
   4991             return INVALID_OPERATION;
   4992     }
   4993 
   4994     /**
   4995      * Collect only the latest trigger, since we only have 1 field
   4996      * in the request settings per trigger tag, and can't send more than 1
   4997      * trigger per request.
   4998      */
   4999     if (index != NAME_NOT_FOUND) {
   5000         mTriggerMap.editValueAt(index) = trigger;
   5001     } else {
   5002         mTriggerMap.add(tag, trigger);
   5003     }
   5004 
   5005     return OK;
   5006 }
   5007 
   5008 status_t Camera3Device::RequestThread::setRepeatingRequests(
   5009         const RequestList &requests,
   5010         /*out*/
   5011         int64_t *lastFrameNumber) {
   5012     ATRACE_CALL();
   5013     Mutex::Autolock l(mRequestLock);
   5014     if (lastFrameNumber != NULL) {
   5015         *lastFrameNumber = mRepeatingLastFrameNumber;
   5016     }
   5017     mRepeatingRequests.clear();
   5018     mRepeatingRequests.insert(mRepeatingRequests.begin(),
   5019             requests.begin(), requests.end());
   5020 
   5021     unpauseForNewRequests();
   5022 
   5023     mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
   5024     return OK;
   5025 }
   5026 
   5027 bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
   5028     if (mRepeatingRequests.empty()) {
   5029         return false;
   5030     }
   5031     int32_t requestId = requestIn->mResultExtras.requestId;
   5032     const RequestList &repeatRequests = mRepeatingRequests;
   5033     // All repeating requests are guaranteed to have same id so only check first quest
   5034     const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
   5035     return (firstRequest->mResultExtras.requestId == requestId);
   5036 }
   5037 
   5038 status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
   5039     ATRACE_CALL();
   5040     Mutex::Autolock l(mRequestLock);
   5041     return clearRepeatingRequestsLocked(lastFrameNumber);
   5042 
   5043 }
   5044 
   5045 status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
   5046     mRepeatingRequests.clear();
   5047     if (lastFrameNumber != NULL) {
   5048         *lastFrameNumber = mRepeatingLastFrameNumber;
   5049     }
   5050     mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
   5051     return OK;
   5052 }
   5053 
   5054 status_t Camera3Device::RequestThread::clear(
   5055         /*out*/int64_t *lastFrameNumber) {
   5056     ATRACE_CALL();
   5057     Mutex::Autolock l(mRequestLock);
   5058     ALOGV("RequestThread::%s:", __FUNCTION__);
   5059 
   5060     mRepeatingRequests.clear();
   5061 
   5062     // Send errors for all requests pending in the request queue, including
   5063     // pending repeating requests
   5064     sp<NotificationListener> listener = mListener.promote();
   5065     if (listener != NULL) {
   5066         for (RequestList::iterator it = mRequestQueue.begin();
   5067                  it != mRequestQueue.end(); ++it) {
   5068             // Abort the input buffers for reprocess requests.
   5069             if ((*it)->mInputStream != NULL) {
   5070                 camera3_stream_buffer_t inputBuffer;
   5071                 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
   5072                         /*respectHalLimit*/ false);
   5073                 if (res != OK) {
   5074                     ALOGW("%s: %d: couldn't get input buffer while clearing the request "
   5075                             "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
   5076                 } else {
   5077                     res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
   5078                     if (res != OK) {
   5079                         ALOGE("%s: %d: couldn't return input buffer while clearing the request "
   5080                                 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
   5081                     }
   5082                 }
   5083             }
   5084             // Set the frame number this request would have had, if it
   5085             // had been submitted; this frame number will not be reused.
   5086             // The requestId and burstId fields were set when the request was
   5087             // submitted originally (in convertMetadataListToRequestListLocked)
   5088             (*it)->mResultExtras.frameNumber = mFrameNumber++;
   5089             listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
   5090                     (*it)->mResultExtras);
   5091         }
   5092     }
   5093     mRequestQueue.clear();
   5094 
   5095     Mutex::Autolock al(mTriggerMutex);
   5096     mTriggerMap.clear();
   5097     if (lastFrameNumber != NULL) {
   5098         *lastFrameNumber = mRepeatingLastFrameNumber;
   5099     }
   5100     mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
   5101     return OK;
   5102 }
   5103 
   5104 status_t Camera3Device::RequestThread::flush() {
   5105     ATRACE_CALL();
   5106     Mutex::Autolock l(mFlushLock);
   5107 
   5108     return mInterface->flush();
   5109 }
   5110 
   5111 void Camera3Device::RequestThread::setPaused(bool paused) {
   5112     ATRACE_CALL();
   5113     Mutex::Autolock l(mPauseLock);
   5114     mDoPause = paused;
   5115     mDoPauseSignal.signal();
   5116 }
   5117 
   5118 status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
   5119         int32_t requestId, nsecs_t timeout) {
   5120     ATRACE_CALL();
   5121     Mutex::Autolock l(mLatestRequestMutex);
   5122     status_t res;
   5123     while (mLatestRequestId != requestId) {
   5124         nsecs_t startTime = systemTime();
   5125 
   5126         res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
   5127         if (res != OK) return res;
   5128 
   5129         timeout -= (systemTime() - startTime);
   5130     }
   5131 
   5132     return OK;
   5133 }
   5134 
   5135 void Camera3Device::RequestThread::requestExit() {
   5136     // Call parent to set up shutdown
   5137     Thread::requestExit();
   5138     // The exit from any possible waits
   5139     mDoPauseSignal.signal();
   5140     mRequestSignal.signal();
   5141 
   5142     mRequestLatency.log("ProcessCaptureRequest latency histogram");
   5143     mRequestLatency.reset();
   5144 }
   5145 
   5146 void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
   5147     ATRACE_CALL();
   5148     bool surfaceAbandoned = false;
   5149     int64_t lastFrameNumber = 0;
   5150     sp<NotificationListener> listener;
   5151     {
   5152         Mutex::Autolock l(mRequestLock);
   5153         // Check all streams needed by repeating requests are still valid. Otherwise, stop
   5154         // repeating requests.
   5155         for (const auto& request : mRepeatingRequests) {
   5156             for (const auto& s : request->mOutputStreams) {
   5157                 if (s->isAbandoned()) {
   5158                     surfaceAbandoned = true;
   5159                     clearRepeatingRequestsLocked(&lastFrameNumber);
   5160                     break;
   5161                 }
   5162             }
   5163             if (surfaceAbandoned) {
   5164                 break;
   5165             }
   5166         }
   5167         listener = mListener.promote();
   5168     }
   5169 
   5170     if (listener != NULL && surfaceAbandoned) {
   5171         listener->notifyRepeatingRequestError(lastFrameNumber);
   5172     }
   5173 }
   5174 
   5175 bool Camera3Device::RequestThread::sendRequestsBatch() {
   5176     ATRACE_CALL();
   5177     status_t res;
   5178     size_t batchSize = mNextRequests.size();
   5179     std::vector<camera3_capture_request_t*> requests(batchSize);
   5180     uint32_t numRequestProcessed = 0;
   5181     for (size_t i = 0; i < batchSize; i++) {
   5182         requests[i] = &mNextRequests.editItemAt(i).halRequest;
   5183         ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
   5184     }
   5185 
   5186     res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
   5187 
   5188     bool triggerRemoveFailed = false;
   5189     NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
   5190     for (size_t i = 0; i < numRequestProcessed; i++) {
   5191         NextRequest& nextRequest = mNextRequests.editItemAt(i);
   5192         nextRequest.submitted = true;
   5193 
   5194         updateNextRequest(nextRequest);
   5195 
   5196         if (!triggerRemoveFailed) {
   5197             // Remove any previously queued triggers (after unlock)
   5198             status_t removeTriggerRes = removeTriggers(mPrevRequest);
   5199             if (removeTriggerRes != OK) {
   5200                 triggerRemoveFailed = true;
   5201                 triggerFailedRequest = nextRequest;
   5202             }
   5203         }
   5204     }
   5205 
   5206     if (triggerRemoveFailed) {
   5207         SET_ERR("RequestThread: Unable to remove triggers "
   5208               "(capture request %d, HAL device: %s (%d)",
   5209               triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
   5210         cleanUpFailedRequests(/*sendRequestError*/ false);
   5211         return false;
   5212     }
   5213 
   5214     if (res != OK) {
   5215         // Should only get a failure here for malformed requests or device-level
   5216         // errors, so consider all errors fatal.  Bad metadata failures should
   5217         // come through notify.
   5218         SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
   5219                 mNextRequests[numRequestProcessed].halRequest.frame_number,
   5220                 strerror(-res), res);
   5221         cleanUpFailedRequests(/*sendRequestError*/ false);
   5222         return false;
   5223     }
   5224     return true;
   5225 }
   5226 
   5227 nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
   5228     nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
   5229     camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
   5230     find_camera_metadata_ro_entry(request,
   5231             ANDROID_CONTROL_AE_MODE,
   5232             &e);
   5233     if (e.count == 0) return maxExpectedDuration;
   5234 
   5235     switch (e.data.u8[0]) {
   5236         case ANDROID_CONTROL_AE_MODE_OFF:
   5237             find_camera_metadata_ro_entry(request,
   5238                     ANDROID_SENSOR_EXPOSURE_TIME,
   5239                     &e);
   5240             if (e.count > 0) {
   5241                 maxExpectedDuration = e.data.i64[0];
   5242             }
   5243             find_camera_metadata_ro_entry(request,
   5244                     ANDROID_SENSOR_FRAME_DURATION,
   5245                     &e);
   5246             if (e.count > 0) {
   5247                 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
   5248             }
   5249             break;
   5250         default:
   5251             find_camera_metadata_ro_entry(request,
   5252                     ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
   5253                     &e);
   5254             if (e.count > 1) {
   5255                 maxExpectedDuration = 1e9 / e.data.u8[0];
   5256             }
   5257             break;
   5258     }
   5259 
   5260     return maxExpectedDuration;
   5261 }
   5262 
   5263 bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
   5264         const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
   5265     if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
   5266             (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
   5267             (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
   5268         return true;
   5269     }
   5270 
   5271     return false;
   5272 }
   5273 
   5274 void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
   5275     // Update the latest request sent to HAL
   5276     if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
   5277         Mutex::Autolock al(mLatestRequestMutex);
   5278 
   5279         camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
   5280         mLatestRequest.acquire(cloned);
   5281 
   5282         mLatestPhysicalRequest.clear();
   5283         for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
   5284             cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
   5285             mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
   5286                     CameraMetadata(cloned));
   5287         }
   5288 
   5289         sp<Camera3Device> parent = mParent.promote();
   5290         if (parent != NULL) {
   5291             parent->monitorMetadata(TagMonitor::REQUEST,
   5292                     nextRequest.halRequest.frame_number,
   5293                     0, mLatestRequest, mLatestPhysicalRequest);
   5294         }
   5295     }
   5296 
   5297     if (nextRequest.halRequest.settings != NULL) {
   5298         nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
   5299                 nextRequest.halRequest.settings);
   5300     }
   5301 
   5302     cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
   5303 }
   5304 
   5305 bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
   5306     ATRACE_CALL();
   5307     bool updatesDetected = false;
   5308 
   5309     CameraMetadata updatedParams(mLatestSessionParams);
   5310     for (auto tag : mSessionParamKeys) {
   5311         camera_metadata_ro_entry entry = settings.find(tag);
   5312         camera_metadata_entry lastEntry = updatedParams.find(tag);
   5313 
   5314         if (entry.count > 0) {
   5315             bool isDifferent = false;
   5316             if (lastEntry.count > 0) {
   5317                 // Have a last value, compare to see if changed
   5318                 if (lastEntry.type == entry.type &&
   5319                         lastEntry.count == entry.count) {
   5320                     // Same type and count, compare values
   5321                     size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
   5322                     size_t entryBytes = bytesPerValue * lastEntry.count;
   5323                     int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
   5324                     if (cmp != 0) {
   5325                         isDifferent = true;
   5326                     }
   5327                 } else {
   5328                     // Count or type has changed
   5329                     isDifferent = true;
   5330                 }
   5331             } else {
   5332                 // No last entry, so always consider to be different
   5333                 isDifferent = true;
   5334             }
   5335 
   5336             if (isDifferent) {
   5337                 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
   5338                 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
   5339                     updatesDetected = true;
   5340                 }
   5341                 updatedParams.update(entry);
   5342             }
   5343         } else if (lastEntry.count > 0) {
   5344             // Value has been removed
   5345             ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
   5346             updatedParams.erase(tag);
   5347             updatesDetected = true;
   5348         }
   5349     }
   5350 
   5351     bool reconfigureRequired;
   5352     if (updatesDetected) {
   5353         reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
   5354                 updatedParams);
   5355         mLatestSessionParams = updatedParams;
   5356     } else {
   5357         reconfigureRequired = false;
   5358     }
   5359 
   5360     return reconfigureRequired;
   5361 }
   5362 
   5363 bool Camera3Device::RequestThread::threadLoop() {
   5364     ATRACE_CALL();
   5365     status_t res;
   5366 
   5367     // Handle paused state.
   5368     if (waitIfPaused()) {
   5369         return true;
   5370     }
   5371 
   5372     // Wait for the next batch of requests.
   5373     waitForNextRequestBatch();
   5374     if (mNextRequests.size() == 0) {
   5375         return true;
   5376     }
   5377 
   5378     // Get the latest request ID, if any
   5379     int latestRequestId;
   5380     camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
   5381             captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
   5382     if (requestIdEntry.count > 0) {
   5383         latestRequestId = requestIdEntry.data.i32[0];
   5384     } else {
   5385         ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
   5386         latestRequestId = NAME_NOT_FOUND;
   5387     }
   5388 
   5389     // 'mNextRequests' will at this point contain either a set of HFR batched requests
   5390     //  or a single request from streaming or burst. In either case the first element
   5391     //  should contain the latest camera settings that we need to check for any session
   5392     //  parameter updates.
   5393     if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
   5394         res = OK;
   5395 
   5396         //Input stream buffers are already acquired at this point so an input stream
   5397         //will not be able to move to idle state unless we force it.
   5398         if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
   5399             res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
   5400             if (res != OK) {
   5401                 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
   5402                 cleanUpFailedRequests(/*sendRequestError*/ false);
   5403                 return false;
   5404             }
   5405         }
   5406 
   5407         if (res == OK) {
   5408             sp<StatusTracker> statusTracker = mStatusTracker.promote();
   5409             if (statusTracker != 0) {
   5410                 sp<Camera3Device> parent = mParent.promote();
   5411                 if (parent != nullptr) {
   5412                     parent->pauseStateNotify(true);
   5413                 }
   5414 
   5415                 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
   5416 
   5417                 if (parent != nullptr) {
   5418                     mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
   5419                 }
   5420 
   5421                 statusTracker->markComponentActive(mStatusId);
   5422                 setPaused(false);
   5423             }
   5424 
   5425             if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
   5426                 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
   5427                 if (res != OK) {
   5428                     ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
   5429                     cleanUpFailedRequests(/*sendRequestError*/ false);
   5430                     return false;
   5431                 }
   5432             }
   5433         }
   5434     }
   5435 
   5436     // Prepare a batch of HAL requests and output buffers.
   5437     res = prepareHalRequests();
   5438     if (res == TIMED_OUT) {
   5439         // Not a fatal error if getting output buffers time out.
   5440         cleanUpFailedRequests(/*sendRequestError*/ true);
   5441         // Check if any stream is abandoned.
   5442         checkAndStopRepeatingRequest();
   5443         return true;
   5444     } else if (res != OK) {
   5445         cleanUpFailedRequests(/*sendRequestError*/ false);
   5446         return false;
   5447     }
   5448 
   5449     // Inform waitUntilRequestProcessed thread of a new request ID
   5450     {
   5451         Mutex::Autolock al(mLatestRequestMutex);
   5452 
   5453         mLatestRequestId = latestRequestId;
   5454         mLatestRequestSignal.signal();
   5455     }
   5456 
   5457     // Submit a batch of requests to HAL.
   5458     // Use flush lock only when submitting multilple requests in a batch.
   5459     // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
   5460     // which may take a long time to finish so synchronizing flush() and
   5461     // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
   5462     // For now, only synchronize for high speed recording and we should figure something out for
   5463     // removing the synchronization.
   5464     bool useFlushLock = mNextRequests.size() > 1;
   5465 
   5466     if (useFlushLock) {
   5467         mFlushLock.lock();
   5468     }
   5469 
   5470     ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
   5471             mNextRequests.size());
   5472 
   5473     sp<Camera3Device> parent = mParent.promote();
   5474     if (parent != nullptr) {
   5475         parent->mRequestBufferSM.onSubmittingRequest();
   5476     }
   5477 
   5478     bool submitRequestSuccess = false;
   5479     nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
   5480     submitRequestSuccess = sendRequestsBatch();
   5481 
   5482     nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
   5483     mRequestLatency.add(tRequestStart, tRequestEnd);
   5484 
   5485     if (useFlushLock) {
   5486         mFlushLock.unlock();
   5487     }
   5488 
   5489     // Unset as current request
   5490     {
   5491         Mutex::Autolock l(mRequestLock);
   5492         mNextRequests.clear();
   5493     }
   5494 
   5495     return submitRequestSuccess;
   5496 }
   5497 
   5498 status_t Camera3Device::RequestThread::prepareHalRequests() {
   5499     ATRACE_CALL();
   5500 
   5501     bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
   5502     for (size_t i = 0; i < mNextRequests.size(); i++) {
   5503         auto& nextRequest = mNextRequests.editItemAt(i);
   5504         sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
   5505         camera3_capture_request_t* halRequest = &nextRequest.halRequest;
   5506         Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
   5507 
   5508         // Prepare a request to HAL
   5509         halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
   5510 
   5511         // Insert any queued triggers (before metadata is locked)
   5512         status_t res = insertTriggers(captureRequest);
   5513         if (res < 0) {
   5514             SET_ERR("RequestThread: Unable to insert triggers "
   5515                     "(capture request %d, HAL device: %s (%d)",
   5516                     halRequest->frame_number, strerror(-res), res);
   5517             return INVALID_OPERATION;
   5518         }
   5519 
   5520         int triggerCount = res;
   5521         bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
   5522         mPrevTriggers = triggerCount;
   5523 
   5524         // If the request is the same as last, or we had triggers last time
   5525         bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
   5526                 // Request settings are all the same within one batch, so only treat the first
   5527                 // request in a batch as new
   5528                 !(batchedRequest && i > 0);
   5529         if (newRequest) {
   5530             /**
   5531              * HAL workaround:
   5532              * Insert a dummy trigger ID if a trigger is set but no trigger ID is
   5533              */
   5534             res = addDummyTriggerIds(captureRequest);
   5535             if (res != OK) {
   5536                 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
   5537                         "(capture request %d, HAL device: %s (%d)",
   5538                         halRequest->frame_number, strerror(-res), res);
   5539                 return INVALID_OPERATION;
   5540             }
   5541 
   5542             {
   5543                 // Correct metadata regions for distortion correction if enabled
   5544                 sp<Camera3Device> parent = mParent.promote();
   5545                 if (parent != nullptr) {
   5546                     List<PhysicalCameraSettings>::iterator it;
   5547                     for (it = captureRequest->mSettingsList.begin();
   5548                             it != captureRequest->mSettingsList.end(); it++) {
   5549                         if (parent->mDistortionMappers.find(it->cameraId) ==
   5550                                 parent->mDistortionMappers.end()) {
   5551                             continue;
   5552                         }
   5553                         res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
   5554                             &(it->metadata));
   5555                         if (res != OK) {
   5556                             SET_ERR("RequestThread: Unable to correct capture requests "
   5557                                     "for lens distortion for request %d: %s (%d)",
   5558                                     halRequest->frame_number, strerror(-res), res);
   5559                             return INVALID_OPERATION;
   5560                         }
   5561                     }
   5562                 }
   5563             }
   5564 
   5565             /**
   5566              * The request should be presorted so accesses in HAL
   5567              *   are O(logn). Sidenote, sorting a sorted metadata is nop.
   5568              */
   5569             captureRequest->mSettingsList.begin()->metadata.sort();
   5570             halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
   5571             mPrevRequest = captureRequest;
   5572             ALOGVV("%s: Request settings are NEW", __FUNCTION__);
   5573 
   5574             IF_ALOGV() {
   5575                 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
   5576                 find_camera_metadata_ro_entry(
   5577                         halRequest->settings,
   5578                         ANDROID_CONTROL_AF_TRIGGER,
   5579                         &e
   5580                 );
   5581                 if (e.count > 0) {
   5582                     ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
   5583                           __FUNCTION__,
   5584                           halRequest->frame_number,
   5585                           e.data.u8[0]);
   5586                 }
   5587             }
   5588         } else {
   5589             // leave request.settings NULL to indicate 'reuse latest given'
   5590             ALOGVV("%s: Request settings are REUSED",
   5591                    __FUNCTION__);
   5592         }
   5593 
   5594         if (captureRequest->mSettingsList.size() > 1) {
   5595             halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
   5596             halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
   5597             if (newRequest) {
   5598                 halRequest->physcam_settings =
   5599                     new const camera_metadata* [halRequest->num_physcam_settings];
   5600             } else {
   5601                 halRequest->physcam_settings = nullptr;
   5602             }
   5603             auto it = ++captureRequest->mSettingsList.begin();
   5604             size_t i = 0;
   5605             for (; it != captureRequest->mSettingsList.end(); it++, i++) {
   5606                 halRequest->physcam_id[i] = it->cameraId.c_str();
   5607                 if (newRequest) {
   5608                     it->metadata.sort();
   5609                     halRequest->physcam_settings[i] = it->metadata.getAndLock();
   5610                 }
   5611             }
   5612         }
   5613 
   5614         uint32_t totalNumBuffers = 0;
   5615 
   5616         // Fill in buffers
   5617         if (captureRequest->mInputStream != NULL) {
   5618             halRequest->input_buffer = &captureRequest->mInputBuffer;
   5619             totalNumBuffers += 1;
   5620         } else {
   5621             halRequest->input_buffer = NULL;
   5622         }
   5623 
   5624         outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
   5625                 captureRequest->mOutputStreams.size());
   5626         halRequest->output_buffers = outputBuffers->array();
   5627         std::set<String8> requestedPhysicalCameras;
   5628 
   5629         sp<Camera3Device> parent = mParent.promote();
   5630         if (parent == NULL) {
   5631             // Should not happen, and nowhere to send errors to, so just log it
   5632             CLOGE("RequestThread: Parent is gone");
   5633             return INVALID_OPERATION;
   5634         }
   5635         nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
   5636 
   5637         SurfaceMap uniqueSurfaceIdMap;
   5638         for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
   5639             sp<Camera3OutputStreamInterface> outputStream =
   5640                     captureRequest->mOutputStreams.editItemAt(j);
   5641             int streamId = outputStream->getId();
   5642 
   5643             // Prepare video buffers for high speed recording on the first video request.
   5644             if (mPrepareVideoStream && outputStream->isVideoStream()) {
   5645                 // Only try to prepare video stream on the first video request.
   5646                 mPrepareVideoStream = false;
   5647 
   5648                 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
   5649                         false /*blockRequest*/);
   5650                 while (res == NOT_ENOUGH_DATA) {
   5651                     res = outputStream->prepareNextBuffer();
   5652                 }
   5653                 if (res != OK) {
   5654                     ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
   5655                         __FUNCTION__, strerror(-res), res);
   5656                     outputStream->cancelPrepare();
   5657                 }
   5658             }
   5659 
   5660             std::vector<size_t> uniqueSurfaceIds;
   5661             res = outputStream->getUniqueSurfaceIds(
   5662                     captureRequest->mOutputSurfaces[streamId],
   5663                     &uniqueSurfaceIds);
   5664             // INVALID_OPERATION is normal output for streams not supporting surfaceIds
   5665             if (res != OK && res != INVALID_OPERATION) {
   5666                 ALOGE("%s: failed to query stream %d unique surface IDs",
   5667                         __FUNCTION__, streamId);
   5668                 return res;
   5669             }
   5670             if (res == OK) {
   5671                 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
   5672             }
   5673 
   5674             if (mUseHalBufManager) {
   5675                 if (outputStream->isAbandoned()) {
   5676                     ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
   5677                     return TIMED_OUT;
   5678                 }
   5679                 // HAL will request buffer through requestStreamBuffer API
   5680                 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
   5681                 buffer.stream = outputStream->asHalStream();
   5682                 buffer.buffer = nullptr;
   5683                 buffer.status = CAMERA3_BUFFER_STATUS_OK;
   5684                 buffer.acquire_fence = -1;
   5685                 buffer.release_fence = -1;
   5686             } else {
   5687                 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
   5688                         waitDuration,
   5689                         captureRequest->mOutputSurfaces[streamId]);
   5690                 if (res != OK) {
   5691                     // Can't get output buffer from gralloc queue - this could be due to
   5692                     // abandoned queue or other consumer misbehavior, so not a fatal
   5693                     // error
   5694                     ALOGV("RequestThread: Can't get output buffer, skipping request:"
   5695                             " %s (%d)", strerror(-res), res);
   5696 
   5697                     return TIMED_OUT;
   5698                 }
   5699             }
   5700 
   5701             {
   5702                 sp<Camera3Device> parent = mParent.promote();
   5703                 if (parent != nullptr) {
   5704                     const String8& streamCameraId = outputStream->getPhysicalCameraId();
   5705                     for (const auto& settings : captureRequest->mSettingsList) {
   5706                         if ((streamCameraId.isEmpty() &&
   5707                                 parent->getId() == settings.cameraId.c_str()) ||
   5708                                 streamCameraId == settings.cameraId.c_str()) {
   5709                             outputStream->fireBufferRequestForFrameNumber(
   5710                                     captureRequest->mResultExtras.frameNumber,
   5711                                     settings.metadata);
   5712                         }
   5713                     }
   5714                 }
   5715             }
   5716 
   5717             String8 physicalCameraId = outputStream->getPhysicalCameraId();
   5718 
   5719             if (!physicalCameraId.isEmpty()) {
   5720                 // Physical stream isn't supported for input request.
   5721                 if (halRequest->input_buffer) {
   5722                     CLOGE("Physical stream is not supported for input request");
   5723                     return INVALID_OPERATION;
   5724                 }
   5725                 requestedPhysicalCameras.insert(physicalCameraId);
   5726             }
   5727             halRequest->num_output_buffers++;
   5728         }
   5729         totalNumBuffers += halRequest->num_output_buffers;
   5730 
   5731         // Log request in the in-flight queue
   5732         // If this request list is for constrained high speed recording (not
   5733         // preview), and the current request is not the last one in the batch,
   5734         // do not send callback to the app.
   5735         bool hasCallback = true;
   5736         if (batchedRequest && i != mNextRequests.size()-1) {
   5737             hasCallback = false;
   5738         }
   5739         bool isStillCapture = false;
   5740         bool isZslCapture = false;
   5741         if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
   5742             camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
   5743             find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
   5744             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
   5745                 isStillCapture = true;
   5746                 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
   5747             }
   5748 
   5749             find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
   5750             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
   5751                 isZslCapture = true;
   5752             }
   5753         }
   5754         res = parent->registerInFlight(halRequest->frame_number,
   5755                 totalNumBuffers, captureRequest->mResultExtras,
   5756                 /*hasInput*/halRequest->input_buffer != NULL,
   5757                 hasCallback,
   5758                 calculateMaxExpectedDuration(halRequest->settings),
   5759                 requestedPhysicalCameras, isStillCapture, isZslCapture,
   5760                 (mUseHalBufManager) ? uniqueSurfaceIdMap :
   5761                                       SurfaceMap{});
   5762         ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
   5763                ", burstId = %" PRId32 ".",
   5764                 __FUNCTION__,
   5765                 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
   5766                 captureRequest->mResultExtras.burstId);
   5767         if (res != OK) {
   5768             SET_ERR("RequestThread: Unable to register new in-flight request:"
   5769                     " %s (%d)", strerror(-res), res);
   5770             return INVALID_OPERATION;
   5771         }
   5772     }
   5773 
   5774     return OK;
   5775 }
   5776 
   5777 CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
   5778     ATRACE_CALL();
   5779     Mutex::Autolock al(mLatestRequestMutex);
   5780 
   5781     ALOGV("RequestThread::%s", __FUNCTION__);
   5782 
   5783     return mLatestRequest;
   5784 }
   5785 
   5786 bool Camera3Device::RequestThread::isStreamPending(
   5787         sp<Camera3StreamInterface>& stream) {
   5788     ATRACE_CALL();
   5789     Mutex::Autolock l(mRequestLock);
   5790 
   5791     for (const auto& nextRequest : mNextRequests) {
   5792         if (!nextRequest.submitted) {
   5793             for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
   5794                 if (stream == s) return true;
   5795             }
   5796             if (stream == nextRequest.captureRequest->mInputStream) return true;
   5797         }
   5798     }
   5799 
   5800     for (const auto& request : mRequestQueue) {
   5801         for (const auto& s : request->mOutputStreams) {
   5802             if (stream == s) return true;
   5803         }
   5804         if (stream == request->mInputStream) return true;
   5805     }
   5806 
   5807     for (const auto& request : mRepeatingRequests) {
   5808         for (const auto& s : request->mOutputStreams) {
   5809             if (stream == s) return true;
   5810         }
   5811         if (stream == request->mInputStream) return true;
   5812     }
   5813 
   5814     return false;
   5815 }
   5816 
   5817 bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
   5818     ATRACE_CALL();
   5819     Mutex::Autolock l(mRequestLock);
   5820 
   5821     for (const auto& nextRequest : mNextRequests) {
   5822         for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
   5823             if (s.first == streamId) {
   5824                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
   5825                 if (it != s.second.end()) {
   5826                     return true;
   5827                 }
   5828             }
   5829         }
   5830     }
   5831 
   5832     for (const auto& request : mRequestQueue) {
   5833         for (const auto& s : request->mOutputSurfaces) {
   5834             if (s.first == streamId) {
   5835                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
   5836                 if (it != s.second.end()) {
   5837                     return true;
   5838                 }
   5839             }
   5840         }
   5841     }
   5842 
   5843     for (const auto& request : mRepeatingRequests) {
   5844         for (const auto& s : request->mOutputSurfaces) {
   5845             if (s.first == streamId) {
   5846                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
   5847                 if (it != s.second.end()) {
   5848                     return true;
   5849                 }
   5850             }
   5851         }
   5852     }
   5853 
   5854     return false;
   5855 }
   5856 
   5857 void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
   5858     if (!mUseHalBufManager) {
   5859         ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
   5860         return;
   5861     }
   5862 
   5863     Mutex::Autolock pl(mPauseLock);
   5864     if (mPaused) {
   5865         mInterface->signalPipelineDrain(streamIds);
   5866         return;
   5867     }
   5868     // If request thread is still busy, wait until paused then notify HAL
   5869     mNotifyPipelineDrain = true;
   5870     mStreamIdsToBeDrained = streamIds;
   5871 }
   5872 
   5873 nsecs_t Camera3Device::getExpectedInFlightDuration() {
   5874     ATRACE_CALL();
   5875     Mutex::Autolock al(mInFlightLock);
   5876     return mExpectedInflightDuration > kMinInflightDuration ?
   5877             mExpectedInflightDuration : kMinInflightDuration;
   5878 }
   5879 
   5880 void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
   5881         camera3_capture_request_t *halRequest) {
   5882     if ((request == nullptr) || (halRequest == nullptr)) {
   5883         ALOGE("%s: Invalid request!", __FUNCTION__);
   5884         return;
   5885     }
   5886 
   5887     if (halRequest->num_physcam_settings > 0) {
   5888         if (halRequest->physcam_id != nullptr) {
   5889             delete [] halRequest->physcam_id;
   5890             halRequest->physcam_id = nullptr;
   5891         }
   5892         if (halRequest->physcam_settings != nullptr) {
   5893             auto it = ++(request->mSettingsList.begin());
   5894             size_t i = 0;
   5895             for (; it != request->mSettingsList.end(); it++, i++) {
   5896                 it->metadata.unlock(halRequest->physcam_settings[i]);
   5897             }
   5898             delete [] halRequest->physcam_settings;
   5899             halRequest->physcam_settings = nullptr;
   5900         }
   5901     }
   5902 }
   5903 
   5904 void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
   5905     if (mNextRequests.empty()) {
   5906         return;
   5907     }
   5908 
   5909     for (auto& nextRequest : mNextRequests) {
   5910         // Skip the ones that have been submitted successfully.
   5911         if (nextRequest.submitted) {
   5912             continue;
   5913         }
   5914 
   5915         sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
   5916         camera3_capture_request_t* halRequest = &nextRequest.halRequest;
   5917         Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
   5918 
   5919         if (halRequest->settings != NULL) {
   5920             captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
   5921         }
   5922 
   5923         cleanupPhysicalSettings(captureRequest, halRequest);
   5924 
   5925         if (captureRequest->mInputStream != NULL) {
   5926             captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
   5927             captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
   5928         }
   5929 
   5930         // No output buffer can be returned when using HAL buffer manager
   5931         if (!mUseHalBufManager) {
   5932             for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
   5933                 //Buffers that failed processing could still have
   5934                 //valid acquire fence.
   5935                 int acquireFence = (*outputBuffers)[i].acquire_fence;
   5936                 if (0 <= acquireFence) {
   5937                     close(acquireFence);
   5938                     outputBuffers->editItemAt(i).acquire_fence = -1;
   5939                 }
   5940                 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
   5941                 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
   5942                         /*timestampIncreasing*/true, std::vector<size_t> (),
   5943                         captureRequest->mResultExtras.frameNumber);
   5944             }
   5945         }
   5946 
   5947         if (sendRequestError) {
   5948             Mutex::Autolock l(mRequestLock);
   5949             sp<NotificationListener> listener = mListener.promote();
   5950             if (listener != NULL) {
   5951                 listener->notifyError(
   5952                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
   5953                         captureRequest->mResultExtras);
   5954             }
   5955         }
   5956 
   5957         // Remove yet-to-be submitted inflight request from inflightMap
   5958         {
   5959           sp<Camera3Device> parent = mParent.promote();
   5960           if (parent != NULL) {
   5961               Mutex::Autolock l(parent->mInFlightLock);
   5962               ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
   5963               if (idx >= 0) {
   5964                   ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
   5965                         __FUNCTION__, captureRequest->mResultExtras.frameNumber);
   5966                   parent->removeInFlightMapEntryLocked(idx);
   5967               }
   5968           }
   5969         }
   5970     }
   5971 
   5972     Mutex::Autolock l(mRequestLock);
   5973     mNextRequests.clear();
   5974 }
   5975 
   5976 void Camera3Device::RequestThread::waitForNextRequestBatch() {
   5977     ATRACE_CALL();
   5978     // Optimized a bit for the simple steady-state case (single repeating
   5979     // request), to avoid putting that request in the queue temporarily.
   5980     Mutex::Autolock l(mRequestLock);
   5981 
   5982     assert(mNextRequests.empty());
   5983 
   5984     NextRequest nextRequest;
   5985     nextRequest.captureRequest = waitForNextRequestLocked();
   5986     if (nextRequest.captureRequest == nullptr) {
   5987         return;
   5988     }
   5989 
   5990     nextRequest.halRequest = camera3_capture_request_t();
   5991     nextRequest.submitted = false;
   5992     mNextRequests.add(nextRequest);
   5993 
   5994     // Wait for additional requests
   5995     const size_t batchSize = nextRequest.captureRequest->mBatchSize;
   5996 
   5997     for (size_t i = 1; i < batchSize; i++) {
   5998         NextRequest additionalRequest;
   5999         additionalRequest.captureRequest = waitForNextRequestLocked();
   6000         if (additionalRequest.captureRequest == nullptr) {
   6001             break;
   6002         }
   6003 
   6004         additionalRequest.halRequest = camera3_capture_request_t();
   6005         additionalRequest.submitted = false;
   6006         mNextRequests.add(additionalRequest);
   6007     }
   6008 
   6009     if (mNextRequests.size() < batchSize) {
   6010         ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
   6011                 mNextRequests.size(), batchSize);
   6012         cleanUpFailedRequests(/*sendRequestError*/true);
   6013     }
   6014 
   6015     return;
   6016 }
   6017 
   6018 sp<Camera3Device::CaptureRequest>
   6019         Camera3Device::RequestThread::waitForNextRequestLocked() {
   6020     status_t res;
   6021     sp<CaptureRequest> nextRequest;
   6022 
   6023     while (mRequestQueue.empty()) {
   6024         if (!mRepeatingRequests.empty()) {
   6025             // Always atomically enqueue all requests in a repeating request
   6026             // list. Guarantees a complete in-sequence set of captures to
   6027             // application.
   6028             const RequestList &requests = mRepeatingRequests;
   6029             RequestList::const_iterator firstRequest =
   6030                     requests.begin();
   6031             nextRequest = *firstRequest;
   6032             mRequestQueue.insert(mRequestQueue.end(),
   6033                     ++firstRequest,
   6034                     requests.end());
   6035             // No need to wait any longer
   6036 
   6037             mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
   6038 
   6039             break;
   6040         }
   6041 
   6042         res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
   6043 
   6044         if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
   6045                 exitPending()) {
   6046             Mutex::Autolock pl(mPauseLock);
   6047             if (mPaused == false) {
   6048                 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
   6049                 mPaused = true;
   6050                 if (mNotifyPipelineDrain) {
   6051                     mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
   6052                     mNotifyPipelineDrain = false;
   6053                     mStreamIdsToBeDrained.clear();
   6054                 }
   6055                 // Let the tracker know
   6056                 sp<StatusTracker> statusTracker = mStatusTracker.promote();
   6057                 if (statusTracker != 0) {
   6058                     statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
   6059                 }
   6060                 sp<Camera3Device> parent = mParent.promote();
   6061                 if (parent != nullptr) {
   6062                     parent->mRequestBufferSM.onRequestThreadPaused();
   6063                 }
   6064             }
   6065             // Stop waiting for now and let thread management happen
   6066             return NULL;
   6067         }
   6068     }
   6069 
   6070     if (nextRequest == NULL) {
   6071         // Don't have a repeating request already in hand, so queue
   6072         // must have an entry now.
   6073         RequestList::iterator firstRequest =
   6074                 mRequestQueue.begin();
   6075         nextRequest = *firstRequest;
   6076         mRequestQueue.erase(firstRequest);
   6077         if (mRequestQueue.empty() && !nextRequest->mRepeating) {
   6078             sp<NotificationListener> listener = mListener.promote();
   6079             if (listener != NULL) {
   6080                 listener->notifyRequestQueueEmpty();
   6081             }
   6082         }
   6083     }
   6084 
   6085     // In case we've been unpaused by setPaused clearing mDoPause, need to
   6086     // update internal pause state (capture/setRepeatingRequest unpause
   6087     // directly).
   6088     Mutex::Autolock pl(mPauseLock);
   6089     if (mPaused) {
   6090         ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
   6091         sp<StatusTracker> statusTracker = mStatusTracker.promote();
   6092         if (statusTracker != 0) {
   6093             statusTracker->markComponentActive(mStatusId);
   6094         }
   6095     }
   6096     mPaused = false;
   6097 
   6098     // Check if we've reconfigured since last time, and reset the preview
   6099     // request if so. Can't use 'NULL request == repeat' across configure calls.
   6100     if (mReconfigured) {
   6101         mPrevRequest.clear();
   6102         mReconfigured = false;
   6103     }
   6104 
   6105     if (nextRequest != NULL) {
   6106         nextRequest->mResultExtras.frameNumber = mFrameNumber++;
   6107         nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
   6108         nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
   6109 
   6110         // Since RequestThread::clear() removes buffers from the input stream,
   6111         // get the right buffer here before unlocking mRequestLock
   6112         if (nextRequest->mInputStream != NULL) {
   6113             res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
   6114             if (res != OK) {
   6115                 // Can't get input buffer from gralloc queue - this could be due to
   6116                 // disconnected queue or other producer misbehavior, so not a fatal
   6117                 // error
   6118                 ALOGE("%s: Can't get input buffer, skipping request:"
   6119                         " %s (%d)", __FUNCTION__, strerror(-res), res);
   6120 
   6121                 sp<NotificationListener> listener = mListener.promote();
   6122                 if (listener != NULL) {
   6123                     listener->notifyError(
   6124                             hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
   6125                             nextRequest->mResultExtras);
   6126                 }
   6127                 return NULL;
   6128             }
   6129         }
   6130     }
   6131 
   6132     return nextRequest;
   6133 }
   6134 
   6135 bool Camera3Device::RequestThread::waitIfPaused() {
   6136     ATRACE_CALL();
   6137     status_t res;
   6138     Mutex::Autolock l(mPauseLock);
   6139     while (mDoPause) {
   6140         if (mPaused == false) {
   6141             mPaused = true;
   6142             ALOGV("%s: RequestThread: Paused", __FUNCTION__);
   6143             if (mNotifyPipelineDrain) {
   6144                 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
   6145                 mNotifyPipelineDrain = false;
   6146                 mStreamIdsToBeDrained.clear();
   6147             }
   6148             // Let the tracker know
   6149             sp<StatusTracker> statusTracker = mStatusTracker.promote();
   6150             if (statusTracker != 0) {
   6151                 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
   6152             }
   6153             sp<Camera3Device> parent = mParent.promote();
   6154             if (parent != nullptr) {
   6155                 parent->mRequestBufferSM.onRequestThreadPaused();
   6156             }
   6157         }
   6158 
   6159         res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
   6160         if (res == TIMED_OUT || exitPending()) {
   6161             return true;
   6162         }
   6163     }
   6164     // We don't set mPaused to false here, because waitForNextRequest needs
   6165     // to further manage the paused state in case of starvation.
   6166     return false;
   6167 }
   6168 
   6169 void Camera3Device::RequestThread::unpauseForNewRequests() {
   6170     ATRACE_CALL();
   6171     // With work to do, mark thread as unpaused.
   6172     // If paused by request (setPaused), don't resume, to avoid
   6173     // extra signaling/waiting overhead to waitUntilPaused
   6174     mRequestSignal.signal();
   6175     Mutex::Autolock p(mPauseLock);
   6176     if (!mDoPause) {
   6177         ALOGV("%s: RequestThread: Going active", __FUNCTION__);
   6178         if (mPaused) {
   6179             sp<StatusTracker> statusTracker = mStatusTracker.promote();
   6180             if (statusTracker != 0) {
   6181                 statusTracker->markComponentActive(mStatusId);
   6182             }
   6183         }
   6184         mPaused = false;
   6185     }
   6186 }
   6187 
   6188 void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
   6189     sp<Camera3Device> parent = mParent.promote();
   6190     if (parent != NULL) {
   6191         va_list args;
   6192         va_start(args, fmt);
   6193 
   6194         parent->setErrorStateV(fmt, args);
   6195 
   6196         va_end(args);
   6197     }
   6198 }
   6199 
   6200 status_t Camera3Device::RequestThread::insertTriggers(
   6201         const sp<CaptureRequest> &request) {
   6202     ATRACE_CALL();
   6203     Mutex::Autolock al(mTriggerMutex);
   6204 
   6205     sp<Camera3Device> parent = mParent.promote();
   6206     if (parent == NULL) {
   6207         CLOGE("RequestThread: Parent is gone");
   6208         return DEAD_OBJECT;
   6209     }
   6210 
   6211     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
   6212     size_t count = mTriggerMap.size();
   6213 
   6214     for (size_t i = 0; i < count; ++i) {
   6215         RequestTrigger trigger = mTriggerMap.valueAt(i);
   6216         uint32_t tag = trigger.metadataTag;
   6217 
   6218         if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
   6219             bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
   6220             uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
   6221             if (isAeTrigger) {
   6222                 request->mResultExtras.precaptureTriggerId = triggerId;
   6223                 mCurrentPreCaptureTriggerId = triggerId;
   6224             } else {
   6225                 request->mResultExtras.afTriggerId = triggerId;
   6226                 mCurrentAfTriggerId = triggerId;
   6227             }
   6228             continue;
   6229         }
   6230 
   6231         camera_metadata_entry entry = metadata.find(tag);
   6232 
   6233         if (entry.count > 0) {
   6234             /**
   6235              * Already has an entry for this trigger in the request.
   6236              * Rewrite it with our requested trigger value.
   6237              */
   6238             RequestTrigger oldTrigger = trigger;
   6239 
   6240             oldTrigger.entryValue = entry.data.u8[0];
   6241 
   6242             mTriggerReplacedMap.add(tag, oldTrigger);
   6243         } else {
   6244             /**
   6245              * More typical, no trigger entry, so we just add it
   6246              */
   6247             mTriggerRemovedMap.add(tag, trigger);
   6248         }
   6249 
   6250         status_t res;
   6251 
   6252         switch (trigger.getTagType()) {
   6253             case TYPE_BYTE: {
   6254                 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
   6255                 res = metadata.update(tag,
   6256                                       &entryValue,
   6257                                       /*count*/1);
   6258                 break;
   6259             }
   6260             case TYPE_INT32:
   6261                 res = metadata.update(tag,
   6262                                       &trigger.entryValue,
   6263                                       /*count*/1);
   6264                 break;
   6265             default:
   6266                 ALOGE("%s: Type not supported: 0x%x",
   6267                       __FUNCTION__,
   6268                       trigger.getTagType());
   6269                 return INVALID_OPERATION;
   6270         }
   6271 
   6272         if (res != OK) {
   6273             ALOGE("%s: Failed to update request metadata with trigger tag %s"
   6274                   ", value %d", __FUNCTION__, trigger.getTagName(),
   6275                   trigger.entryValue);
   6276             return res;
   6277         }
   6278 
   6279         ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
   6280               trigger.getTagName(),
   6281               trigger.entryValue);
   6282     }
   6283 
   6284     mTriggerMap.clear();
   6285 
   6286     return count;
   6287 }
   6288 
   6289 status_t Camera3Device::RequestThread::removeTriggers(
   6290         const sp<CaptureRequest> &request) {
   6291     ATRACE_CALL();
   6292     Mutex::Autolock al(mTriggerMutex);
   6293 
   6294     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
   6295 
   6296     /**
   6297      * Replace all old entries with their old values.
   6298      */
   6299     for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
   6300         RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
   6301 
   6302         status_t res;
   6303 
   6304         uint32_t tag = trigger.metadataTag;
   6305         switch (trigger.getTagType()) {
   6306             case TYPE_BYTE: {
   6307                 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
   6308                 res = metadata.update(tag,
   6309                                       &entryValue,
   6310                                       /*count*/1);
   6311                 break;
   6312             }
   6313             case TYPE_INT32:
   6314                 res = metadata.update(tag,
   6315                                       &trigger.entryValue,
   6316                                       /*count*/1);
   6317                 break;
   6318             default:
   6319                 ALOGE("%s: Type not supported: 0x%x",
   6320                       __FUNCTION__,
   6321                       trigger.getTagType());
   6322                 return INVALID_OPERATION;
   6323         }
   6324 
   6325         if (res != OK) {
   6326             ALOGE("%s: Failed to restore request metadata with trigger tag %s"
   6327                   ", trigger value %d", __FUNCTION__,
   6328                   trigger.getTagName(), trigger.entryValue);
   6329             return res;
   6330         }
   6331     }
   6332     mTriggerReplacedMap.clear();
   6333 
   6334     /**
   6335      * Remove all new entries.
   6336      */
   6337     for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
   6338         RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
   6339         status_t res = metadata.erase(trigger.metadataTag);
   6340 
   6341         if (res != OK) {
   6342             ALOGE("%s: Failed to erase metadata with trigger tag %s"
   6343                   ", trigger value %d", __FUNCTION__,
   6344                   trigger.getTagName(), trigger.entryValue);
   6345             return res;
   6346         }
   6347     }
   6348     mTriggerRemovedMap.clear();
   6349 
   6350     return OK;
   6351 }
   6352 
   6353 status_t Camera3Device::RequestThread::addDummyTriggerIds(
   6354         const sp<CaptureRequest> &request) {
   6355     // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
   6356     static const int32_t dummyTriggerId = 1;
   6357     status_t res;
   6358 
   6359     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
   6360 
   6361     // If AF trigger is active, insert a dummy AF trigger ID if none already
   6362     // exists
   6363     camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
   6364     camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
   6365     if (afTrigger.count > 0 &&
   6366             afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
   6367             afId.count == 0) {
   6368         res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
   6369         if (res != OK) return res;
   6370     }
   6371 
   6372     // If AE precapture trigger is active, insert a dummy precapture trigger ID
   6373     // if none already exists
   6374     camera_metadata_entry pcTrigger =
   6375             metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
   6376     camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
   6377     if (pcTrigger.count > 0 &&
   6378             pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
   6379             pcId.count == 0) {
   6380         res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
   6381                 &dummyTriggerId, 1);
   6382         if (res != OK) return res;
   6383     }
   6384 
   6385     return OK;
   6386 }
   6387 
   6388 /**
   6389  * PreparerThread inner class methods
   6390  */
   6391 
   6392 Camera3Device::PreparerThread::PreparerThread() :
   6393         Thread(/*canCallJava*/false), mListener(nullptr),
   6394         mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
   6395 }
   6396 
   6397 Camera3Device::PreparerThread::~PreparerThread() {
   6398     Thread::requestExitAndWait();
   6399     if (mCurrentStream != nullptr) {
   6400         mCurrentStream->cancelPrepare();
   6401         ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
   6402         mCurrentStream.clear();
   6403     }
   6404     clear();
   6405 }
   6406 
   6407 status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
   6408     ATRACE_CALL();
   6409     status_t res;
   6410 
   6411     Mutex::Autolock l(mLock);
   6412     sp<NotificationListener> listener = mListener.promote();
   6413 
   6414     res = stream->startPrepare(maxCount, true /*blockRequest*/);
   6415     if (res == OK) {
   6416         // No preparation needed, fire listener right off
   6417         ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
   6418         if (listener != NULL) {
   6419             listener->notifyPrepared(stream->getId());
   6420         }
   6421         return OK;
   6422     } else if (res != NOT_ENOUGH_DATA) {
   6423         return res;
   6424     }
   6425 
   6426     // Need to prepare, start up thread if necessary
   6427     if (!mActive) {
   6428         // mRunning will change to false before the thread fully shuts down, so wait to be sure it
   6429         // isn't running
   6430         Thread::requestExitAndWait();
   6431         res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
   6432         if (res != OK) {
   6433             ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
   6434             if (listener != NULL) {
   6435                 listener->notifyPrepared(stream->getId());
   6436             }
   6437             return res;
   6438         }
   6439         mCancelNow = false;
   6440         mActive = true;
   6441         ALOGV("%s: Preparer stream started", __FUNCTION__);
   6442     }
   6443 
   6444     // queue up the work
   6445     mPendingStreams.emplace(maxCount, stream);
   6446     ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
   6447 
   6448     return OK;
   6449 }
   6450 
   6451 void Camera3Device::PreparerThread::pause() {
   6452     ATRACE_CALL();
   6453 
   6454     Mutex::Autolock l(mLock);
   6455 
   6456     std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
   6457     pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
   6458     sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
   6459     int currentMaxCount = mCurrentMaxCount;
   6460     mPendingStreams.clear();
   6461     mCancelNow = true;
   6462     while (mActive) {
   6463         auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
   6464         if (res == TIMED_OUT) {
   6465             ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
   6466             return;
   6467         } else if (res != OK) {
   6468             ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
   6469             return;
   6470         }
   6471     }
   6472 
   6473     //Check whether the prepare thread was able to complete the current
   6474     //stream. In case work is still pending emplace it along with the rest
   6475     //of the streams in the pending list.
   6476     if (currentStream != nullptr) {
   6477         if (!mCurrentPrepareComplete) {
   6478             pendingStreams.emplace(currentMaxCount, currentStream);
   6479         }
   6480     }
   6481 
   6482     mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
   6483     for (const auto& it : mPendingStreams) {
   6484         it.second->cancelPrepare();
   6485     }
   6486 }
   6487 
   6488 status_t Camera3Device::PreparerThread::resume() {
   6489     ATRACE_CALL();
   6490     status_t res;
   6491 
   6492     Mutex::Autolock l(mLock);
   6493     sp<NotificationListener> listener = mListener.promote();
   6494 
   6495     if (mActive) {
   6496         ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
   6497         return NO_INIT;
   6498     }
   6499 
   6500     auto it = mPendingStreams.begin();
   6501     for (; it != mPendingStreams.end();) {
   6502         res = it->second->startPrepare(it->first, true /*blockRequest*/);
   6503         if (res == OK) {
   6504             if (listener != NULL) {
   6505                 listener->notifyPrepared(it->second->getId());
   6506             }
   6507             it = mPendingStreams.erase(it);
   6508         } else if (res != NOT_ENOUGH_DATA) {
   6509             ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
   6510                     res, strerror(-res));
   6511             it = mPendingStreams.erase(it);
   6512         } else {
   6513             it++;
   6514         }
   6515     }
   6516 
   6517     if (mPendingStreams.empty()) {
   6518         return OK;
   6519     }
   6520 
   6521     res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
   6522     if (res != OK) {
   6523         ALOGE("%s: Unable to start preparer stream: %d (%s)",
   6524                 __FUNCTION__, res, strerror(-res));
   6525         return res;
   6526     }
   6527     mCancelNow = false;
   6528     mActive = true;
   6529     ALOGV("%s: Preparer stream started", __FUNCTION__);
   6530 
   6531     return OK;
   6532 }
   6533 
   6534 status_t Camera3Device::PreparerThread::clear() {
   6535     ATRACE_CALL();
   6536     Mutex::Autolock l(mLock);
   6537 
   6538     for (const auto& it : mPendingStreams) {
   6539         it.second->cancelPrepare();
   6540     }
   6541     mPendingStreams.clear();
   6542     mCancelNow = true;
   6543 
   6544     return OK;
   6545 }
   6546 
   6547 void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
   6548     ATRACE_CALL();
   6549     Mutex::Autolock l(mLock);
   6550     mListener = listener;
   6551 }
   6552 
   6553 bool Camera3Device::PreparerThread::threadLoop() {
   6554     status_t res;
   6555     {
   6556         Mutex::Autolock l(mLock);
   6557         if (mCurrentStream == nullptr) {
   6558             // End thread if done with work
   6559             if (mPendingStreams.empty()) {
   6560                 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
   6561                 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
   6562                 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
   6563                 mActive = false;
   6564                 mThreadActiveSignal.signal();
   6565                 return false;
   6566             }
   6567 
   6568             // Get next stream to prepare
   6569             auto it = mPendingStreams.begin();
   6570             mCurrentStream = it->second;
   6571             mCurrentMaxCount = it->first;
   6572             mCurrentPrepareComplete = false;
   6573             mPendingStreams.erase(it);
   6574             ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
   6575             ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
   6576         } else if (mCancelNow) {
   6577             mCurrentStream->cancelPrepare();
   6578             ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
   6579             ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
   6580             mCurrentStream.clear();
   6581             mCancelNow = false;
   6582             return true;
   6583         }
   6584     }
   6585 
   6586     res = mCurrentStream->prepareNextBuffer();
   6587     if (res == NOT_ENOUGH_DATA) return true;
   6588     if (res != OK) {
   6589         // Something bad happened; try to recover by cancelling prepare and
   6590         // signalling listener anyway
   6591         ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
   6592                 mCurrentStream->getId(), res, strerror(-res));
   6593         mCurrentStream->cancelPrepare();
   6594     }
   6595 
   6596     // This stream has finished, notify listener
   6597     Mutex::Autolock l(mLock);
   6598     sp<NotificationListener> listener = mListener.promote();
   6599     if (listener != NULL) {
   6600         ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
   6601                 mCurrentStream->getId());
   6602         listener->notifyPrepared(mCurrentStream->getId());
   6603     }
   6604 
   6605     ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
   6606     mCurrentStream.clear();
   6607     mCurrentPrepareComplete = true;
   6608 
   6609     return true;
   6610 }
   6611 
   6612 status_t Camera3Device::RequestBufferStateMachine::initialize(
   6613         sp<camera3::StatusTracker> statusTracker) {
   6614     if (statusTracker == nullptr) {
   6615         ALOGE("%s: statusTracker is null", __FUNCTION__);
   6616         return BAD_VALUE;
   6617     }
   6618 
   6619     std::lock_guard<std::mutex> lock(mLock);
   6620     mStatusTracker = statusTracker;
   6621     mRequestBufferStatusId = statusTracker->addComponent();
   6622     return OK;
   6623 }
   6624 
   6625 bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
   6626     std::lock_guard<std::mutex> lock(mLock);
   6627     if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
   6628         mRequestBufferOngoing = true;
   6629         notifyTrackerLocked(/*active*/true);
   6630         return true;
   6631     }
   6632     return false;
   6633 }
   6634 
   6635 void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
   6636     std::lock_guard<std::mutex> lock(mLock);
   6637     if (!mRequestBufferOngoing) {
   6638         ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
   6639         return;
   6640     }
   6641     mRequestBufferOngoing = false;
   6642     if (mStatus == RB_STATUS_PENDING_STOP) {
   6643         checkSwitchToStopLocked();
   6644     }
   6645     notifyTrackerLocked(/*active*/false);
   6646 }
   6647 
   6648 void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
   6649     std::lock_guard<std::mutex> lock(mLock);
   6650     mStatus = RB_STATUS_READY;
   6651     return;
   6652 }
   6653 
   6654 void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
   6655     std::lock_guard<std::mutex> lock(mLock);
   6656     mRequestThreadPaused = false;
   6657     // inflight map register actually happens in prepareHalRequest now, but it is close enough
   6658     // approximation.
   6659     mInflightMapEmpty = false;
   6660     if (mStatus == RB_STATUS_STOPPED) {
   6661         mStatus = RB_STATUS_READY;
   6662     }
   6663     return;
   6664 }
   6665 
   6666 void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
   6667     std::lock_guard<std::mutex> lock(mLock);
   6668     mRequestThreadPaused = true;
   6669     if (mStatus == RB_STATUS_PENDING_STOP) {
   6670         checkSwitchToStopLocked();
   6671     }
   6672     return;
   6673 }
   6674 
   6675 void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
   6676     std::lock_guard<std::mutex> lock(mLock);
   6677     mInflightMapEmpty = true;
   6678     if (mStatus == RB_STATUS_PENDING_STOP) {
   6679         checkSwitchToStopLocked();
   6680     }
   6681     return;
   6682 }
   6683 
   6684 void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
   6685     std::lock_guard<std::mutex> lock(mLock);
   6686     if (!checkSwitchToStopLocked()) {
   6687         mStatus = RB_STATUS_PENDING_STOP;
   6688     }
   6689     return;
   6690 }
   6691 
   6692 void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
   6693     sp<StatusTracker> statusTracker = mStatusTracker.promote();
   6694     if (statusTracker != nullptr) {
   6695         if (active) {
   6696             statusTracker->markComponentActive(mRequestBufferStatusId);
   6697         } else {
   6698             statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
   6699         }
   6700     }
   6701 }
   6702 
   6703 bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
   6704     if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
   6705         mStatus = RB_STATUS_STOPPED;
   6706         return true;
   6707     }
   6708     return false;
   6709 }
   6710 
   6711 status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
   6712         CameraMetadata& resultMetadata) {
   6713     status_t res = OK;
   6714     if (!mNeedFixupMonochromeTags) {
   6715         return res;
   6716     }
   6717 
   6718     // Remove tags that are not applicable to monochrome camera.
   6719     int32_t tagsToRemove[] = {
   6720            ANDROID_SENSOR_GREEN_SPLIT,
   6721            ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
   6722            ANDROID_COLOR_CORRECTION_MODE,
   6723            ANDROID_COLOR_CORRECTION_TRANSFORM,
   6724            ANDROID_COLOR_CORRECTION_GAINS,
   6725     };
   6726     for (auto tag : tagsToRemove) {
   6727         res = resultMetadata.erase(tag);
   6728         if (res != OK) {
   6729             ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
   6730             return res;
   6731         }
   6732     }
   6733 
   6734     // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
   6735     camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
   6736     for (size_t i = 1; i < blEntry.count; i++) {
   6737         blEntry.data.f[i] = blEntry.data.f[0];
   6738     }
   6739 
   6740     // ANDROID_SENSOR_NOISE_PROFILE
   6741     camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
   6742     if (npEntry.count > 0 && npEntry.count % 2 == 0) {
   6743         double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
   6744         res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
   6745         if (res != OK) {
   6746              ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
   6747                     __FUNCTION__, strerror(-res), res);
   6748             return res;
   6749         }
   6750     }
   6751 
   6752     // ANDROID_STATISTICS_LENS_SHADING_MAP
   6753     camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
   6754     camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
   6755     if (lsSizeEntry.count == 2 && lsEntry.count > 0
   6756             && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
   6757         for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
   6758             lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
   6759             lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
   6760             lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
   6761         }
   6762     }
   6763 
   6764     // ANDROID_TONEMAP_CURVE_BLUE
   6765     // ANDROID_TONEMAP_CURVE_GREEN
   6766     // ANDROID_TONEMAP_CURVE_RED
   6767     camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
   6768     camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
   6769     camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
   6770     if (tcbEntry.count > 0
   6771             && tcbEntry.count == tcgEntry.count
   6772             && tcbEntry.count == tcrEntry.count) {
   6773         for (size_t i = 0; i < tcbEntry.count; i++) {
   6774             tcbEntry.data.f[i] = tcrEntry.data.f[i];
   6775             tcgEntry.data.f[i] = tcrEntry.data.f[i];
   6776         }
   6777     }
   6778 
   6779     return res;
   6780 }
   6781 
   6782 }; // namespace android
   6783