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