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.c_str(), __FUNCTION__, \
30             ##__VA_ARGS__)
31 
32 #define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.c_str(), __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 <android-base/stringprintf.h>
48 #include <sched.h>
49 #include <utils/Log.h>
50 #include <utils/Trace.h>
51 #include <utils/Timers.h>
52 #include <cutils/properties.h>
53 #include <camera/StringUtils.h>
54 
55 #include <android-base/properties.h>
56 #include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
57 #include <android/hardware/camera2/ICameraDeviceUser.h>
58 #include <com_android_internal_camera_flags.h>
59 
60 #include "CameraService.h"
61 #include "aidl/android/hardware/graphics/common/Dataspace.h"
62 #include "aidl/AidlUtils.h"
63 #include "device3/Camera3Device.h"
64 #include "device3/Camera3FakeStream.h"
65 #include "device3/Camera3InputStream.h"
66 #include "device3/Camera3OutputStream.h"
67 #include "device3/Camera3SharedOutputStream.h"
68 #include "utils/CameraTraces.h"
69 #include "utils/SchedulingPolicyUtils.h"
70 #include "utils/SessionConfigurationUtils.h"
71 #include "utils/TraceHFR.h"
72 #include "utils/Utils.h"
73 
74 #include <algorithm>
75 #include <optional>
76 #include <tuple>
77 
78 using namespace android::camera3;
79 using namespace android::camera3::SessionConfigurationUtils;
80 using namespace android::hardware::camera;
81 using namespace android::hardware::cameraservice::utils::conversion::aidl;
82 
83 namespace flags = com::android::internal::camera::flags;
84 namespace android {
85 
Camera3Device(std::shared_ptr<CameraServiceProxyWrapper> & cameraServiceProxyWrapper,std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,const std::string & id,bool overrideForPerfClass,int rotationOverride,bool legacyClient)86 Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
87         std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
88         const std::string &id, bool overrideForPerfClass, int rotationOverride,
89         bool legacyClient):
90         AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
91         mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
92         mId(id),
93         mLegacyClient(legacyClient),
94         mOperatingMode(NO_MODE),
95         mIsConstrainedHighSpeedConfiguration(false),
96         mIsCompositeJpegRDisabled(false),
97         mStatus(STATUS_UNINITIALIZED),
98         mStatusWaiters(0),
99         mUsePartialResult(false),
100         mNumPartialResults(1),
101         mDeviceTimeBaseIsRealtime(false),
102         mTimestampOffset(0),
103         mNextResultFrameNumber(0),
104         mNextReprocessResultFrameNumber(0),
105         mNextZslStillResultFrameNumber(0),
106         mNextShutterFrameNumber(0),
107         mNextReprocessShutterFrameNumber(0),
108         mNextZslStillShutterFrameNumber(0),
109         mListener(NULL),
110         mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
111         mLastTemplateId(-1),
112         mNeedFixupMonochromeTags(false),
113         mOverrideForPerfClass(overrideForPerfClass),
114         mRotationOverride(rotationOverride),
115         mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
116         mComposerOutput(false),
117         mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
118         mSettingsOverride(-1),
119         mActivePhysicalId("")
120 {
121     ATRACE_CALL();
122     ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.c_str());
123 }
124 
~Camera3Device()125 Camera3Device::~Camera3Device()
126 {
127     ATRACE_CALL();
128     ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.c_str());
129     disconnectImpl();
130 }
131 
getId() const132 const std::string& Camera3Device::getId() const {
133     return mId;
134 }
135 
initializeCommonLocked()136 status_t Camera3Device::initializeCommonLocked() {
137 
138     /** Start up status tracker thread */
139     mStatusTracker = new StatusTracker(this);
140     status_t res = mStatusTracker->run((std::string("C3Dev-") + mId + "-Status").c_str());
141     if (res != OK) {
142         SET_ERR_L("Unable to start status tracking thread: %s (%d)",
143                 strerror(-res), res);
144         mInterface->close();
145         mStatusTracker.clear();
146         return res;
147     }
148 
149     /** Register in-flight map to the status tracker */
150     mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
151 
152     /** Create buffer manager */
153     mBufferManager = new Camera3BufferManager();
154 
155     Vector<int32_t> sessionParamKeys;
156     camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
157             ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
158     if (sessionKeysEntry.count > 0) {
159         sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
160     }
161 
162     camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
163             ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
164     for (size_t i = 0; i < availableTestPatternModes.count; i++) {
165         if (availableTestPatternModes.data.i32[i] ==
166                 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
167             mSupportCameraMute = true;
168             mSupportTestPatternSolidColor = true;
169             break;
170         } else if (availableTestPatternModes.data.i32[i] ==
171                 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
172             mSupportCameraMute = true;
173             mSupportTestPatternSolidColor = false;
174         }
175     }
176 
177     camera_metadata_entry_t availableSettingsOverrides = mDeviceInfo.find(
178             ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES);
179     for (size_t i = 0; i < availableSettingsOverrides.count; i++) {
180         if (availableSettingsOverrides.data.i32[i] ==
181                 ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM) {
182             mSupportZoomOverride = true;
183             break;
184         }
185     }
186 
187     /** Start up request queue thread */
188     mRequestThread = createNewRequestThread(
189             this, mStatusTracker, mInterface, sessionParamKeys,
190             mUseHalBufManager, mSupportCameraMute, mRotationOverride,
191             mSupportZoomOverride);
192     res = mRequestThread->run((std::string("C3Dev-") + mId + "-ReqQueue").c_str());
193     if (res != OK) {
194         SET_ERR_L("Unable to start request queue thread: %s (%d)",
195                 strerror(-res), res);
196         mInterface->close();
197         mRequestThread.clear();
198         return res;
199     }
200 
201     setCameraMuteLocked(mCameraMuteInitial);
202 
203     mPreparerThread = new PreparerThread();
204 
205     internalUpdateStatusLocked(STATUS_UNCONFIGURED);
206     mNextStreamId = 0;
207     mFakeStreamId = NO_STREAM;
208     mNeedConfig = true;
209     mPauseStateNotify = false;
210     mIsInputStreamMultiResolution = false;
211 
212     // Measure the clock domain offset between camera and video/hw_composer
213     mTimestampOffset = getMonoToBoottimeOffset();
214     camera_metadata_entry timestampSource =
215             mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
216     if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
217             ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
218         mDeviceTimeBaseIsRealtime = true;
219     }
220 
221     // Will the HAL be sending in early partial result metadata?
222     camera_metadata_entry partialResultsCount =
223             mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
224     if (partialResultsCount.count > 0) {
225         mNumPartialResults = partialResultsCount.data.i32[0];
226         mUsePartialResult = (mNumPartialResults > 1);
227     }
228 
229     bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
230     if (usePrecorrectArray) {
231         res = mDistortionMappers[mId].setupStaticInfo(mDeviceInfo);
232         if (res != OK) {
233             SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
234             return res;
235         }
236     }
237 
238     mZoomRatioMappers[mId] = ZoomRatioMapper(&mDeviceInfo,
239             mSupportNativeZoomRatio, usePrecorrectArray);
240 
241     if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
242         mUHRCropAndMeteringRegionMappers[mId] =
243                 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
244     }
245 
246     if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
247         mRotateAndCropMappers.emplace(mId, &mDeviceInfo);
248     }
249 
250     // Hidl/AidlCamera3DeviceInjectionMethods
251     mInjectionMethods = createCamera3DeviceInjectionMethods(this);
252 
253     /** Start watchdog thread */
254     mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
255     res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
256     if (res != OK) {
257         SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
258                 strerror(-res), res);
259         return res;
260     }
261 
262     mSupportsExtensionKeys = areExtensionKeysSupported(mDeviceInfo);
263 
264     return OK;
265 }
266 
disconnect()267 status_t Camera3Device::disconnect() {
268     return disconnectImpl();
269 }
270 
disconnectImpl()271 status_t Camera3Device::disconnectImpl() {
272     ATRACE_CALL();
273     Mutex::Autolock il(mInterfaceLock);
274 
275     ALOGI("%s: E", __FUNCTION__);
276 
277     status_t res = OK;
278     std::vector<wp<Camera3StreamInterface>> streams;
279     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
280     {
281         Mutex::Autolock l(mLock);
282         if (mStatus == STATUS_UNINITIALIZED) return res;
283 
284         if (mRequestThread != NULL) {
285             if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
286                 res = mRequestThread->clear();
287                 if (res != OK) {
288                     SET_ERR_L("Can't stop streaming");
289                     // Continue to close device even in case of error
290                 } else {
291                     res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
292                                   /*requestThreadInvocation*/ false);
293                     if (res != OK) {
294                         SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
295                                 maxExpectedDuration);
296                         // Continue to close device even in case of error
297                     }
298                 }
299             }
300         }
301 
302         if (mStatus == STATUS_ERROR) {
303             CLOGE("Shutting down in an error state");
304         }
305 
306         if (mStatusTracker != NULL) {
307             mStatusTracker->requestExit();
308         }
309 
310         if (mRequestThread != NULL) {
311             mRequestThread->requestExit();
312         }
313 
314         streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
315         for (size_t i = 0; i < mOutputStreams.size(); i++) {
316             streams.push_back(mOutputStreams[i]);
317         }
318         if (mInputStream != nullptr) {
319             streams.push_back(mInputStream);
320         }
321     }
322 
323     // Joining done without holding mLock, otherwise deadlocks may ensue
324     // as the threads try to access parent state
325     if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
326         // HAL may be in a bad state, so waiting for request thread
327         // (which may be stuck in the HAL processCaptureRequest call)
328         // could be dangerous.
329         mRequestThread->join();
330     }
331 
332     if (mStatusTracker != NULL) {
333         mStatusTracker->join();
334     }
335 
336     if (mInjectionMethods->isInjecting()) {
337         mInjectionMethods->stopInjection();
338     }
339 
340     HalInterface* interface;
341     {
342         Mutex::Autolock l(mLock);
343         mRequestThread.clear();
344         Mutex::Autolock stLock(mTrackerLock);
345         mStatusTracker.clear();
346         interface = mInterface.get();
347     }
348 
349     // Call close without internal mutex held, as the HAL close may need to
350     // wait on assorted callbacks,etc, to complete before it can return.
351     mCameraServiceWatchdog->WATCH(interface->close());
352 
353     flushInflightRequests();
354 
355     {
356         Mutex::Autolock l(mLock);
357         mInterface->clear();
358         mOutputStreams.clear();
359         mInputStream.clear();
360         mDeletedStreams.clear();
361         mBufferManager.clear();
362         internalUpdateStatusLocked(STATUS_UNINITIALIZED);
363     }
364 
365     for (auto& weakStream : streams) {
366         sp<Camera3StreamInterface> stream = weakStream.promote();
367         if (stream != nullptr) {
368             ALOGE("%s: Stream %d leaked! strong reference (%d)!",
369                     __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
370         }
371     }
372     ALOGI("%s: X", __FUNCTION__);
373 
374     if (mCameraServiceWatchdog != NULL) {
375         mCameraServiceWatchdog->requestExit();
376         mCameraServiceWatchdog.clear();
377     }
378 
379     return res;
380 }
381 
382 // For dumping/debugging only -
383 // try to acquire a lock a few times, eventually give up to proceed with
384 // debug/dump operations
tryLockSpinRightRound(Mutex & lock)385 bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
386     bool gotLock = false;
387     for (size_t i = 0; i < kDumpLockAttempts; ++i) {
388         if (lock.tryLock() == NO_ERROR) {
389             gotLock = true;
390             break;
391         } else {
392             usleep(kDumpSleepDuration);
393         }
394     }
395     return gotLock;
396 }
397 
getMonoToBoottimeOffset()398 nsecs_t Camera3Device::getMonoToBoottimeOffset() {
399     // try three times to get the clock offset, choose the one
400     // with the minimum gap in measurements.
401     const int tries = 3;
402     nsecs_t bestGap, measured;
403     for (int i = 0; i < tries; ++i) {
404         const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
405         const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
406         const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
407         const nsecs_t gap = tmono2 - tmono;
408         if (i == 0 || gap < bestGap) {
409             bestGap = gap;
410             measured = tbase - ((tmono + tmono2) >> 1);
411         }
412     }
413     return measured;
414 }
415 
getJpegBufferSize(const CameraMetadata & info,uint32_t width,uint32_t height) const416 ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
417         uint32_t height) const {
418     // Get max jpeg size (area-wise) for default sensor pixel mode
419     camera3::Size maxDefaultJpegResolution =
420             SessionConfigurationUtils::getMaxJpegResolution(info,
421                     /*supportsUltraHighResolutionCapture*/false);
422     // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
423     // not ultra high res sensor
424     camera3::Size uhrMaxJpegResolution =
425             SessionConfigurationUtils::getMaxJpegResolution(info,
426                     /*isUltraHighResolution*/true);
427     if (maxDefaultJpegResolution.width == 0) {
428         ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
429                 __FUNCTION__, mId.c_str());
430         return BAD_VALUE;
431     }
432     bool useMaxSensorPixelModeThreshold = false;
433     if (uhrMaxJpegResolution.width != 0 &&
434             width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
435         // Use the ultra high res max jpeg size and max jpeg buffer size
436         useMaxSensorPixelModeThreshold = true;
437     }
438 
439     // Get max jpeg buffer size
440     ssize_t maxJpegBufferSize = 0;
441     camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
442     if (jpegBufMaxSize.count == 0) {
443         ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
444                 mId.c_str());
445         return BAD_VALUE;
446     }
447     maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
448 
449     camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
450     if (useMaxSensorPixelModeThreshold) {
451         maxJpegBufferSize =
452                 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
453                         maxDefaultJpegResolution, maxJpegBufferSize);
454         chosenMaxJpegResolution = uhrMaxJpegResolution;
455     }
456     assert(kMinJpegBufferSize < maxJpegBufferSize);
457 
458     // Calculate final jpeg buffer size for the given resolution.
459     float scaleFactor = ((float) (width * height)) /
460             (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
461     ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
462             kMinJpegBufferSize;
463     if (jpegBufferSize > maxJpegBufferSize) {
464         ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
465                   __FUNCTION__, maxJpegBufferSize);
466         jpegBufferSize = maxJpegBufferSize;
467     }
468     return jpegBufferSize;
469 }
470 
getPointCloudBufferSize(const CameraMetadata & info) const471 ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
472     const int FLOATS_PER_POINT=4;
473     camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
474     if (maxPointCount.count == 0) {
475         ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
476                 __FUNCTION__, mId.c_str());
477         return BAD_VALUE;
478     }
479     ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
480             maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
481     return maxBytesForPointCloud;
482 }
483 
getRawOpaqueBufferSize(const CameraMetadata & info,int32_t width,int32_t height,bool maxResolution) const484 ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
485         int32_t height, bool maxResolution) const {
486     const int PER_CONFIGURATION_SIZE = 3;
487     const int WIDTH_OFFSET = 0;
488     const int HEIGHT_OFFSET = 1;
489     const int SIZE_OFFSET = 2;
490     camera_metadata_ro_entry rawOpaqueSizes =
491         info.find(
492             camera3::SessionConfigurationUtils::getAppropriateModeTag(
493                     ANDROID_SENSOR_OPAQUE_RAW_SIZE,
494                     maxResolution));
495     size_t count = rawOpaqueSizes.count;
496     if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
497         ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
498                 __FUNCTION__, mId.c_str(), count);
499         return BAD_VALUE;
500     }
501 
502     for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
503         if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
504                 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
505             return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
506         }
507     }
508 
509     ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
510             __FUNCTION__, mId.c_str(), width, height);
511     return BAD_VALUE;
512 }
513 
dump(int fd,const Vector<String16> & args)514 status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
515     ATRACE_CALL();
516 
517     // Try to lock, but continue in case of failure (to avoid blocking in
518     // deadlocks)
519     bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
520     bool gotLock = tryLockSpinRightRound(mLock);
521 
522     ALOGW_IF(!gotInterfaceLock,
523             "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
524             mId.c_str(), __FUNCTION__);
525     ALOGW_IF(!gotLock,
526             "Camera %s: %s: Unable to lock main lock, proceeding anyway",
527             mId.c_str(), __FUNCTION__);
528 
529     bool dumpTemplates = false;
530 
531     String16 templatesOption("-t");
532     int n = args.size();
533     for (int i = 0; i < n; i++) {
534         if (args[i] == templatesOption) {
535             dumpTemplates = true;
536         }
537         if (args[i] == toString16(TagMonitor::kMonitorOption)) {
538             if (i + 1 < n) {
539                 std::string monitorTags = toStdString(args[i + 1]);
540                 if (monitorTags == "off") {
541                     mTagMonitor.disableMonitoring();
542                 } else {
543                     mTagMonitor.parseTagsToMonitor(monitorTags);
544                 }
545             } else {
546                 mTagMonitor.disableMonitoring();
547             }
548         }
549     }
550 
551     std::string lines;
552 
553     const char *status =
554             mStatus == STATUS_ERROR         ? "ERROR" :
555             mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
556             mStatus == STATUS_UNCONFIGURED  ? "UNCONFIGURED" :
557             mStatus == STATUS_CONFIGURED    ? "CONFIGURED" :
558             mStatus == STATUS_ACTIVE        ? "ACTIVE" :
559             "Unknown";
560 
561     lines += fmt::sprintf("    Device status: %s\n", status);
562     if (mStatus == STATUS_ERROR) {
563         lines += fmt::sprintf("    Error cause: %s\n", mErrorCause.c_str());
564     }
565     lines += "    Stream configuration:\n";
566     const char *mode =
567             mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
568             mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
569                     "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
570     lines += fmt::sprintf("    Operation mode: %s (%d) \n", mode, mOperatingMode);
571 
572     if (mInputStream != NULL) {
573         write(fd, lines.c_str(), lines.size());
574         mInputStream->dump(fd, args);
575     } else {
576         lines += "      No input stream.\n";
577         write(fd, lines.c_str(), lines.size());
578     }
579     for (size_t i = 0; i < mOutputStreams.size(); i++) {
580         mOutputStreams[i]->dump(fd,args);
581     }
582 
583     if (mBufferManager != NULL) {
584         lines = "    Camera3 Buffer Manager:\n";
585         write(fd, lines.c_str(), lines.size());
586         mBufferManager->dump(fd, args);
587     }
588 
589     lines = "    In-flight requests:\n";
590     if (mInFlightLock.try_lock()) {
591         if (mInFlightMap.size() == 0) {
592             lines += "      None\n";
593         } else {
594             for (size_t i = 0; i < mInFlightMap.size(); i++) {
595                 InFlightRequest r = mInFlightMap.valueAt(i);
596                 lines += fmt::sprintf("      Frame %d |  Timestamp: %" PRId64 ", metadata"
597                         " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
598                         r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
599                         r.numBuffersLeft);
600             }
601         }
602         mInFlightLock.unlock();
603     } else {
604         lines += "      Failed to acquire In-flight lock!\n";
605     }
606     write(fd, lines.c_str(), lines.size());
607 
608     if (mRequestThread != NULL) {
609         mRequestThread->dumpCaptureRequestLatency(fd,
610                 "    ProcessCaptureRequest latency histogram:");
611     }
612 
613     {
614         lines = "    Last request sent:\n";
615         write(fd, lines.c_str(), lines.size());
616 
617         CameraMetadata lastRequest = getLatestRequestLocked();
618         lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
619     }
620 
621     if (dumpTemplates) {
622         const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
623             "TEMPLATE_PREVIEW",
624             "TEMPLATE_STILL_CAPTURE",
625             "TEMPLATE_VIDEO_RECORD",
626             "TEMPLATE_VIDEO_SNAPSHOT",
627             "TEMPLATE_ZERO_SHUTTER_LAG",
628             "TEMPLATE_MANUAL",
629         };
630 
631         for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
632             camera_metadata_t *templateRequest = nullptr;
633             mInterface->constructDefaultRequestSettings(
634                     (camera_request_template_t) i, &templateRequest);
635             lines = fmt::sprintf("    HAL Request %s:\n", templateNames[i-1]);
636             if (templateRequest == nullptr) {
637                 lines += "       Not supported\n";
638                 write(fd, lines.c_str(), lines.size());
639             } else {
640                 write(fd, lines.c_str(), lines.size());
641                 dump_indented_camera_metadata(templateRequest,
642                         fd, /*verbosity*/2, /*indentation*/8);
643             }
644             free_camera_metadata(templateRequest);
645         }
646     }
647 
648     mTagMonitor.dumpMonitoredMetadata(fd);
649 
650     if (mInterface->valid()) {
651         lines = "     HAL device dump:\n";
652         write(fd, lines.c_str(), lines.size());
653         mInterface->dump(fd);
654     }
655 
656     if (gotLock) mLock.unlock();
657     if (gotInterfaceLock) mInterfaceLock.unlock();
658 
659     return OK;
660 }
661 
startWatchingTags(const std::string & tags)662 status_t Camera3Device::startWatchingTags(const std::string &tags) {
663     mTagMonitor.parseTagsToMonitor(tags);
664     return OK;
665 }
666 
stopWatchingTags()667 status_t Camera3Device::stopWatchingTags() {
668     mTagMonitor.disableMonitoring();
669     return OK;
670 }
671 
dumpWatchedEventsToVector(std::vector<std::string> & out)672 status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
673     mTagMonitor.getLatestMonitoredTagEvents(out);
674     return OK;
675 }
676 
infoPhysical(const std::string & physicalId) const677 const CameraMetadata& Camera3Device::infoPhysical(const std::string& physicalId) const {
678     ALOGVV("%s: E", __FUNCTION__);
679     if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
680                     mStatus == STATUS_ERROR)) {
681         ALOGW("%s: Access to static info %s!", __FUNCTION__,
682                 mStatus == STATUS_ERROR ?
683                 "when in error state" : "before init");
684     }
685     if (physicalId.empty()) {
686         return mDeviceInfo;
687     } else {
688         if (mPhysicalDeviceInfoMap.find(physicalId) != mPhysicalDeviceInfoMap.end()) {
689             return mPhysicalDeviceInfoMap.at(physicalId);
690         } else {
691             ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
692             return mDeviceInfo;
693         }
694     }
695 }
696 
info() const697 const CameraMetadata& Camera3Device::info() const {
698     return infoPhysical(/*physicalId*/ std::string());
699 }
700 
checkStatusOkToCaptureLocked()701 status_t Camera3Device::checkStatusOkToCaptureLocked() {
702     switch (mStatus) {
703         case STATUS_ERROR:
704             CLOGE("Device has encountered a serious error");
705             return INVALID_OPERATION;
706         case STATUS_UNINITIALIZED:
707             CLOGE("Device not initialized");
708             return INVALID_OPERATION;
709         case STATUS_UNCONFIGURED:
710         case STATUS_CONFIGURED:
711         case STATUS_ACTIVE:
712             // OK
713             break;
714         default:
715             SET_ERR_L("Unexpected status: %d", mStatus);
716             return INVALID_OPERATION;
717     }
718     return OK;
719 }
720 
convertMetadataListToRequestListLocked(const List<const PhysicalCameraSettingsList> & metadataList,const std::list<const SurfaceMap> & surfaceMaps,bool repeating,nsecs_t requestTimeNs,RequestList * requestList)721 status_t Camera3Device::convertMetadataListToRequestListLocked(
722         const List<const PhysicalCameraSettingsList> &metadataList,
723         const std::list<const SurfaceMap> &surfaceMaps,
724         bool repeating, nsecs_t requestTimeNs,
725         RequestList *requestList) {
726     if (requestList == NULL) {
727         CLOGE("requestList cannot be NULL.");
728         return BAD_VALUE;
729     }
730 
731     int32_t burstId = 0;
732     List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
733     std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
734     for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
735             ++metadataIt, ++surfaceMapIt) {
736         sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
737         if (newRequest == 0) {
738             CLOGE("Can't create capture request");
739             return BAD_VALUE;
740         }
741 
742         newRequest->mRepeating = repeating;
743         newRequest->mRequestTimeNs = requestTimeNs;
744 
745         // Setup burst Id and request Id
746         newRequest->mResultExtras.burstId = burstId++;
747         auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
748         if (requestIdEntry.count == 0) {
749             CLOGE("RequestID does not exist in metadata");
750             return BAD_VALUE;
751         }
752         newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
753 
754         requestList->push_back(newRequest);
755 
756         ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
757     }
758     if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
759         ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
760         return BAD_VALUE;
761     }
762 
763     // Setup batch size if this is a high speed video recording request.
764     if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
765         auto firstRequest = requestList->begin();
766         for (auto& outputStream : (*firstRequest)->mOutputStreams) {
767             if (outputStream->isVideoStream()) {
768                 applyMaxBatchSizeLocked(requestList, outputStream);
769                 break;
770             }
771         }
772     }
773 
774     return OK;
775 }
776 
capture(CameraMetadata & request,int64_t * lastFrameNumber)777 status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
778     ATRACE_CALL();
779 
780     List<const PhysicalCameraSettingsList> requestsList;
781     std::list<const SurfaceMap> surfaceMaps;
782     convertToRequestList(requestsList, surfaceMaps, request);
783 
784     return captureList(requestsList, surfaceMaps, lastFrameNumber);
785 }
786 
convertToRequestList(List<const PhysicalCameraSettingsList> & requestsList,std::list<const SurfaceMap> & surfaceMaps,const CameraMetadata & request)787 void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
788         std::list<const SurfaceMap>& surfaceMaps,
789         const CameraMetadata& request) {
790     PhysicalCameraSettingsList requestList;
791     requestList.push_back({getId(), request});
792     requestsList.push_back(requestList);
793 
794     SurfaceMap surfaceMap;
795     camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
796     // With no surface list passed in, stream and surface will have 1-to-1
797     // mapping. So the surface index is 0 for each stream in the surfaceMap.
798     for (size_t i = 0; i < streams.count; i++) {
799         surfaceMap[streams.data.i32[i]].push_back(0);
800     }
801     surfaceMaps.push_back(surfaceMap);
802 }
803 
submitRequestsHelper(const List<const PhysicalCameraSettingsList> & requests,const std::list<const SurfaceMap> & surfaceMaps,bool repeating,int64_t * lastFrameNumber)804 status_t Camera3Device::submitRequestsHelper(
805         const List<const PhysicalCameraSettingsList> &requests,
806         const std::list<const SurfaceMap> &surfaceMaps,
807         bool repeating,
808         /*out*/
809         int64_t *lastFrameNumber) {
810     ATRACE_CALL();
811     nsecs_t requestTimeNs = systemTime();
812 
813     Mutex::Autolock il(mInterfaceLock);
814     Mutex::Autolock l(mLock);
815 
816     status_t res = checkStatusOkToCaptureLocked();
817     if (res != OK) {
818         // error logged by previous call
819         return res;
820     }
821 
822     RequestList requestList;
823 
824     res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
825             repeating, requestTimeNs, /*out*/&requestList);
826     if (res != OK) {
827         // error logged by previous call
828         return res;
829     }
830 
831     if (repeating) {
832         res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
833     } else {
834         res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
835     }
836 
837     if (res == OK) {
838         waitUntilStateThenRelock(/*active*/true, kActiveTimeout, /*requestThreadInvocation*/false);
839         if (res != OK) {
840             SET_ERR_L("Can't transition to active in %f seconds!",
841                     kActiveTimeout/1e9);
842         }
843         ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.c_str(),
844               (*(requestList.begin()))->mResultExtras.requestId);
845     } else {
846         CLOGE("Cannot queue request. Impossible.");
847         return BAD_VALUE;
848     }
849 
850     return res;
851 }
852 
captureList(const List<const PhysicalCameraSettingsList> & requestsList,const std::list<const SurfaceMap> & surfaceMaps,int64_t * lastFrameNumber)853 status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
854                                     const std::list<const SurfaceMap> &surfaceMaps,
855                                     int64_t *lastFrameNumber) {
856     ATRACE_CALL();
857 
858     return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
859 }
860 
setStreamingRequest(const CameraMetadata & request,int64_t *)861 status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
862                                             int64_t* /*lastFrameNumber*/) {
863     ATRACE_CALL();
864 
865     List<const PhysicalCameraSettingsList> requestsList;
866     std::list<const SurfaceMap> surfaceMaps;
867     convertToRequestList(requestsList, surfaceMaps, request);
868 
869     return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
870                                    /*lastFrameNumber*/NULL);
871 }
872 
setStreamingRequestList(const List<const PhysicalCameraSettingsList> & requestsList,const std::list<const SurfaceMap> & surfaceMaps,int64_t * lastFrameNumber)873 status_t Camera3Device::setStreamingRequestList(
874         const List<const PhysicalCameraSettingsList> &requestsList,
875         const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
876     ATRACE_CALL();
877 
878     return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
879 }
880 
setUpRequestLocked(const PhysicalCameraSettingsList & request,const SurfaceMap & surfaceMap)881 sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
882         const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
883     status_t res;
884 
885     if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
886         // This point should only be reached via API1 (API2 must explicitly call configureStreams)
887         // so unilaterally select normal operating mode.
888         res = filterParamsAndConfigureLocked(request.begin()->metadata,
889                 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
890         // Stream configuration failed. Client might try other configuraitons.
891         if (res != OK) {
892             CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
893             return NULL;
894         } else if (mStatus == STATUS_UNCONFIGURED) {
895             // Stream configuration successfully configure to empty stream configuration.
896             CLOGE("No streams configured");
897             return NULL;
898         }
899     }
900 
901     sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
902     return newRequest;
903 }
904 
clearStreamingRequest(int64_t * lastFrameNumber)905 status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
906     ATRACE_CALL();
907     Mutex::Autolock il(mInterfaceLock);
908     Mutex::Autolock l(mLock);
909 
910     switch (mStatus) {
911         case STATUS_ERROR:
912             CLOGE("Device has encountered a serious error");
913             return INVALID_OPERATION;
914         case STATUS_UNINITIALIZED:
915             CLOGE("Device not initialized");
916             return INVALID_OPERATION;
917         case STATUS_UNCONFIGURED:
918         case STATUS_CONFIGURED:
919         case STATUS_ACTIVE:
920             // OK
921             break;
922         default:
923             SET_ERR_L("Unexpected status: %d", mStatus);
924             return INVALID_OPERATION;
925     }
926     ALOGV("Camera %s: Clearing repeating request", mId.c_str());
927 
928     return mRequestThread->clearRepeatingRequests(lastFrameNumber);
929 }
930 
waitUntilRequestReceived(int32_t requestId,nsecs_t timeout)931 status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
932     ATRACE_CALL();
933     Mutex::Autolock il(mInterfaceLock);
934 
935     return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
936 }
937 
createInputStream(uint32_t width,uint32_t height,int format,bool isMultiResolution,int * id)938 status_t Camera3Device::createInputStream(
939         uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
940     ATRACE_CALL();
941     Mutex::Autolock il(mInterfaceLock);
942     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
943     Mutex::Autolock l(mLock);
944     ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
945             mId.c_str(), mNextStreamId, width, height, format);
946 
947     status_t res;
948     bool wasActive = false;
949 
950     switch (mStatus) {
951         case STATUS_ERROR:
952             ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
953             return INVALID_OPERATION;
954         case STATUS_UNINITIALIZED:
955             ALOGE("%s: Device not initialized", __FUNCTION__);
956             return INVALID_OPERATION;
957         case STATUS_UNCONFIGURED:
958         case STATUS_CONFIGURED:
959             // OK
960             break;
961         case STATUS_ACTIVE:
962             ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
963             res = internalPauseAndWaitLocked(maxExpectedDuration,
964                           /*requestThreadInvocation*/ false);
965             if (res != OK) {
966                 SET_ERR_L("Can't pause captures to reconfigure streams!");
967                 return res;
968             }
969             wasActive = true;
970             break;
971         default:
972             SET_ERR_L("%s: Unexpected status: %d", mStatus);
973             return INVALID_OPERATION;
974     }
975     assert(mStatus != STATUS_ACTIVE);
976 
977     if (mInputStream != 0) {
978         ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
979         return INVALID_OPERATION;
980     }
981 
982     sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
983                 width, height, format);
984     newStream->setStatusTracker(mStatusTracker);
985 
986     mInputStream = newStream;
987     mIsInputStreamMultiResolution = isMultiResolution;
988 
989     *id = mNextStreamId++;
990 
991     // Continue captures if active at start
992     if (wasActive) {
993         ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
994         // Reuse current operating mode and session parameters for new stream config
995         res = configureStreamsLocked(mOperatingMode, mSessionParams);
996         if (res != OK) {
997             ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
998                     __FUNCTION__, mNextStreamId, strerror(-res), res);
999             return res;
1000         }
1001         internalResumeLocked();
1002     }
1003 
1004     ALOGV("Camera %s: Created input stream", mId.c_str());
1005     return OK;
1006 }
1007 
createStream(sp<Surface> consumer,uint32_t width,uint32_t height,int format,android_dataspace dataSpace,camera_stream_rotation_t rotation,int * id,const std::string & physicalCameraId,const std::unordered_set<int32_t> & sensorPixelModesUsed,std::vector<int> * surfaceIds,int streamSetId,bool isShared,bool isMultiResolution,uint64_t consumerUsage,int64_t dynamicRangeProfile,int64_t streamUseCase,int timestampBase,int mirrorMode,int32_t colorSpace,bool useReadoutTimestamp)1008 status_t Camera3Device::createStream(sp<Surface> consumer,
1009             uint32_t width, uint32_t height, int format,
1010             android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
1011             const std::string& physicalCameraId,
1012             const std::unordered_set<int32_t> &sensorPixelModesUsed,
1013             std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1014             uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1015             int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
1016     ATRACE_CALL();
1017 
1018     if (consumer == nullptr) {
1019         ALOGE("%s: consumer must not be null", __FUNCTION__);
1020         return BAD_VALUE;
1021     }
1022 
1023     std::vector<sp<Surface>> consumers;
1024     consumers.push_back(consumer);
1025 
1026     return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
1027             format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1028             streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
1029             streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1030 }
1031 
isRawFormat(int format)1032 static bool isRawFormat(int format) {
1033     switch (format) {
1034         case HAL_PIXEL_FORMAT_RAW16:
1035         case HAL_PIXEL_FORMAT_RAW12:
1036         case HAL_PIXEL_FORMAT_RAW10:
1037         case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1038             return true;
1039         default:
1040             return false;
1041     }
1042 }
1043 
createStream(const std::vector<sp<Surface>> & consumers,bool hasDeferredConsumer,uint32_t width,uint32_t height,int format,android_dataspace dataSpace,camera_stream_rotation_t rotation,int * id,const std::string & physicalCameraId,const std::unordered_set<int32_t> & sensorPixelModesUsed,std::vector<int> * surfaceIds,int streamSetId,bool isShared,bool isMultiResolution,uint64_t consumerUsage,int64_t dynamicRangeProfile,int64_t streamUseCase,int timestampBase,int mirrorMode,int32_t colorSpace,bool useReadoutTimestamp)1044 status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1045         bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1046         android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
1047         const std::string& physicalCameraId,
1048         const std::unordered_set<int32_t> &sensorPixelModesUsed,
1049         std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1050         uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1051         int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
1052     ATRACE_CALL();
1053 
1054     Mutex::Autolock il(mInterfaceLock);
1055     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
1056     Mutex::Autolock l(mLock);
1057     ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
1058             " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
1059             " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1060             " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
1061             mId.c_str(), mNextStreamId, width, height, format, dataSpace, rotation,
1062             consumerUsage, isShared, physicalCameraId.c_str(), isMultiResolution,
1063             dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1064             useReadoutTimestamp);
1065 
1066     status_t res;
1067     bool wasActive = false;
1068 
1069     switch (mStatus) {
1070         case STATUS_ERROR:
1071             CLOGE("Device has encountered a serious error");
1072             return INVALID_OPERATION;
1073         case STATUS_UNINITIALIZED:
1074             CLOGE("Device not initialized");
1075             return INVALID_OPERATION;
1076         case STATUS_UNCONFIGURED:
1077         case STATUS_CONFIGURED:
1078             // OK
1079             break;
1080         case STATUS_ACTIVE:
1081             ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
1082             res = internalPauseAndWaitLocked(maxExpectedDuration,
1083                           /*requestThreadInvocation*/ false);
1084             if (res != OK) {
1085                 SET_ERR_L("Can't pause captures to reconfigure streams!");
1086                 return res;
1087             }
1088             wasActive = true;
1089             break;
1090         default:
1091             SET_ERR_L("Unexpected status: %d", mStatus);
1092             return INVALID_OPERATION;
1093     }
1094     assert(mStatus != STATUS_ACTIVE);
1095 
1096     sp<Camera3OutputStream> newStream;
1097 
1098     if (consumers.size() == 0 && !hasDeferredConsumer) {
1099         ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1100         return BAD_VALUE;
1101     }
1102 
1103     if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
1104         ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1105         return BAD_VALUE;
1106     }
1107 
1108     if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1109         // We can't use one stream with a raw format in both sensor pixel modes since its going to
1110         // be found in only one sensor pixel mode.
1111         ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1112         return BAD_VALUE;
1113     }
1114     IPCTransport transport = getTransportType();
1115     if (format == HAL_PIXEL_FORMAT_BLOB) {
1116         ssize_t blobBufferSize;
1117         if (dataSpace == HAL_DATASPACE_DEPTH) {
1118             blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
1119             if (blobBufferSize <= 0) {
1120                 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1121                 return BAD_VALUE;
1122             }
1123         } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1124             blobBufferSize = width * height;
1125         } else {
1126             blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
1127             if (blobBufferSize <= 0) {
1128                 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1129                 return BAD_VALUE;
1130             }
1131         }
1132         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
1133                 width, height, blobBufferSize, format, dataSpace, rotation,
1134                 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
1135                 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
1136                 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1137     } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1138         bool maxResolution =
1139                 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1140                         sensorPixelModesUsed.end();
1141         ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1142                 height, maxResolution);
1143         if (rawOpaqueBufferSize <= 0) {
1144             SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1145             return BAD_VALUE;
1146         }
1147         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
1148                 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
1149                 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
1150                 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
1151                 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1152     } else if (isShared) {
1153         newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1154                 width, height, format, consumerUsage, dataSpace, rotation,
1155                 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
1156                 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
1157                 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1158     } else if (consumers.size() == 0 && hasDeferredConsumer) {
1159         newStream = new Camera3OutputStream(mNextStreamId,
1160                 width, height, format, consumerUsage, dataSpace, rotation,
1161                 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
1162                 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
1163                 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1164     } else {
1165         newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
1166                 width, height, format, dataSpace, rotation,
1167                 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
1168                 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
1169                 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
1170     }
1171 
1172     size_t consumerCount = consumers.size();
1173     for (size_t i = 0; i < consumerCount; i++) {
1174         int id = newStream->getSurfaceId(consumers[i]);
1175         if (id < 0) {
1176             SET_ERR_L("Invalid surface id");
1177             return BAD_VALUE;
1178         }
1179         if (surfaceIds != nullptr) {
1180             surfaceIds->push_back(id);
1181         }
1182     }
1183 
1184     newStream->setStatusTracker(mStatusTracker);
1185 
1186     newStream->setBufferManager(mBufferManager);
1187 
1188     newStream->setImageDumpMask(mImageDumpMask);
1189 
1190     res = mOutputStreams.add(mNextStreamId, newStream);
1191     if (res < 0) {
1192         SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
1193         return res;
1194     }
1195 
1196     mSessionStatsBuilder.addStream(mNextStreamId);
1197 
1198     *id = mNextStreamId++;
1199     mNeedConfig = true;
1200 
1201     // Continue captures if active at start
1202     if (wasActive) {
1203         ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
1204         // Reuse current operating mode and session parameters for new stream config
1205         res = configureStreamsLocked(mOperatingMode, mSessionParams);
1206         if (res != OK) {
1207             CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1208                     mNextStreamId, strerror(-res), res);
1209             return res;
1210         }
1211         internalResumeLocked();
1212     }
1213     ALOGV("Camera %s: Created new stream", mId.c_str());
1214     return OK;
1215 }
1216 
getStreamInfo(int id,StreamInfo * streamInfo)1217 status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
1218     ATRACE_CALL();
1219     if (nullptr == streamInfo) {
1220         return BAD_VALUE;
1221     }
1222     Mutex::Autolock il(mInterfaceLock);
1223     Mutex::Autolock l(mLock);
1224 
1225     switch (mStatus) {
1226         case STATUS_ERROR:
1227             CLOGE("Device has encountered a serious error");
1228             return INVALID_OPERATION;
1229         case STATUS_UNINITIALIZED:
1230             CLOGE("Device not initialized!");
1231             return INVALID_OPERATION;
1232         case STATUS_UNCONFIGURED:
1233         case STATUS_CONFIGURED:
1234         case STATUS_ACTIVE:
1235             // OK
1236             break;
1237         default:
1238             SET_ERR_L("Unexpected status: %d", mStatus);
1239             return INVALID_OPERATION;
1240     }
1241 
1242     sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1243     if (stream == nullptr) {
1244         CLOGE("Stream %d is unknown", id);
1245         return BAD_VALUE;
1246     }
1247 
1248     streamInfo->width  = stream->getWidth();
1249     streamInfo->height = stream->getHeight();
1250     streamInfo->format = stream->getFormat();
1251     streamInfo->dataSpace = stream->getDataSpace();
1252     streamInfo->formatOverridden = stream->isFormatOverridden();
1253     streamInfo->originalFormat = stream->getOriginalFormat();
1254     streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1255     streamInfo->originalDataSpace = stream->getOriginalDataSpace();
1256     streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
1257     streamInfo->colorSpace = stream->getColorSpace();
1258     return OK;
1259 }
1260 
setStreamTransform(int id,int transform)1261 status_t Camera3Device::setStreamTransform(int id,
1262         int transform) {
1263     ATRACE_CALL();
1264     Mutex::Autolock il(mInterfaceLock);
1265     Mutex::Autolock l(mLock);
1266 
1267     switch (mStatus) {
1268         case STATUS_ERROR:
1269             CLOGE("Device has encountered a serious error");
1270             return INVALID_OPERATION;
1271         case STATUS_UNINITIALIZED:
1272             CLOGE("Device not initialized");
1273             return INVALID_OPERATION;
1274         case STATUS_UNCONFIGURED:
1275         case STATUS_CONFIGURED:
1276         case STATUS_ACTIVE:
1277             // OK
1278             break;
1279         default:
1280             SET_ERR_L("Unexpected status: %d", mStatus);
1281             return INVALID_OPERATION;
1282     }
1283 
1284     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1285     if (stream == nullptr) {
1286         CLOGE("Stream %d does not exist", id);
1287         return BAD_VALUE;
1288     }
1289     return stream->setTransform(transform, false /*mayChangeMirror*/);
1290 }
1291 
deleteStream(int id)1292 status_t Camera3Device::deleteStream(int id) {
1293     ATRACE_CALL();
1294     Mutex::Autolock il(mInterfaceLock);
1295     Mutex::Autolock l(mLock);
1296     status_t res;
1297 
1298     ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.c_str(), id);
1299 
1300     // CameraDevice semantics require device to already be idle before
1301     // deleteStream is called, unlike for createStream.
1302     if (mStatus == STATUS_ACTIVE) {
1303         ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.c_str());
1304         return -EBUSY;
1305     }
1306 
1307     if (mStatus == STATUS_ERROR) {
1308         ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1309                 __FUNCTION__, mId.c_str());
1310         return -EBUSY;
1311     }
1312 
1313     sp<Camera3StreamInterface> deletedStream;
1314     sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1315     if (mInputStream != NULL && id == mInputStream->getId()) {
1316         deletedStream = mInputStream;
1317         mInputStream.clear();
1318     } else {
1319         if (stream == nullptr) {
1320             CLOGE("Stream %d does not exist", id);
1321             return BAD_VALUE;
1322         }
1323         mSessionStatsBuilder.removeStream(id);
1324     }
1325 
1326     // Delete output stream or the output part of a bi-directional stream.
1327     if (stream != nullptr) {
1328         deletedStream = stream;
1329         mOutputStreams.remove(id);
1330     }
1331 
1332     // Free up the stream endpoint so that it can be used by some other stream
1333     res = deletedStream->disconnect();
1334     if (res != OK) {
1335         SET_ERR_L("Can't disconnect deleted stream %d", id);
1336         // fall through since we want to still list the stream as deleted.
1337     }
1338     mDeletedStreams.add(deletedStream);
1339     mNeedConfig = true;
1340 
1341     return res;
1342 }
1343 
configureStreams(const CameraMetadata & sessionParams,int operatingMode)1344 status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
1345     ATRACE_CALL();
1346     ALOGV("%s: E", __FUNCTION__);
1347 
1348     Mutex::Autolock il(mInterfaceLock);
1349     Mutex::Autolock l(mLock);
1350 
1351     // In case the client doesn't include any session parameter, try a
1352     // speculative configuration using the values from the last cached
1353     // default request.
1354     if (sessionParams.isEmpty() &&
1355             ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
1356             (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1357         ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1358                 mLastTemplateId);
1359         return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1360                 operatingMode);
1361     }
1362 
1363     return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1364 }
1365 
filterParamsAndConfigureLocked(const CameraMetadata & params,int operatingMode)1366 status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& params,
1367         int operatingMode) {
1368     CameraMetadata filteredParams;
1369     SessionConfigurationUtils::filterParameters(params, mDeviceInfo,
1370             /*additionalKeys*/{}, mVendorTagId, filteredParams);
1371 
1372     camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1373             ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
1374 
1375     bool rotateAndCropSessionKey = false;
1376     bool autoframingSessionKey = false;
1377     for (size_t i = 0; i < availableSessionKeys.count; i++) {
1378         if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1379             rotateAndCropSessionKey = true;
1380         }
1381         if (ANDROID_CONTROL_AUTOFRAMING == availableSessionKeys.data.i32[i]) {
1382             autoframingSessionKey = true;
1383         }
1384     }
1385 
1386     if (rotateAndCropSessionKey || autoframingSessionKey) {
1387         sp<CaptureRequest> request = new CaptureRequest();
1388         PhysicalCameraSettings settingsList;
1389         settingsList.metadata = filteredParams;
1390         request->mSettingsList.push_back(settingsList);
1391 
1392         if (rotateAndCropSessionKey) {
1393             auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1394             if (rotateAndCropEntry.count > 0 &&
1395                     rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1396                 request->mRotateAndCropAuto = true;
1397             } else {
1398                 request->mRotateAndCropAuto = false;
1399             }
1400 
1401             overrideAutoRotateAndCrop(request, mRotationOverride, mRotateAndCropOverride);
1402         }
1403 
1404         if (autoframingSessionKey) {
1405             auto autoframingEntry = filteredParams.find(ANDROID_CONTROL_AUTOFRAMING);
1406             if (autoframingEntry.count > 0 &&
1407                     autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
1408                 overrideAutoframing(request, mAutoframingOverride);
1409             }
1410         }
1411 
1412         filteredParams = request->mSettingsList.begin()->metadata;
1413     }
1414 
1415     return configureStreamsLocked(operatingMode, filteredParams);
1416 }
1417 
getInputBufferProducer(sp<IGraphicBufferProducer> * producer)1418 status_t Camera3Device::getInputBufferProducer(
1419         sp<IGraphicBufferProducer> *producer) {
1420     ATRACE_CALL();
1421     Mutex::Autolock il(mInterfaceLock);
1422     Mutex::Autolock l(mLock);
1423 
1424     if (producer == NULL) {
1425         return BAD_VALUE;
1426     } else if (mInputStream == NULL) {
1427         return INVALID_OPERATION;
1428     }
1429 
1430     return mInputStream->getInputBufferProducer(producer);
1431 }
1432 
createDefaultRequest(camera_request_template_t templateId,CameraMetadata * request)1433 status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
1434         CameraMetadata *request) {
1435     ATRACE_CALL();
1436     ALOGV("%s: for template %d", __FUNCTION__, templateId);
1437 
1438     if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
1439         android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1440                 getCallingUid(), nullptr, 0);
1441         return BAD_VALUE;
1442     }
1443 
1444     Mutex::Autolock il(mInterfaceLock);
1445 
1446     {
1447         Mutex::Autolock l(mLock);
1448         switch (mStatus) {
1449             case STATUS_ERROR:
1450                 CLOGE("Device has encountered a serious error");
1451                 return INVALID_OPERATION;
1452             case STATUS_UNINITIALIZED:
1453                 CLOGE("Device is not initialized!");
1454                 return INVALID_OPERATION;
1455             case STATUS_UNCONFIGURED:
1456             case STATUS_CONFIGURED:
1457             case STATUS_ACTIVE:
1458                 // OK
1459                 break;
1460             default:
1461                 SET_ERR_L("Unexpected status: %d", mStatus);
1462                 return INVALID_OPERATION;
1463         }
1464 
1465         if (!mRequestTemplateCache[templateId].isEmpty()) {
1466             *request = mRequestTemplateCache[templateId];
1467             mLastTemplateId = templateId;
1468             return OK;
1469         }
1470     }
1471 
1472     camera_metadata_t *rawRequest;
1473     status_t res = mInterface->constructDefaultRequestSettings(
1474             (camera_request_template_t) templateId, &rawRequest);
1475 
1476     {
1477         Mutex::Autolock l(mLock);
1478         if (res == BAD_VALUE) {
1479             ALOGI("%s: template %d is not supported on this camera device",
1480                   __FUNCTION__, templateId);
1481             return res;
1482         } else if (res != OK) {
1483             CLOGE("Unable to construct request template %d: %s (%d)",
1484                     templateId, strerror(-res), res);
1485             return res;
1486         }
1487 
1488         set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1489         mRequestTemplateCache[templateId].acquire(rawRequest);
1490 
1491         res = overrideDefaultRequestKeys(&mRequestTemplateCache[templateId]);
1492         if (res != OK) {
1493             CLOGE("Failed to overrideDefaultRequestKeys for template %d: %s (%d)",
1494                     templateId, strerror(-res), res);
1495             return res;
1496         }
1497 
1498         *request = mRequestTemplateCache[templateId];
1499         mLastTemplateId = templateId;
1500     }
1501     return OK;
1502 }
1503 
waitUntilDrained()1504 status_t Camera3Device::waitUntilDrained() {
1505     ATRACE_CALL();
1506     Mutex::Autolock il(mInterfaceLock);
1507     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
1508     Mutex::Autolock l(mLock);
1509 
1510     return waitUntilDrainedLocked(maxExpectedDuration);
1511 }
1512 
waitUntilDrainedLocked(nsecs_t maxExpectedDuration)1513 status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
1514     switch (mStatus) {
1515         case STATUS_UNINITIALIZED:
1516         case STATUS_UNCONFIGURED:
1517             ALOGV("%s: Already idle", __FUNCTION__);
1518             return OK;
1519         case STATUS_CONFIGURED:
1520             // To avoid race conditions, check with tracker to be sure
1521         case STATUS_ERROR:
1522         case STATUS_ACTIVE:
1523             // Need to verify shut down
1524             break;
1525         default:
1526             SET_ERR_L("Unexpected status: %d",mStatus);
1527             return INVALID_OPERATION;
1528     }
1529     ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.c_str(),
1530             maxExpectedDuration);
1531     status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1532                            /*requestThreadInvocation*/ false);
1533     if (res != OK) {
1534         mStatusTracker->dumpActiveComponents();
1535         SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1536                 res);
1537     }
1538     return res;
1539 }
1540 
internalUpdateStatusLocked(Status status)1541 void Camera3Device::internalUpdateStatusLocked(Status status) {
1542     mStatus = status;
1543     mStatusIsInternal = mPauseStateNotify ? true : false;
1544     mRecentStatusUpdates.add({mStatus, mStatusIsInternal});
1545     mStatusChanged.broadcast();
1546 }
1547 
1548 // Pause to reconfigure
internalPauseAndWaitLocked(nsecs_t maxExpectedDuration,bool requestThreadInvocation)1549 status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration,
1550         bool requestThreadInvocation) {
1551     if (mRequestThread.get() != nullptr) {
1552         mRequestThread->setPaused(true);
1553     } else {
1554         return NO_INIT;
1555     }
1556 
1557     ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.c_str(),
1558           maxExpectedDuration);
1559     status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1560                            requestThreadInvocation);
1561     if (res != OK) {
1562         mStatusTracker->dumpActiveComponents();
1563         SET_ERR_L("Can't idle device in %f seconds!",
1564                 maxExpectedDuration/1e9);
1565     }
1566 
1567     return res;
1568 }
1569 
1570 // Resume after internalPauseAndWaitLocked
internalResumeLocked()1571 status_t Camera3Device::internalResumeLocked() {
1572     status_t res;
1573 
1574     mRequestThread->setPaused(false);
1575 
1576     ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.c_str(),
1577             kActiveTimeout);
1578     // internalResumeLocked is always called from a binder thread.
1579     res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout,
1580                   /*requestThreadInvocation*/ false);
1581     if (res != OK) {
1582         SET_ERR_L("Can't transition to active in %f seconds!",
1583                 kActiveTimeout/1e9);
1584     }
1585     mPauseStateNotify = false;
1586     return OK;
1587 }
1588 
waitUntilStateThenRelock(bool active,nsecs_t timeout,bool requestThreadInvocation)1589 status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout,
1590         bool requestThreadInvocation) {
1591     status_t res = OK;
1592 
1593     size_t startIndex = 0;
1594     if (mStatusWaiters == 0) {
1595         // Clear the list of recent statuses if there are no existing threads waiting on updates to
1596         // this status list
1597         mRecentStatusUpdates.clear();
1598     } else {
1599         // If other threads are waiting on updates to this status list, set the position of the
1600         // first element that this list will check rather than clearing the list.
1601         startIndex = mRecentStatusUpdates.size();
1602     }
1603 
1604     mStatusWaiters++;
1605 
1606     bool signalPipelineDrain = false;
1607     if (!active &&
1608             (mUseHalBufManager ||
1609                     (flags::session_hal_buf_manager() && mHalBufManagedStreamIds.size() != 0))) {
1610         auto streamIds = mOutputStreams.getStreamIds();
1611         if (mStatus == STATUS_ACTIVE) {
1612             mRequestThread->signalPipelineDrain(streamIds);
1613             signalPipelineDrain = true;
1614         }
1615         mRequestBufferSM.onWaitUntilIdle();
1616     }
1617 
1618     bool stateSeen = false;
1619     nsecs_t startTime = systemTime();
1620     do {
1621         if (mStatus == STATUS_ERROR) {
1622             // Device in error state. Return right away.
1623             break;
1624         }
1625         if (active == (mStatus == STATUS_ACTIVE) &&
1626             (requestThreadInvocation || !mStatusIsInternal)) {
1627             // Desired state is current
1628             break;
1629         }
1630 
1631         nsecs_t timeElapsed = systemTime() - startTime;
1632         nsecs_t timeToWait = timeout - timeElapsed;
1633         if (timeToWait <= 0) {
1634             // Thread woke up spuriously but has timed out since.
1635             // Force out of loop with TIMED_OUT result.
1636             res = TIMED_OUT;
1637             break;
1638         }
1639         res = mStatusChanged.waitRelative(mLock, timeToWait);
1640         if (res != OK) break;
1641 
1642         // This is impossible, but if not, could result in subtle deadlocks and invalid state
1643         // transitions.
1644         LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1645                 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1646                 __FUNCTION__);
1647 
1648         // Encountered desired state since we began waiting. Internal invocations coming from
1649         // request threads (such as reconfigureCamera) should be woken up immediately, whereas
1650         // invocations from binder threads (such as createInputStream) should only be woken up if
1651         // they are not paused. This avoids intermediate pause signals from reconfigureCamera as it
1652         // changes the status to active right after.
1653         for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
1654             if (mRecentStatusUpdates[i].status == STATUS_ERROR) {
1655                 // Device in error state. Return right away.
1656                 stateSeen = true;
1657                 break;
1658             }
1659             if (active == (mRecentStatusUpdates[i].status == STATUS_ACTIVE) &&
1660                 (requestThreadInvocation || !mRecentStatusUpdates[i].isInternal)) {
1661                 stateSeen = true;
1662                 break;
1663             }
1664         }
1665     } while (!stateSeen);
1666 
1667     if (signalPipelineDrain) {
1668         mRequestThread->resetPipelineDrain();
1669     }
1670 
1671     mStatusWaiters--;
1672 
1673     return res;
1674 }
1675 
1676 
setNotifyCallback(wp<NotificationListener> listener)1677 status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
1678     ATRACE_CALL();
1679     std::lock_guard<std::mutex> l(mOutputLock);
1680 
1681     if (listener != NULL && mListener != NULL) {
1682         ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1683     }
1684     mListener = listener;
1685     mRequestThread->setNotificationListener(listener);
1686     mPreparerThread->setNotificationListener(listener);
1687 
1688     return OK;
1689 }
1690 
willNotify3A()1691 bool Camera3Device::willNotify3A() {
1692     return false;
1693 }
1694 
waitForNextFrame(nsecs_t timeout)1695 status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
1696     ATRACE_CALL();
1697     std::unique_lock<std::mutex> l(mOutputLock);
1698 
1699     while (mResultQueue.empty()) {
1700         auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1701         if (st == std::cv_status::timeout) {
1702             return TIMED_OUT;
1703         }
1704     }
1705     return OK;
1706 }
1707 
getNextResult(CaptureResult * frame)1708 status_t Camera3Device::getNextResult(CaptureResult *frame) {
1709     ATRACE_CALL();
1710     std::lock_guard<std::mutex> l(mOutputLock);
1711 
1712     if (mResultQueue.empty()) {
1713         return NOT_ENOUGH_DATA;
1714     }
1715 
1716     if (frame == NULL) {
1717         ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1718         return BAD_VALUE;
1719     }
1720 
1721     CaptureResult &result = *(mResultQueue.begin());
1722     frame->mResultExtras = result.mResultExtras;
1723     frame->mMetadata.acquire(result.mMetadata);
1724     frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
1725     mResultQueue.erase(mResultQueue.begin());
1726 
1727     return OK;
1728 }
1729 
triggerAutofocus(uint32_t id)1730 status_t Camera3Device::triggerAutofocus(uint32_t id) {
1731     ATRACE_CALL();
1732     Mutex::Autolock il(mInterfaceLock);
1733 
1734     ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1735     // Mix-in this trigger into the next request and only the next request.
1736     RequestTrigger trigger[] = {
1737         {
1738             ANDROID_CONTROL_AF_TRIGGER,
1739             ANDROID_CONTROL_AF_TRIGGER_START
1740         },
1741         {
1742             ANDROID_CONTROL_AF_TRIGGER_ID,
1743             static_cast<int32_t>(id)
1744         }
1745     };
1746 
1747     return mRequestThread->queueTrigger(trigger,
1748                                         sizeof(trigger)/sizeof(trigger[0]));
1749 }
1750 
triggerCancelAutofocus(uint32_t id)1751 status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1752     ATRACE_CALL();
1753     Mutex::Autolock il(mInterfaceLock);
1754 
1755     ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1756     // Mix-in this trigger into the next request and only the next request.
1757     RequestTrigger trigger[] = {
1758         {
1759             ANDROID_CONTROL_AF_TRIGGER,
1760             ANDROID_CONTROL_AF_TRIGGER_CANCEL
1761         },
1762         {
1763             ANDROID_CONTROL_AF_TRIGGER_ID,
1764             static_cast<int32_t>(id)
1765         }
1766     };
1767 
1768     return mRequestThread->queueTrigger(trigger,
1769                                         sizeof(trigger)/sizeof(trigger[0]));
1770 }
1771 
triggerPrecaptureMetering(uint32_t id)1772 status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1773     ATRACE_CALL();
1774     Mutex::Autolock il(mInterfaceLock);
1775 
1776     ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1777     // Mix-in this trigger into the next request and only the next request.
1778     RequestTrigger trigger[] = {
1779         {
1780             ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1781             ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1782         },
1783         {
1784             ANDROID_CONTROL_AE_PRECAPTURE_ID,
1785             static_cast<int32_t>(id)
1786         }
1787     };
1788 
1789     return mRequestThread->queueTrigger(trigger,
1790                                         sizeof(trigger)/sizeof(trigger[0]));
1791 }
1792 
flush(int64_t * frameNumber)1793 status_t Camera3Device::flush(int64_t *frameNumber) {
1794     ATRACE_CALL();
1795     ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.c_str());
1796     Mutex::Autolock il(mInterfaceLock);
1797 
1798     {
1799         Mutex::Autolock l(mLock);
1800 
1801         // b/116514106 "disconnect()" can get called twice for the same device. The
1802         // camera device will not be initialized during the second run.
1803         if (mStatus == STATUS_UNINITIALIZED) {
1804             return OK;
1805         }
1806 
1807         mRequestThread->clear(/*out*/frameNumber);
1808 
1809         // Stop session and stream counter
1810         mSessionStatsBuilder.stopCounter();
1811     }
1812 
1813     // Calculate expected duration for flush with additional buffer time in ms for watchdog
1814     uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
1815     status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1816             maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1817 
1818     return res;
1819 }
1820 
prepare(int streamId)1821 status_t Camera3Device::prepare(int streamId) {
1822     return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1823 }
1824 
prepare(int maxCount,int streamId)1825 status_t Camera3Device::prepare(int maxCount, int streamId) {
1826     ATRACE_CALL();
1827     ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.c_str(), streamId);
1828     Mutex::Autolock il(mInterfaceLock);
1829     Mutex::Autolock l(mLock);
1830 
1831     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1832     if (stream == nullptr) {
1833         CLOGE("Stream %d does not exist", streamId);
1834         return BAD_VALUE;
1835     }
1836 
1837     if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
1838         CLOGE("Stream %d has already been a request target", streamId);
1839         return BAD_VALUE;
1840     }
1841 
1842     if (mRequestThread->isStreamPending(stream)) {
1843         CLOGE("Stream %d is already a target in a pending request", streamId);
1844         return BAD_VALUE;
1845     }
1846 
1847     return mPreparerThread->prepare(maxCount, stream);
1848 }
1849 
tearDown(int streamId)1850 status_t Camera3Device::tearDown(int streamId) {
1851     ATRACE_CALL();
1852     ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.c_str(), streamId);
1853     Mutex::Autolock il(mInterfaceLock);
1854     Mutex::Autolock l(mLock);
1855 
1856     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1857     if (stream == nullptr) {
1858         CLOGE("Stream %d does not exist", streamId);
1859         return BAD_VALUE;
1860     }
1861 
1862     if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1863         CLOGE("Stream %d is a target of a in-progress request", streamId);
1864         return BAD_VALUE;
1865     }
1866 
1867     return stream->tearDown();
1868 }
1869 
addBufferListenerForStream(int streamId,wp<Camera3StreamBufferListener> listener)1870 status_t Camera3Device::addBufferListenerForStream(int streamId,
1871         wp<Camera3StreamBufferListener> listener) {
1872     ATRACE_CALL();
1873     ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.c_str(),
1874             streamId);
1875     Mutex::Autolock il(mInterfaceLock);
1876     Mutex::Autolock l(mLock);
1877 
1878     sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1879     if (stream == nullptr) {
1880         CLOGE("Stream %d does not exist", streamId);
1881         return BAD_VALUE;
1882     }
1883     stream->addBufferListener(listener);
1884 
1885     return OK;
1886 }
1887 
getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream)1888 float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1889     camera_metadata_entry minDurations =
1890             mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1891     for (size_t i = 0; i < minDurations.count; i += 4) {
1892         if (minDurations.data.i64[i] == stream->getOriginalFormat()
1893                 && minDurations.data.i64[i+1] == stream->getWidth()
1894                 && minDurations.data.i64[i+2] == stream->getHeight()) {
1895             int64_t minFrameDuration = minDurations.data.i64[i+3];
1896             return 1e9f / minFrameDuration;
1897         }
1898     }
1899     return 0.0f;
1900 }
1901 
1902 /**
1903  * Methods called by subclasses
1904  */
1905 
notifyStatus(bool idle)1906 void Camera3Device::notifyStatus(bool idle) {
1907     ATRACE_CALL();
1908     std::vector<int> streamIds;
1909     std::vector<hardware::CameraStreamStats> streamStats;
1910     float sessionMaxPreviewFps = 0.0f;
1911 
1912     {
1913         // Need mLock to safely update state and synchronize to current
1914         // state of methods in flight.
1915         Mutex::Autolock l(mLock);
1916         // We can get various system-idle notices from the status tracker
1917         // while starting up. Only care about them if we've actually sent
1918         // in some requests recently.
1919         if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1920             return;
1921         }
1922         ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.c_str(),
1923                 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
1924         internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
1925 
1926         // Skip notifying listener if we're doing some user-transparent
1927         // state changes
1928         if (mPauseStateNotify) return;
1929 
1930         for (size_t i = 0; i < mOutputStreams.size(); i++) {
1931             auto stream = mOutputStreams[i];
1932             if (stream.get() == nullptr) continue;
1933 
1934             float streamMaxPreviewFps = getMaxPreviewFps(stream);
1935             sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1936 
1937             // Populate stream statistics in case of Idle
1938             if (idle) {
1939                 streamIds.push_back(stream->getId());
1940                 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1941                 int64_t usage = 0LL;
1942                 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
1943                 if (camera3Stream != nullptr) {
1944                     usage = camera3Stream->getUsage();
1945                     streamUseCase = camera3Stream->getStreamUseCase();
1946                 }
1947                 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1948                     stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
1949                     stream->getMaxHalBuffers(),
1950                     stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
1951                     stream->getDynamicRangeProfile(), streamUseCase,
1952                     stream->getColorSpace());
1953             }
1954         }
1955     }
1956 
1957     sp<NotificationListener> listener;
1958     {
1959         std::lock_guard<std::mutex> l(mOutputLock);
1960         listener = mListener.promote();
1961     }
1962     status_t res = OK;
1963     if (listener != nullptr) {
1964         if (idle) {
1965             // Get session stats from the builder, and notify the listener.
1966             int64_t requestCount, resultErrorCount;
1967             bool deviceError;
1968             std::pair<int32_t, int32_t> mostRequestedFpsRange;
1969             std::map<int, StreamStats> streamStatsMap;
1970             mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1971                     &deviceError, &mostRequestedFpsRange, &streamStatsMap);
1972             for (size_t i = 0; i < streamIds.size(); i++) {
1973                 int streamId = streamIds[i];
1974                 auto stats = streamStatsMap.find(streamId);
1975                 if (stats != streamStatsMap.end()) {
1976                     streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1977                     streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1978                     streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1979                     streamStats[i].mHistogramType =
1980                             hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1981                     streamStats[i].mHistogramBins.assign(
1982                             stats->second.mCaptureLatencyBins.begin(),
1983                             stats->second.mCaptureLatencyBins.end());
1984                     streamStats[i].mHistogramCounts.assign(
1985                            stats->second.mCaptureLatencyHistogram.begin(),
1986                            stats->second.mCaptureLatencyHistogram.end());
1987                 }
1988             }
1989             listener->notifyIdle(requestCount, resultErrorCount, deviceError,
1990                 mostRequestedFpsRange, streamStats);
1991         } else {
1992             res = listener->notifyActive(sessionMaxPreviewFps);
1993         }
1994     }
1995     if (res != OK) {
1996         SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1997                 strerror(-res), res);
1998     }
1999 }
2000 
setConsumerSurfaces(int streamId,const std::vector<sp<Surface>> & consumers,std::vector<int> * surfaceIds)2001 status_t Camera3Device::setConsumerSurfaces(int streamId,
2002         const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
2003     ATRACE_CALL();
2004     ALOGV("%s: Camera %s: set consumer surface for stream %d",
2005             __FUNCTION__, mId.c_str(), streamId);
2006 
2007     if (surfaceIds == nullptr) {
2008         return BAD_VALUE;
2009     }
2010 
2011     Mutex::Autolock il(mInterfaceLock);
2012     Mutex::Autolock l(mLock);
2013 
2014     if (consumers.size() == 0) {
2015         CLOGE("No consumer is passed!");
2016         return BAD_VALUE;
2017     }
2018 
2019     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2020     if (stream == nullptr) {
2021         CLOGE("Stream %d is unknown", streamId);
2022         return BAD_VALUE;
2023     }
2024 
2025     // isConsumerConfigurationDeferred will be off after setConsumers
2026     bool isDeferred = stream->isConsumerConfigurationDeferred();
2027     status_t res = stream->setConsumers(consumers);
2028     if (res != OK) {
2029         CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2030         return res;
2031     }
2032 
2033     for (auto &consumer : consumers) {
2034         int id = stream->getSurfaceId(consumer);
2035         if (id < 0) {
2036             CLOGE("Invalid surface id!");
2037             return BAD_VALUE;
2038         }
2039         surfaceIds->push_back(id);
2040     }
2041 
2042     if (isDeferred) {
2043         if (!stream->isConfiguring()) {
2044             CLOGE("Stream %d was already fully configured.", streamId);
2045             return INVALID_OPERATION;
2046         }
2047 
2048         res = stream->finishConfiguration();
2049         if (res != OK) {
2050             // If finishConfiguration fails due to abandoned surface, do not set
2051             // device to error state.
2052             bool isSurfaceAbandoned =
2053                     (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2054             if (!isSurfaceAbandoned) {
2055                 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2056                         stream->getId(), strerror(-res), res);
2057             }
2058             return res;
2059         }
2060     }
2061 
2062     return OK;
2063 }
2064 
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)2065 status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2066         const std::vector<OutputStreamInfo> &outputInfo,
2067         const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2068     Mutex::Autolock il(mInterfaceLock);
2069     Mutex::Autolock l(mLock);
2070 
2071     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2072     if (stream == nullptr) {
2073         CLOGE("Stream %d is unknown", streamId);
2074         return BAD_VALUE;
2075     }
2076 
2077     for (const auto &it : removedSurfaceIds) {
2078         if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2079             CLOGE("Shared surface still part of a pending request!");
2080             return -EBUSY;
2081         }
2082     }
2083 
2084     status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2085     if (res != OK) {
2086         CLOGE("Stream %d failed to update stream (error %d %s) ",
2087               streamId, res, strerror(-res));
2088         if (res == UNKNOWN_ERROR) {
2089             SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2090                     __FUNCTION__);
2091         }
2092         return res;
2093     }
2094 
2095     return res;
2096 }
2097 
dropStreamBuffers(bool dropping,int streamId)2098 status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2099     Mutex::Autolock il(mInterfaceLock);
2100     Mutex::Autolock l(mLock);
2101 
2102     sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2103     if (stream == nullptr) {
2104         ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2105         return BAD_VALUE;
2106     }
2107 
2108     if (dropping) {
2109         mSessionStatsBuilder.stopCounter(streamId);
2110     } else {
2111         mSessionStatsBuilder.startCounter(streamId);
2112     }
2113     return stream->dropBuffers(dropping);
2114 }
2115 
2116 /**
2117  * Camera3Device private methods
2118  */
2119 
createCaptureRequest(const PhysicalCameraSettingsList & request,const SurfaceMap & surfaceMap)2120 sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
2121         const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
2122     ATRACE_CALL();
2123 
2124     sp<CaptureRequest> newRequest = new CaptureRequest();
2125     newRequest->mSettingsList = request;
2126 
2127     camera_metadata_entry_t inputStreams =
2128             newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
2129     if (inputStreams.count > 0) {
2130         if (mInputStream == NULL ||
2131                 mInputStream->getId() != inputStreams.data.i32[0]) {
2132             CLOGE("Request references unknown input stream %d",
2133                     inputStreams.data.u8[0]);
2134             return NULL;
2135         }
2136 
2137         if (mInputStream->isConfiguring()) {
2138             SET_ERR_L("%s: input stream %d is not configured!",
2139                     __FUNCTION__, mInputStream->getId());
2140             return NULL;
2141         }
2142         // Check if stream prepare is blocking requests.
2143         if (mInputStream->isBlockedByPrepare()) {
2144             CLOGE("Request references an input stream that's being prepared!");
2145             return NULL;
2146         }
2147 
2148         newRequest->mInputStream = mInputStream;
2149         newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
2150     }
2151 
2152     camera_metadata_entry_t streams =
2153             newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
2154     if (streams.count == 0) {
2155         CLOGE("Zero output streams specified!");
2156         return NULL;
2157     }
2158 
2159     for (size_t i = 0; i < streams.count; i++) {
2160         sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2161         if (stream == nullptr) {
2162             CLOGE("Request references unknown stream %d",
2163                     streams.data.i32[i]);
2164             return NULL;
2165         }
2166         // It is illegal to include a deferred consumer output stream into a request
2167         auto iter = surfaceMap.find(streams.data.i32[i]);
2168         if (iter != surfaceMap.end()) {
2169             const std::vector<size_t>& surfaces = iter->second;
2170             for (const auto& surface : surfaces) {
2171                 if (stream->isConsumerConfigurationDeferred(surface)) {
2172                     CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2173                           "due to deferred consumer", stream->getId(), surface);
2174                     return NULL;
2175                 }
2176             }
2177             newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
2178         }
2179 
2180         if (stream->isConfiguring()) {
2181             SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2182             return NULL;
2183         }
2184         // Check if stream prepare is blocking requests.
2185         if (stream->isBlockedByPrepare()) {
2186             CLOGE("Request references an output stream that's being prepared!");
2187             return NULL;
2188         }
2189 
2190         newRequest->mOutputStreams.push(stream);
2191     }
2192     newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
2193     newRequest->mBatchSize = 1;
2194 
2195     auto rotateAndCropEntry =
2196             newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2197     if (rotateAndCropEntry.count > 0 &&
2198             rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2199         newRequest->mRotateAndCropAuto = true;
2200     } else {
2201         newRequest->mRotateAndCropAuto = false;
2202     }
2203 
2204     auto autoframingEntry =
2205             newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2206     if (autoframingEntry.count > 0 &&
2207             autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2208         newRequest->mAutoframingAuto = true;
2209     } else {
2210         newRequest->mAutoframingAuto = false;
2211     }
2212 
2213     auto zoomRatioEntry =
2214             newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2215     if (zoomRatioEntry.count > 0 &&
2216             zoomRatioEntry.data.f[0] == 1.0f) {
2217         newRequest->mZoomRatioIs1x = true;
2218     } else {
2219         newRequest->mZoomRatioIs1x = false;
2220     }
2221 
2222     if (mSupportCameraMute) {
2223         for (auto& settings : newRequest->mSettingsList) {
2224             auto testPatternModeEntry =
2225                     settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2226             settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2227                     testPatternModeEntry.data.i32[0] :
2228                     ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2229 
2230             auto testPatternDataEntry =
2231                     settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2232             if (testPatternDataEntry.count >= 4) {
2233                 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2234                         sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2235             } else {
2236                 settings.mOriginalTestPatternData[0] = 0;
2237                 settings.mOriginalTestPatternData[1] = 0;
2238                 settings.mOriginalTestPatternData[2] = 0;
2239                 settings.mOriginalTestPatternData[3] = 0;
2240             }
2241         }
2242     }
2243 
2244     if (mSupportZoomOverride) {
2245         for (auto& settings : newRequest->mSettingsList) {
2246             auto settingsOverrideEntry =
2247                     settings.metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
2248             settings.mOriginalSettingsOverride = settingsOverrideEntry.count > 0 ?
2249                     settingsOverrideEntry.data.i32[0] :
2250                     ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
2251         }
2252     }
2253 
2254     return newRequest;
2255 }
2256 
cancelStreamsConfigurationLocked()2257 void Camera3Device::cancelStreamsConfigurationLocked() {
2258     int res = OK;
2259     if (mInputStream != NULL && mInputStream->isConfiguring()) {
2260         res = mInputStream->cancelConfiguration();
2261         if (res != OK) {
2262             CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2263                     mInputStream->getId(), strerror(-res), res);
2264         }
2265     }
2266 
2267     for (size_t i = 0; i < mOutputStreams.size(); i++) {
2268         sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
2269         if (outputStream->isConfiguring()) {
2270             res = outputStream->cancelConfiguration();
2271             if (res != OK) {
2272                 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2273                         outputStream->getId(), strerror(-res), res);
2274             }
2275         }
2276     }
2277 
2278     // Return state to that at start of call, so that future configures
2279     // properly clean things up
2280     internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2281     mNeedConfig = true;
2282 
2283     res = mPreparerThread->resume();
2284     if (res != OK) {
2285         ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.c_str());
2286     }
2287 }
2288 
checkAbandonedStreamsLocked()2289 bool Camera3Device::checkAbandonedStreamsLocked() {
2290     if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2291         return true;
2292     }
2293 
2294     for (size_t i = 0; i < mOutputStreams.size(); i++) {
2295         auto stream = mOutputStreams[i];
2296         if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2297             return true;
2298         }
2299     }
2300 
2301     return false;
2302 }
2303 
reconfigureCamera(const CameraMetadata & sessionParams,int clientStatusId)2304 bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
2305     ATRACE_CALL();
2306     bool ret = false;
2307 
2308     nsecs_t startTime = systemTime();
2309 
2310     // We must not hold mInterfaceLock here since this function is called from
2311     // RequestThread::threadLoop and holding mInterfaceLock could lead to
2312     // deadlocks (http://b/143513518)
2313     nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2314 
2315     // Make sure status tracker is flushed
2316     mStatusTracker->flushPendingStates();
2317 
2318     Mutex::Autolock l(mLock);
2319     if (checkAbandonedStreamsLocked()) {
2320         ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2321                 __FUNCTION__);
2322         return true;
2323     }
2324 
2325     status_t rc = NO_ERROR;
2326     bool markClientActive = false;
2327     if (mStatus == STATUS_ACTIVE) {
2328         markClientActive = true;
2329         mPauseStateNotify = true;
2330         mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2331 
2332         // This is essentially the same as calling rc = internalPauseAndWaitLocked(..), except that
2333         // we don't want to call setPaused(true) to avoid it interfering with setPaused() called
2334         // from createInputStream/createStream.
2335         rc = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
2336                 /*requestThreadInvocation*/ true);
2337         if (rc != OK) {
2338             mStatusTracker->dumpActiveComponents();
2339             SET_ERR_L("Can't idle device in %f seconds!",
2340                 maxExpectedDuration/1e9);
2341         }
2342     }
2343 
2344     if (rc == NO_ERROR) {
2345         mNeedConfig = true;
2346         rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2347         if (rc == NO_ERROR) {
2348             ret = true;
2349             mPauseStateNotify = false;
2350             //Moving to active state while holding 'mLock' is important.
2351             //There could be pending calls to 'create-/deleteStream' which
2352             //will trigger another stream configuration while the already
2353             //present streams end up with outstanding buffers that will
2354             //not get drained.
2355             internalUpdateStatusLocked(STATUS_ACTIVE);
2356 
2357             mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode,
2358                     true /*internalReconfig*/, ns2ms(systemTime() - startTime));
2359         } else if (rc == DEAD_OBJECT) {
2360             // DEAD_OBJECT can be returned if either the consumer surface is
2361             // abandoned, or the HAL has died.
2362             // - If the HAL has died, configureStreamsLocked call will set
2363             // device to error state,
2364             // - If surface is abandoned, we should not set device to error
2365             // state.
2366             ALOGE("Failed to re-configure camera due to abandoned surface");
2367         } else {
2368             SET_ERR_L("Failed to re-configure camera: %d", rc);
2369         }
2370     } else {
2371         ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2372     }
2373 
2374     if (markClientActive) {
2375         mStatusTracker->markComponentActive(clientStatusId);
2376     }
2377 
2378     return ret;
2379 }
2380 
2381 
configureStreamsLocked(int operatingMode,const CameraMetadata & sessionParams,bool notifyRequestThread)2382 status_t Camera3Device::configureStreamsLocked(int operatingMode,
2383         const CameraMetadata& sessionParams, bool notifyRequestThread) {
2384     ATRACE_CALL();
2385     status_t res;
2386     // Stream/surface setup can include a lot of binder IPC. Raise the
2387     // thread priority when running the binder IPC heavy configuration
2388     // sequence.
2389     RunThreadWithRealtimePriority priorityBump;
2390 
2391     if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
2392         CLOGE("Not idle");
2393         return INVALID_OPERATION;
2394     }
2395 
2396     if (operatingMode < 0) {
2397         CLOGE("Invalid operating mode: %d", operatingMode);
2398         return BAD_VALUE;
2399     }
2400 
2401     bool isConstrainedHighSpeed =
2402             CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
2403 
2404     if (mOperatingMode != operatingMode) {
2405         mNeedConfig = true;
2406         mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2407         mOperatingMode = operatingMode;
2408     }
2409 
2410     // Reset min expected duration when session is reconfigured.
2411     mMinExpectedDuration = 0;
2412 
2413     // In case called from configureStreams, abort queued input buffers not belonging to
2414     // any pending requests.
2415     if (mInputStream != NULL && notifyRequestThread) {
2416         while (true) {
2417             camera_stream_buffer_t inputBuffer;
2418             camera3::Size inputBufferSize;
2419             status_t res = mInputStream->getInputBuffer(&inputBuffer,
2420                     &inputBufferSize, /*respectHalLimit*/ false);
2421             if (res != OK) {
2422                 // Exhausted acquiring all input buffers.
2423                 break;
2424             }
2425 
2426             inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
2427             res = mInputStream->returnInputBuffer(inputBuffer);
2428             if (res != OK) {
2429                 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2430                         "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2431             }
2432         }
2433     }
2434 
2435     if (!mNeedConfig) {
2436         ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2437         return OK;
2438     }
2439 
2440     // Workaround for device HALv3.2 or older spec bug - zero streams requires
2441     // adding a fake stream instead.
2442     // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2443     if (mOutputStreams.size() == 0) {
2444         addFakeStreamLocked();
2445     } else {
2446         tryRemoveFakeStreamLocked();
2447     }
2448 
2449     // Override stream use case based on "adb shell command"
2450     overrideStreamUseCaseLocked();
2451 
2452     // Start configuring the streams
2453     ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.c_str());
2454 
2455     mPreparerThread->pause();
2456 
2457     camera_stream_configuration config;
2458     config.operation_mode = mOperatingMode;
2459     config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2460     config.input_is_multi_resolution = false;
2461 
2462     Vector<camera3::camera_stream_t*> streams;
2463     streams.setCapacity(config.num_streams);
2464     std::vector<uint32_t> bufferSizes(config.num_streams, 0);
2465 
2466 
2467     if (mInputStream != NULL) {
2468         camera3::camera_stream_t *inputStream;
2469         inputStream = mInputStream->startConfiguration();
2470         if (inputStream == NULL) {
2471             CLOGE("Can't start input stream configuration");
2472             cancelStreamsConfigurationLocked();
2473             return INVALID_OPERATION;
2474         }
2475         streams.add(inputStream);
2476 
2477         config.input_is_multi_resolution = mIsInputStreamMultiResolution;
2478     }
2479 
2480     mGroupIdPhysicalCameraMap.clear();
2481     mComposerOutput = false;
2482     for (size_t i = 0; i < mOutputStreams.size(); i++) {
2483 
2484         // Don't configure bidi streams twice, nor add them twice to the list
2485         if (mOutputStreams[i].get() ==
2486             static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2487 
2488             config.num_streams--;
2489             continue;
2490         }
2491 
2492         camera3::camera_stream_t *outputStream;
2493         outputStream = mOutputStreams[i]->startConfiguration();
2494         if (outputStream == NULL) {
2495             CLOGE("Can't start output stream configuration");
2496             cancelStreamsConfigurationLocked();
2497             return INVALID_OPERATION;
2498         }
2499         streams.add(outputStream);
2500 
2501         if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
2502             size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2503                                                                 // always occupy the initial entry.
2504             if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2505                     (outputStream->data_space ==
2506                      static_cast<android_dataspace_t>(
2507                          aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
2508                 bufferSizes[k] = static_cast<uint32_t>(
2509                         getJpegBufferSize(infoPhysical(outputStream->physical_camera_id),
2510                                 outputStream->width, outputStream->height));
2511             } else if (outputStream->data_space ==
2512                     static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2513                 bufferSizes[k] = outputStream->width * outputStream->height;
2514             } else {
2515                 ALOGW("%s: Blob dataSpace %d not supported",
2516                         __FUNCTION__, outputStream->data_space);
2517             }
2518         }
2519 
2520         if (mOutputStreams[i]->isMultiResolution()) {
2521             int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2522             const std::string &physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2523             mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2524         }
2525 
2526         if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2527             mComposerOutput = true;
2528         }
2529     }
2530 
2531     config.streams = streams.editArray();
2532     config.hal_buffer_managed_streams = mHalBufManagedStreamIds;
2533     config.use_hal_buf_manager = mUseHalBufManager;
2534 
2535     // Do the HAL configuration; will potentially touch stream
2536     // max_buffers, usage, priv fields, data_space and format
2537     // fields for IMPLEMENTATION_DEFINED formats as well as hal buffer managed
2538     // streams and use_hal_buf_manager (in case aconfig flag session_hal_buf_manager
2539     // is not enabled but the HAL supports session specific hal buffer manager).
2540 
2541     int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
2542     const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
2543     res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
2544     sessionParams.unlock(sessionBuffer);
2545 
2546     if (res == BAD_VALUE) {
2547         // HAL rejected this set of streams as unsupported, clean up config
2548         // attempt and return to unconfigured state
2549         CLOGE("Set of requested inputs/outputs not supported by HAL");
2550         cancelStreamsConfigurationLocked();
2551         return BAD_VALUE;
2552     } else if (res != OK) {
2553         // Some other kind of error from configure_streams - this is not
2554         // expected
2555         SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2556                 strerror(-res), res);
2557         return res;
2558     }
2559     // It is possible that use hal buffer manager behavior was changed by the
2560     // configureStreams call.
2561     mUseHalBufManager = config.use_hal_buf_manager;
2562     if (flags::session_hal_buf_manager()) {
2563         bool prevSessionHalBufManager = (mHalBufManagedStreamIds.size() != 0);
2564         // It is possible that configureStreams() changed config.hal_buffer_managed_streams
2565         mHalBufManagedStreamIds = config.hal_buffer_managed_streams;
2566 
2567         bool thisSessionHalBufManager = mHalBufManagedStreamIds.size() != 0;
2568 
2569         if (prevSessionHalBufManager && !thisSessionHalBufManager) {
2570             mRequestBufferSM.deInit();
2571         } else if (!prevSessionHalBufManager && thisSessionHalBufManager) {
2572             res = mRequestBufferSM.initialize(mStatusTracker);
2573             if (res != OK) {
2574                 SET_ERR_L("%s: Camera %s: RequestBuffer State machine couldn't be initialized!",
2575                           __FUNCTION__, mId.c_str());
2576                 return res;
2577             }
2578         }
2579         mRequestThread->setHalBufferManagedStreams(mHalBufManagedStreamIds);
2580     }
2581 
2582     // Finish all stream configuration immediately.
2583     // TODO: Try to relax this later back to lazy completion, which should be
2584     // faster
2585 
2586     if (mInputStream != NULL && mInputStream->isConfiguring()) {
2587         bool streamReConfigured = false;
2588         res = mInputStream->finishConfiguration(&streamReConfigured);
2589         if (res != OK) {
2590             CLOGE("Can't finish configuring input stream %d: %s (%d)", mInputStream->getId(),
2591                   strerror(-res), res);
2592             cancelStreamsConfigurationLocked();
2593             if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2594                 return DEAD_OBJECT;
2595             }
2596             return BAD_VALUE;
2597         }
2598         if (streamReConfigured) {
2599             mInterface->onStreamReConfigured(mInputStream->getId());
2600         }
2601     }
2602 
2603     for (size_t i = 0; i < mOutputStreams.size(); i++) {
2604         sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
2605         if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
2606             bool streamReConfigured = false;
2607             res = outputStream->finishConfiguration(&streamReConfigured);
2608             if (res != OK) {
2609                 CLOGE("Can't finish configuring output stream %d: %s (%d)", outputStream->getId(),
2610                       strerror(-res), res);
2611                 cancelStreamsConfigurationLocked();
2612                 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2613                     return DEAD_OBJECT;
2614                 }
2615                 return BAD_VALUE;
2616             }
2617             if (streamReConfigured) {
2618                 mInterface->onStreamReConfigured(outputStream->getId());
2619             }
2620         }
2621     }
2622 
2623     mRequestThread->setComposerSurface(mComposerOutput);
2624 
2625     // Request thread needs to know to avoid using repeat-last-settings protocol
2626     // across configure_streams() calls
2627     if (notifyRequestThread) {
2628         mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2629                 sessionParams, mGroupIdPhysicalCameraMap);
2630     }
2631 
2632     char value[PROPERTY_VALUE_MAX];
2633     property_get("camera.fifo.disable", value, "0");
2634     int32_t disableFifo = atoi(value);
2635     if (disableFifo != 1) {
2636         // Boost priority of request thread to SCHED_FIFO.
2637         pid_t requestThreadTid = mRequestThread->getTid();
2638         res = SchedulingPolicyUtils::requestPriorityDirect(
2639                 getpid(), requestThreadTid, RunThreadWithRealtimePriority::kRequestThreadPriority);
2640         if (res != OK) {
2641             ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2642                     strerror(-res), res);
2643         } else {
2644             ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2645         }
2646     }
2647 
2648     // Update device state
2649     const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2650     const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2651     bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2652     sessionParams.unlock(newSessionParams);
2653     mSessionParams.unlock(currentSessionParams);
2654     if (updateSessionParams)  {
2655         mSessionParams = sessionParams;
2656     }
2657 
2658     mNeedConfig = false;
2659 
2660     internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
2661             STATUS_CONFIGURED : STATUS_UNCONFIGURED);
2662 
2663     ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.c_str());
2664 
2665     // tear down the deleted streams after configure streams.
2666     mDeletedStreams.clear();
2667 
2668     auto rc = mPreparerThread->resume();
2669     if (rc != OK) {
2670         SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.c_str());
2671         return rc;
2672     }
2673 
2674     if (mFakeStreamId == NO_STREAM) {
2675         mRequestBufferSM.onStreamsConfigured();
2676     }
2677 
2678     // First call injectCamera() and then run configureStreamsLocked() case:
2679     // Since the streams configuration of the injection camera is based on the internal camera, we
2680     // must wait until the internal camera configure streams before running the injection job to
2681     // configure the injection streams.
2682     if (mInjectionMethods->isInjecting()) {
2683         ALOGD("%s: Injection camera %s: Start to configure streams.",
2684               __FUNCTION__, mInjectionMethods->getInjectedCamId().c_str());
2685         res = mInjectionMethods->injectCamera(config, bufferSizes);
2686         if (res != OK) {
2687             ALOGE("Can't finish inject camera process!");
2688             return res;
2689         }
2690     } else {
2691         // First run configureStreamsLocked() and then call injectCamera() case:
2692         // If the stream configuration has been completed and camera deive is active, but the
2693         // injection camera has not been injected yet, we need to store the stream configuration of
2694         // the internal camera (because the stream configuration of the injection camera is based
2695         // on the internal camera). When injecting occurs later, this configuration can be used by
2696         // the injection camera.
2697         ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2698               " injection camera has not been injected yet.", __FUNCTION__);
2699         mInjectionMethods->storeInjectionConfig(config, bufferSizes);
2700     }
2701 
2702     return OK;
2703 }
2704 
addFakeStreamLocked()2705 status_t Camera3Device::addFakeStreamLocked() {
2706     ATRACE_CALL();
2707     status_t res;
2708 
2709     if (mFakeStreamId != NO_STREAM) {
2710         // Should never be adding a second fake stream when one is already
2711         // active
2712         SET_ERR_L("%s: Camera %s: A fake stream already exists!",
2713                 __FUNCTION__, mId.c_str());
2714         return INVALID_OPERATION;
2715     }
2716 
2717     ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.c_str());
2718 
2719     sp<Camera3OutputStreamInterface> fakeStream =
2720             new Camera3FakeStream(mNextStreamId);
2721 
2722     res = mOutputStreams.add(mNextStreamId, fakeStream);
2723     if (res < 0) {
2724         SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
2725         return res;
2726     }
2727 
2728     mFakeStreamId = mNextStreamId;
2729     mNextStreamId++;
2730 
2731     return OK;
2732 }
2733 
tryRemoveFakeStreamLocked()2734 status_t Camera3Device::tryRemoveFakeStreamLocked() {
2735     ATRACE_CALL();
2736     status_t res;
2737 
2738     if (mFakeStreamId == NO_STREAM) return OK;
2739     if (mOutputStreams.size() == 1) return OK;
2740 
2741     ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.c_str());
2742 
2743     // Ok, have a fake stream and there's at least one other output stream,
2744     // so remove the fake
2745 
2746     sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
2747     if (deletedStream == nullptr) {
2748         SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
2749         return INVALID_OPERATION;
2750     }
2751     mOutputStreams.remove(mFakeStreamId);
2752 
2753     // Free up the stream endpoint so that it can be used by some other stream
2754     res = deletedStream->disconnect();
2755     if (res != OK) {
2756         SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
2757         // fall through since we want to still list the stream as deleted.
2758     }
2759     mDeletedStreams.add(deletedStream);
2760     mFakeStreamId = NO_STREAM;
2761 
2762     return res;
2763 }
2764 
setErrorState(const char * fmt,...)2765 void Camera3Device::setErrorState(const char *fmt, ...) {
2766     ATRACE_CALL();
2767     Mutex::Autolock l(mLock);
2768     va_list args;
2769     va_start(args, fmt);
2770 
2771     setErrorStateLockedV(fmt, args);
2772 
2773     va_end(args);
2774 }
2775 
setErrorStateV(const char * fmt,va_list args)2776 void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
2777     ATRACE_CALL();
2778     Mutex::Autolock l(mLock);
2779     setErrorStateLockedV(fmt, args);
2780 }
2781 
setErrorStateLocked(const char * fmt,...)2782 void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2783     va_list args;
2784     va_start(args, fmt);
2785 
2786     setErrorStateLockedV(fmt, args);
2787 
2788     va_end(args);
2789 }
2790 
setErrorStateLockedV(const char * fmt,va_list args)2791 void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
2792     // Print out all error messages to log
2793     std::string errorCause;
2794     base::StringAppendV(&errorCause, fmt, args);
2795     ALOGE("Camera %s: %s", mId.c_str(), errorCause.c_str());
2796 
2797     // But only do error state transition steps for the first error
2798     if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
2799 
2800     mErrorCause = errorCause;
2801 
2802     if (mRequestThread != nullptr) {
2803         mRequestThread->setPaused(true);
2804     }
2805     internalUpdateStatusLocked(STATUS_ERROR);
2806 
2807     // Notify upstream about a device error
2808     sp<NotificationListener> listener = mListener.promote();
2809     if (listener != NULL) {
2810         listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
2811                 CaptureResultExtras());
2812         mSessionStatsBuilder.onDeviceError();
2813     }
2814 
2815     // Save stack trace. View by dumping it later.
2816     CameraTraces::saveTrace();
2817     // TODO: consider adding errorCause and client pid/procname
2818 }
2819 
2820 /**
2821  * In-flight request management
2822  */
2823 
registerInFlight(uint32_t frameNumber,int32_t numBuffers,CaptureResultExtras resultExtras,bool hasInput,bool hasAppCallback,nsecs_t minExpectedDuration,nsecs_t maxExpectedDuration,bool isFixedFps,const std::set<std::set<std::string>> & physicalCameraIds,bool isStillCapture,bool isZslCapture,bool rotateAndCropAuto,bool autoframingAuto,const std::set<std::string> & cameraIdsWithZoom,const SurfaceMap & outputSurfaces,nsecs_t requestTimeNs)2824 status_t Camera3Device::registerInFlight(uint32_t frameNumber,
2825         int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
2826         bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
2827         bool isFixedFps, const std::set<std::set<std::string>>& physicalCameraIds,
2828         bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
2829         const std::set<std::string>& cameraIdsWithZoom,
2830         const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
2831     ATRACE_CALL();
2832     std::lock_guard<std::mutex> l(mInFlightLock);
2833 
2834     ssize_t res;
2835     res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
2836             hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
2837             isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2838             requestTimeNs, outputSurfaces));
2839     if (res < 0) return res;
2840 
2841     if (mInFlightMap.size() == 1) {
2842         // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2843         // avoid a deadlock during reprocess requests.
2844         Mutex::Autolock l(mTrackerLock);
2845         if (mStatusTracker != nullptr) {
2846             mStatusTracker->markComponentActive(mInFlightStatusId);
2847         }
2848     }
2849 
2850     mExpectedInflightDuration += maxExpectedDuration;
2851     return OK;
2852 }
2853 
onInflightEntryRemovedLocked(nsecs_t duration)2854 void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
2855     // Indicate idle inFlightMap to the status tracker
2856     if (mInFlightMap.size() == 0) {
2857         mRequestBufferSM.onInflightMapEmpty();
2858         // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2859         // avoid a deadlock during reprocess requests.
2860         Mutex::Autolock l(mTrackerLock);
2861         if (mStatusTracker != nullptr) {
2862             mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2863         }
2864     }
2865     mExpectedInflightDuration -= duration;
2866 }
2867 
checkInflightMapLengthLocked()2868 void Camera3Device::checkInflightMapLengthLocked() {
2869     // Validation check - if we have too many in-flight frames with long total inflight duration,
2870     // something has likely gone wrong. This might still be legit only if application send in
2871     // a long burst of long exposure requests.
2872     if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2873         if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2874             CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2875                     mInFlightMap.size(), mExpectedInflightDuration);
2876         } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2877                 kInFlightWarnLimitHighSpeed) {
2878             CLOGW("In-flight list too large for high speed configuration: %zu,"
2879                     "total inflight duration %" PRIu64,
2880                     mInFlightMap.size(), mExpectedInflightDuration);
2881         }
2882     }
2883 }
2884 
onInflightMapFlushedLocked()2885 void Camera3Device::onInflightMapFlushedLocked() {
2886     mExpectedInflightDuration = 0;
2887 }
2888 
removeInFlightMapEntryLocked(int idx)2889 void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2890     ATRACE_HFR_CALL();
2891     nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2892     mInFlightMap.removeItemsAt(idx, 1);
2893 
2894     onInflightEntryRemovedLocked(duration);
2895 }
2896 
2897 
flushInflightRequests()2898 void Camera3Device::flushInflightRequests() {
2899     ATRACE_CALL();
2900     sp<NotificationListener> listener;
2901     {
2902         std::lock_guard<std::mutex> l(mOutputLock);
2903         listener = mListener.promote();
2904     }
2905 
2906     FlushInflightReqStates states {
2907         mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2908         mHalBufManagedStreamIds, listener, *this, *mInterface, *this,
2909         mSessionStatsBuilder};
2910 
2911     camera3::flushInflightRequests(states);
2912 }
2913 
getLatestRequestLocked()2914 CameraMetadata Camera3Device::getLatestRequestLocked() {
2915     ALOGV("%s", __FUNCTION__);
2916 
2917     CameraMetadata retVal;
2918 
2919     if (mRequestThread != NULL) {
2920         retVal = mRequestThread->getLatestRequest();
2921     }
2922 
2923     return retVal;
2924 }
2925 
monitorMetadata(TagMonitor::eventSource source,int64_t frameNumber,nsecs_t timestamp,const CameraMetadata & metadata,const std::unordered_map<std::string,CameraMetadata> & physicalMetadata,const camera_stream_buffer_t * outputBuffers,uint32_t numOutputBuffers,int32_t inputStreamId)2926 void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
2927         int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2928         const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
2929         const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2930         int32_t inputStreamId) {
2931 
2932     mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2933             physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
2934 }
2935 
collectRequestStats(int64_t frameNumber,const CameraMetadata & request)2936 void Camera3Device::collectRequestStats(int64_t frameNumber, const CameraMetadata &request) {
2937     if (flags::analytics_24q3()) {
2938         auto entry = request.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
2939         if (entry.count >= 2) {
2940             mSessionStatsBuilder.incFpsRequestedCount(
2941                 entry.data.i32[0], entry.data.i32[1], frameNumber);
2942         }
2943     }
2944 }
2945 
cleanupNativeHandles(std::vector<native_handle_t * > * handles,bool closeFd)2946 void Camera3Device::cleanupNativeHandles(
2947         std::vector<native_handle_t*> *handles, bool closeFd) {
2948     if (handles == nullptr) {
2949         return;
2950     }
2951     if (closeFd) {
2952         for (auto& handle : *handles) {
2953             native_handle_close(handle);
2954         }
2955     }
2956     for (auto& handle : *handles) {
2957         native_handle_delete(handle);
2958     }
2959     handles->clear();
2960     return;
2961 }
2962 
2963 /**
2964  * HalInterface inner class methods
2965  */
2966 
getInflightBufferKeys(std::vector<std::pair<int32_t,int32_t>> * out)2967 void Camera3Device::HalInterface::getInflightBufferKeys(
2968         std::vector<std::pair<int32_t, int32_t>>* out) {
2969     mBufferRecords.getInflightBufferKeys(out);
2970     return;
2971 }
2972 
getInflightRequestBufferKeys(std::vector<uint64_t> * out)2973 void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2974         std::vector<uint64_t>* out) {
2975     mBufferRecords.getInflightRequestBufferKeys(out);
2976     return;
2977 }
2978 
verifyBufferIds(int32_t streamId,std::vector<uint64_t> & bufIds)2979 bool Camera3Device::HalInterface::verifyBufferIds(
2980         int32_t streamId, std::vector<uint64_t>& bufIds) {
2981     return mBufferRecords.verifyBufferIds(streamId, bufIds);
2982 }
2983 
isHalBufferManagedStream(int32_t streamId) const2984 bool Camera3Device::HalInterface::isHalBufferManagedStream(int32_t streamId) const {
2985     return (mUseHalBufManager || (flags::session_hal_buf_manager() &&
2986                                   contains(mHalBufManagedStreamIds, streamId)));
2987 }
2988 
popInflightBuffer(int32_t frameNumber,int32_t streamId,buffer_handle_t ** buffer)2989 status_t Camera3Device::HalInterface::popInflightBuffer(
2990         int32_t frameNumber, int32_t streamId,
2991         /*out*/ buffer_handle_t **buffer) {
2992     return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
2993 }
2994 
pushInflightRequestBuffer(uint64_t bufferId,buffer_handle_t * buf,int32_t streamId)2995 status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
2996         uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
2997     return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
2998 }
2999 
3000 // Find and pop a buffer_handle_t based on bufferId
popInflightRequestBuffer(uint64_t bufferId,buffer_handle_t ** buffer,int32_t * streamId)3001 status_t Camera3Device::HalInterface::popInflightRequestBuffer(
3002         uint64_t bufferId,
3003         /*out*/ buffer_handle_t** buffer,
3004         /*optional out*/ int32_t* streamId) {
3005     return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
3006 }
3007 
getBufferId(const buffer_handle_t & buf,int streamId)3008 std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3009         const buffer_handle_t& buf, int streamId) {
3010     return mBufferRecords.getBufferId(buf, streamId);
3011 }
3012 
removeOneBufferCache(int streamId,const native_handle_t * handle)3013 uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
3014         const native_handle_t* handle) {
3015     return mBufferRecords.removeOneBufferCache(streamId, handle);
3016 }
3017 
onBufferFreed(int streamId,const native_handle_t * handle)3018 void Camera3Device::HalInterface::onBufferFreed(
3019         int streamId, const native_handle_t* handle) {
3020     uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3021     std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3022     if (bufferId != BUFFER_ID_NO_BUFFER) {
3023         mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3024     }
3025 }
3026 
onStreamReConfigured(int streamId)3027 void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
3028     std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3029     std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3030     for (auto bufferId : bufIds) {
3031         mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3032     }
3033 }
3034 
3035 /**
3036  * RequestThread inner class methods
3037  */
3038 
RequestThread(wp<Camera3Device> parent,sp<StatusTracker> statusTracker,sp<HalInterface> interface,const Vector<int32_t> & sessionParamKeys,bool useHalBufManager,bool supportCameraMute,int rotationOverride,bool supportSettingsOverride)3039 Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
3040         sp<StatusTracker> statusTracker,
3041         sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3042         bool useHalBufManager,
3043         bool supportCameraMute,
3044         int rotationOverride,
3045         bool supportSettingsOverride) :
3046         Thread(/*canCallJava*/false),
3047         mParent(parent),
3048         mStatusTracker(statusTracker),
3049         mInterface(interface),
3050         mListener(nullptr),
3051         mId(getId(parent)),
3052         mRequestClearing(false),
3053         mFirstRepeating(false),
3054         mReconfigured(false),
3055         mDoPause(false),
3056         mPaused(true),
3057         mNotifyPipelineDrain(false),
3058         mPrevTriggers(0),
3059         mFrameNumber(0),
3060         mLatestRequestId(NAME_NOT_FOUND),
3061         mLatestFailedRequestId(NAME_NOT_FOUND),
3062         mCurrentAfTriggerId(0),
3063         mCurrentPreCaptureTriggerId(0),
3064         mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
3065         mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
3066         mComposerOutput(false),
3067         mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
3068         mSettingsOverride(ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF),
3069         mRepeatingLastFrameNumber(
3070             hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
3071         mPrepareVideoStream(false),
3072         mConstrainedMode(false),
3073         mRequestLatency(kRequestLatencyBinSize),
3074         mSessionParamKeys(sessionParamKeys),
3075         mLatestSessionParams(sessionParamKeys.size()),
3076         mUseHalBufManager(useHalBufManager),
3077         mSupportCameraMute(supportCameraMute),
3078         mRotationOverride(rotationOverride),
3079         mSupportSettingsOverride(supportSettingsOverride) {
3080     mStatusId = statusTracker->addComponent("RequestThread");
3081     mVndkVersion = getVNDKVersionFromProp(__ANDROID_API_FUTURE__);
3082 }
3083 
~RequestThread()3084 Camera3Device::RequestThread::~RequestThread() {}
3085 
setNotificationListener(wp<NotificationListener> listener)3086 void Camera3Device::RequestThread::setNotificationListener(
3087         wp<NotificationListener> listener) {
3088     ATRACE_CALL();
3089     Mutex::Autolock l(mRequestLock);
3090     mListener = listener;
3091 }
3092 
configurationComplete(bool isConstrainedHighSpeed,const CameraMetadata & sessionParams,const std::map<int32_t,std::set<std::string>> & groupIdPhysicalCameraMap)3093 void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3094         const CameraMetadata& sessionParams,
3095         const std::map<int32_t, std::set<std::string>>& groupIdPhysicalCameraMap) {
3096     ATRACE_CALL();
3097     Mutex::Autolock l(mRequestLock);
3098     mReconfigured = true;
3099     mLatestSessionParams = sessionParams;
3100     mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
3101     // Prepare video stream for high speed recording.
3102     mPrepareVideoStream = isConstrainedHighSpeed;
3103     mConstrainedMode = isConstrainedHighSpeed;
3104 }
3105 
queueRequestList(List<sp<CaptureRequest>> & requests,int64_t * lastFrameNumber)3106 status_t Camera3Device::RequestThread::queueRequestList(
3107         List<sp<CaptureRequest> > &requests,
3108         /*out*/
3109         int64_t *lastFrameNumber) {
3110     ATRACE_CALL();
3111     Mutex::Autolock l(mRequestLock);
3112     for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3113             ++it) {
3114         mRequestQueue.push_back(*it);
3115     }
3116 
3117     if (lastFrameNumber != NULL) {
3118         *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3119         ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3120               __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3121               *lastFrameNumber);
3122     }
3123 
3124     unpauseForNewRequests();
3125 
3126     return OK;
3127 }
3128 
3129 
queueTrigger(RequestTrigger trigger[],size_t count)3130 status_t Camera3Device::RequestThread::queueTrigger(
3131         RequestTrigger trigger[],
3132         size_t count) {
3133     ATRACE_CALL();
3134     Mutex::Autolock l(mTriggerMutex);
3135     status_t ret;
3136 
3137     for (size_t i = 0; i < count; ++i) {
3138         ret = queueTriggerLocked(trigger[i]);
3139 
3140         if (ret != OK) {
3141             return ret;
3142         }
3143     }
3144 
3145     return OK;
3146 }
3147 
getId(const wp<Camera3Device> & device)3148 const std::string& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3149     static std::string deadId("<DeadDevice>");
3150     sp<Camera3Device> d = device.promote();
3151     if (d != nullptr) return d->mId;
3152     return deadId;
3153 }
3154 
queueTriggerLocked(RequestTrigger trigger)3155 status_t Camera3Device::RequestThread::queueTriggerLocked(
3156         RequestTrigger trigger) {
3157 
3158     uint32_t tag = trigger.metadataTag;
3159     ssize_t index = mTriggerMap.indexOfKey(tag);
3160 
3161     switch (trigger.getTagType()) {
3162         case TYPE_BYTE:
3163         // fall-through
3164         case TYPE_INT32:
3165             break;
3166         default:
3167             ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3168                     trigger.getTagType());
3169             return INVALID_OPERATION;
3170     }
3171 
3172     /**
3173      * Collect only the latest trigger, since we only have 1 field
3174      * in the request settings per trigger tag, and can't send more than 1
3175      * trigger per request.
3176      */
3177     if (index != NAME_NOT_FOUND) {
3178         mTriggerMap.editValueAt(index) = trigger;
3179     } else {
3180         mTriggerMap.add(tag, trigger);
3181     }
3182 
3183     return OK;
3184 }
3185 
setRepeatingRequests(const RequestList & requests,int64_t * lastFrameNumber)3186 status_t Camera3Device::RequestThread::setRepeatingRequests(
3187         const RequestList &requests,
3188         /*out*/
3189         int64_t *lastFrameNumber) {
3190     ATRACE_CALL();
3191     Mutex::Autolock l(mRequestLock);
3192     if (lastFrameNumber != NULL) {
3193         *lastFrameNumber = mRepeatingLastFrameNumber;
3194     }
3195     mRepeatingRequests.clear();
3196     mFirstRepeating = true;
3197     mRepeatingRequests.insert(mRepeatingRequests.begin(),
3198             requests.begin(), requests.end());
3199 
3200     unpauseForNewRequests();
3201 
3202     mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
3203     return OK;
3204 }
3205 
isRepeatingRequestLocked(const sp<CaptureRequest> & requestIn)3206 bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
3207     if (mRepeatingRequests.empty()) {
3208         return false;
3209     }
3210     int32_t requestId = requestIn->mResultExtras.requestId;
3211     const RequestList &repeatRequests = mRepeatingRequests;
3212     // All repeating requests are guaranteed to have same id so only check first quest
3213     const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3214     return (firstRequest->mResultExtras.requestId == requestId);
3215 }
3216 
clearRepeatingRequests(int64_t * lastFrameNumber)3217 status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
3218     ATRACE_CALL();
3219     Mutex::Autolock l(mRequestLock);
3220     return clearRepeatingRequestsLocked(lastFrameNumber);
3221 
3222 }
3223 
clearRepeatingRequestsLocked(int64_t * lastFrameNumber)3224 status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3225         /*out*/int64_t *lastFrameNumber) {
3226     std::vector<int32_t> streamIds;
3227     for (const auto& request : mRepeatingRequests) {
3228         for (const auto& stream : request->mOutputStreams) {
3229             streamIds.push_back(stream->getId());
3230         }
3231     }
3232 
3233     mRepeatingRequests.clear();
3234     if (lastFrameNumber != NULL) {
3235         *lastFrameNumber = mRepeatingLastFrameNumber;
3236     }
3237 
3238     mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3239 
3240     mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
3241     return OK;
3242 }
3243 
clear(int64_t * lastFrameNumber)3244 status_t Camera3Device::RequestThread::clear(
3245         /*out*/int64_t *lastFrameNumber) {
3246     ATRACE_CALL();
3247     Mutex::Autolock l(mRequestLock);
3248     ALOGV("RequestThread::%s:", __FUNCTION__);
3249 
3250     // Send errors for all requests pending in the request queue, including
3251     // pending repeating requests
3252     sp<NotificationListener> listener = mListener.promote();
3253     if (listener != NULL) {
3254         for (RequestList::iterator it = mRequestQueue.begin();
3255                  it != mRequestQueue.end(); ++it) {
3256             // Abort the input buffers for reprocess requests.
3257             if ((*it)->mInputStream != NULL) {
3258                 camera_stream_buffer_t inputBuffer;
3259                 camera3::Size inputBufferSize;
3260                 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3261                         &inputBufferSize, /*respectHalLimit*/ false);
3262                 if (res != OK) {
3263                     ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3264                             "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3265                 } else {
3266                     inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
3267                     res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3268                     if (res != OK) {
3269                         ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3270                                 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3271                     }
3272                 }
3273             }
3274             // Set the frame number this request would have had, if it
3275             // had been submitted; this frame number will not be reused.
3276             // The requestId and burstId fields were set when the request was
3277             // submitted originally (in convertMetadataListToRequestListLocked)
3278             (*it)->mResultExtras.frameNumber = mFrameNumber++;
3279             listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
3280                     (*it)->mResultExtras);
3281         }
3282     }
3283     mRequestQueue.clear();
3284 
3285     Mutex::Autolock al(mTriggerMutex);
3286     mTriggerMap.clear();
3287     clearRepeatingRequestsLocked(lastFrameNumber);
3288     mRequestClearing = true;
3289     mRequestSignal.signal();
3290     return OK;
3291 }
3292 
flush()3293 status_t Camera3Device::RequestThread::flush() {
3294     ATRACE_CALL();
3295     Mutex::Autolock l(mFlushLock);
3296 
3297     return mInterface->flush();
3298 }
3299 
setPaused(bool paused)3300 void Camera3Device::RequestThread::setPaused(bool paused) {
3301     ATRACE_CALL();
3302     Mutex::Autolock l(mPauseLock);
3303     mDoPause = paused;
3304     mDoPauseSignal.signal();
3305 }
3306 
setHalBufferManagedStreams(const std::set<int32_t> & halBufferManagedStreams)3307 void Camera3Device::RequestThread::setHalBufferManagedStreams(
3308             const std::set<int32_t> &halBufferManagedStreams) {
3309     mHalBufManagedStreamIds = halBufferManagedStreams;
3310 }
3311 
waitUntilRequestProcessed(int32_t requestId,nsecs_t timeout)3312 status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3313         int32_t requestId, nsecs_t timeout) {
3314     ATRACE_CALL();
3315     Mutex::Autolock l(mLatestRequestMutex);
3316     status_t res;
3317     while (mLatestRequestId != requestId && mLatestFailedRequestId != requestId) {
3318         nsecs_t startTime = systemTime();
3319 
3320         res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3321         if (res != OK) return res;
3322 
3323         timeout -= (systemTime() - startTime);
3324     }
3325 
3326     return OK;
3327 }
3328 
requestExit()3329 void Camera3Device::RequestThread::requestExit() {
3330     {
3331         Mutex::Autolock l(mRequestLock);
3332         mRequestClearing = true;
3333         // Call parent to set up shutdown
3334         Thread::requestExit();
3335     }
3336     // The exit from any possible waits
3337     mDoPauseSignal.signal();
3338     mRequestSignal.signal();
3339 
3340     mRequestLatency.log("ProcessCaptureRequest latency histogram");
3341     mRequestLatency.reset();
3342 }
3343 
checkAndStopRepeatingRequest()3344 void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
3345     ATRACE_CALL();
3346     bool surfaceAbandoned = false;
3347     int64_t lastFrameNumber = 0;
3348     sp<NotificationListener> listener;
3349     {
3350         Mutex::Autolock l(mRequestLock);
3351         // Check all streams needed by repeating requests are still valid. Otherwise, stop
3352         // repeating requests.
3353         for (const auto& request : mRepeatingRequests) {
3354             for (const auto& s : request->mOutputStreams) {
3355                 if (s->isAbandoned()) {
3356                     surfaceAbandoned = true;
3357                     clearRepeatingRequestsLocked(&lastFrameNumber);
3358                     break;
3359                 }
3360             }
3361             if (surfaceAbandoned) {
3362                 break;
3363             }
3364         }
3365         listener = mListener.promote();
3366     }
3367 
3368     if (listener != NULL && surfaceAbandoned) {
3369         listener->notifyRepeatingRequestError(lastFrameNumber);
3370     }
3371 }
3372 
sendRequestsBatch()3373 bool Camera3Device::RequestThread::sendRequestsBatch() {
3374     ATRACE_CALL();
3375     status_t res;
3376     size_t batchSize = mNextRequests.size();
3377     std::vector<camera_capture_request_t*> requests(batchSize);
3378     uint32_t numRequestProcessed = 0;
3379     for (size_t i = 0; i < batchSize; i++) {
3380         requests[i] = &mNextRequests.editItemAt(i).halRequest;
3381         ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
3382     }
3383 
3384     res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3385 
3386     bool triggerRemoveFailed = false;
3387     NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3388     for (size_t i = 0; i < numRequestProcessed; i++) {
3389         NextRequest& nextRequest = mNextRequests.editItemAt(i);
3390         nextRequest.submitted = true;
3391 
3392         updateNextRequest(nextRequest);
3393 
3394         if (!triggerRemoveFailed) {
3395             // Remove any previously queued triggers (after unlock)
3396             status_t removeTriggerRes = removeTriggers(mPrevRequest);
3397             if (removeTriggerRes != OK) {
3398                 triggerRemoveFailed = true;
3399                 triggerFailedRequest = nextRequest;
3400             }
3401         }
3402     }
3403 
3404     if (triggerRemoveFailed) {
3405         SET_ERR("RequestThread: Unable to remove triggers "
3406               "(capture request %d, HAL device: %s (%d)",
3407               triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3408         cleanUpFailedRequests(/*sendRequestError*/ false);
3409         return false;
3410     }
3411 
3412     if (res != OK) {
3413         // Should only get a failure here for malformed requests or device-level
3414         // errors, so consider all errors fatal.  Bad metadata failures should
3415         // come through notify.
3416         SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3417                 mNextRequests[numRequestProcessed].halRequest.frame_number,
3418                 strerror(-res), res);
3419         cleanUpFailedRequests(/*sendRequestError*/ false);
3420         return false;
3421     }
3422     return true;
3423 }
3424 
3425 Camera3Device::RequestThread::ExpectedDurationInfo
calculateExpectedDurationRange(const camera_metadata_t * request)3426         Camera3Device::RequestThread::calculateExpectedDurationRange(
3427                 const camera_metadata_t *request) {
3428     ExpectedDurationInfo expectedDurationInfo = {
3429             InFlightRequest::kDefaultMinExpectedDuration,
3430             InFlightRequest::kDefaultMaxExpectedDuration,
3431             /*isFixedFps*/false};
3432     camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3433     find_camera_metadata_ro_entry(request,
3434             ANDROID_CONTROL_AE_MODE,
3435             &e);
3436     if (e.count == 0) return expectedDurationInfo;
3437 
3438     switch (e.data.u8[0]) {
3439         case ANDROID_CONTROL_AE_MODE_OFF:
3440             find_camera_metadata_ro_entry(request,
3441                     ANDROID_SENSOR_EXPOSURE_TIME,
3442                     &e);
3443             if (e.count > 0) {
3444                 expectedDurationInfo.minDuration = e.data.i64[0];
3445                 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
3446             }
3447             find_camera_metadata_ro_entry(request,
3448                     ANDROID_SENSOR_FRAME_DURATION,
3449                     &e);
3450             if (e.count > 0) {
3451                 expectedDurationInfo.minDuration =
3452                         std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3453                 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
3454             }
3455             expectedDurationInfo.isFixedFps = false;
3456             break;
3457         default:
3458             find_camera_metadata_ro_entry(request,
3459                     ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3460                     &e);
3461             if (e.count > 1) {
3462                 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3463                 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
3464             }
3465             expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
3466             break;
3467     }
3468 
3469     return expectedDurationInfo;
3470 }
3471 
skipHFRTargetFPSUpdate(int32_t tag,const camera_metadata_ro_entry_t & newEntry,const camera_metadata_entry_t & currentEntry)3472 bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3473         const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3474     if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3475             (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3476             (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3477         return true;
3478     }
3479 
3480     return false;
3481 }
3482 
updateNextRequest(NextRequest & nextRequest)3483 void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3484     // Update the latest request sent to HAL
3485     camera_capture_request_t& halRequest = nextRequest.halRequest;
3486     sp<Camera3Device> parent = mParent.promote();
3487     if (halRequest.settings != nullptr) { // Don't update if they were unchanged
3488         Mutex::Autolock al(mLatestRequestMutex);
3489 
3490         camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
3491         mLatestRequest.acquire(cloned);
3492 
3493         mLatestPhysicalRequest.clear();
3494         for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3495             cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3496             mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
3497                     CameraMetadata(cloned));
3498         }
3499 
3500         if (parent != nullptr) {
3501             int32_t inputStreamId = -1;
3502             if (halRequest.input_buffer != nullptr) {
3503               inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3504             }
3505 
3506             parent->monitorMetadata(TagMonitor::REQUEST,
3507                     halRequest.frame_number,
3508                     0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3509                     halRequest.num_output_buffers, inputStreamId);
3510         }
3511     }
3512     if (parent != nullptr) {
3513         parent->collectRequestStats(halRequest.frame_number, mLatestRequest);
3514     }
3515 
3516     if (halRequest.settings != nullptr) {
3517         nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
3518                 halRequest.settings);
3519     }
3520 
3521     cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
3522 }
3523 
updateSessionParameters(const CameraMetadata & settings)3524 bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3525     ATRACE_CALL();
3526     bool updatesDetected = false;
3527 
3528     CameraMetadata updatedParams(mLatestSessionParams);
3529     for (auto tag : mSessionParamKeys) {
3530         camera_metadata_ro_entry entry = settings.find(tag);
3531         camera_metadata_entry lastEntry = updatedParams.find(tag);
3532 
3533         if (entry.count > 0) {
3534             bool isDifferent = false;
3535             if (lastEntry.count > 0) {
3536                 // Have a last value, compare to see if changed
3537                 if (lastEntry.type == entry.type &&
3538                         lastEntry.count == entry.count) {
3539                     // Same type and count, compare values
3540                     size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3541                     size_t entryBytes = bytesPerValue * lastEntry.count;
3542                     int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3543                     if (cmp != 0) {
3544                         isDifferent = true;
3545                     }
3546                 } else {
3547                     // Count or type has changed
3548                     isDifferent = true;
3549                 }
3550             } else {
3551                 // No last entry, so always consider to be different
3552                 isDifferent = true;
3553             }
3554 
3555             if (isDifferent) {
3556                 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
3557                 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3558                     updatesDetected = true;
3559                 }
3560                 updatedParams.update(entry);
3561             }
3562         } else if (lastEntry.count > 0) {
3563             // Value has been removed
3564             ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
3565             updatedParams.erase(tag);
3566             updatesDetected = true;
3567         }
3568     }
3569 
3570     bool reconfigureRequired;
3571     if (updatesDetected) {
3572         reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3573                 updatedParams);
3574         mLatestSessionParams = updatedParams;
3575     } else {
3576         reconfigureRequired = false;
3577     }
3578 
3579     return reconfigureRequired;
3580 }
3581 
threadLoop()3582 bool Camera3Device::RequestThread::threadLoop() {
3583     ATRACE_CALL();
3584     status_t res;
3585     // Any function called from threadLoop() must not hold mInterfaceLock since
3586     // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3587     // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
3588 
3589     // Handle paused state.
3590     if (waitIfPaused()) {
3591         return true;
3592     }
3593 
3594     // Wait for the next batch of requests.
3595     waitForNextRequestBatch();
3596     if (mNextRequests.size() == 0) {
3597         return true;
3598     }
3599 
3600     // Get the latest request ID, if any
3601     int latestRequestId;
3602     camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
3603             captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
3604     if (requestIdEntry.count > 0) {
3605         latestRequestId = requestIdEntry.data.i32[0];
3606     } else {
3607         ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3608         latestRequestId = NAME_NOT_FOUND;
3609     }
3610 
3611     for (size_t i = 0; i < mNextRequests.size(); i++) {
3612         auto& nextRequest = mNextRequests.editItemAt(i);
3613         sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3614         captureRequest->mTestPatternChanged = overrideTestPattern(captureRequest);
3615         // Do not override rotate&crop for stream configurations that include
3616         // SurfaceViews(HW_COMPOSER) output, unless mRotationOverride is set.
3617         // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3618         using hardware::ICameraService::ROTATION_OVERRIDE_NONE;
3619         captureRequest->mRotateAndCropChanged =
3620                 (mComposerOutput && (mRotationOverride == ROTATION_OVERRIDE_NONE)) ?
3621                         false : overrideAutoRotateAndCrop(captureRequest);
3622         captureRequest->mAutoframingChanged = overrideAutoframing(captureRequest);
3623         if (flags::inject_session_params()) {
3624             injectSessionParams(captureRequest, mInjectedSessionParams);
3625         }
3626     }
3627 
3628     // 'mNextRequests' will at this point contain either a set of HFR batched requests
3629     //  or a single request from streaming or burst. In either case the first element
3630     //  should contain the latest camera settings that we need to check for any session
3631     //  parameter updates.
3632     if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
3633         res = OK;
3634 
3635         //Input stream buffers are already acquired at this point so an input stream
3636         //will not be able to move to idle state unless we force it.
3637         if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3638             res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3639             if (res != OK) {
3640                 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3641                 cleanUpFailedRequests(/*sendRequestError*/ false);
3642                 return false;
3643             }
3644         }
3645 
3646         if (res == OK) {
3647             sp<Camera3Device> parent = mParent.promote();
3648             if (parent != nullptr) {
3649                 if (parent->reconfigureCamera(mLatestSessionParams, mStatusId)) {
3650                     mForceNewRequestAfterReconfigure = true;
3651                     mReconfigured = true;
3652                 }
3653             }
3654 
3655             if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3656                 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3657                 if (res != OK) {
3658                     ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3659                     cleanUpFailedRequests(/*sendRequestError*/ false);
3660                     return false;
3661                 }
3662             }
3663         }
3664     }
3665 
3666     // Prepare a batch of HAL requests and output buffers.
3667     res = prepareHalRequests();
3668     if (res == TIMED_OUT) {
3669         // Not a fatal error if getting output buffers time out.
3670         cleanUpFailedRequests(/*sendRequestError*/ true);
3671         // Check if any stream is abandoned.
3672         checkAndStopRepeatingRequest();
3673         // Inform waitUntilRequestProcessed thread of a failed request ID
3674         wakeupLatestRequest(/*failedRequestId*/true, latestRequestId);
3675         return true;
3676     } else if (res != OK) {
3677         cleanUpFailedRequests(/*sendRequestError*/ false);
3678         // Inform waitUntilRequestProcessed thread of a failed request ID
3679         wakeupLatestRequest(/*failedRequestId*/true, latestRequestId);
3680         return false;
3681     }
3682 
3683     // Inform waitUntilRequestProcessed thread of a new request ID
3684     wakeupLatestRequest(/*failedRequestId*/false, latestRequestId);
3685 
3686     // Submit a batch of requests to HAL.
3687     // Use flush lock only when submitting multilple requests in a batch.
3688     // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3689     // which may take a long time to finish so synchronizing flush() and
3690     // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3691     // For now, only synchronize for high speed recording and we should figure something out for
3692     // removing the synchronization.
3693     bool useFlushLock = mNextRequests.size() > 1;
3694 
3695     if (useFlushLock) {
3696         mFlushLock.lock();
3697     }
3698 
3699     ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
3700             mNextRequests.size());
3701 
3702     sp<Camera3Device> parent = mParent.promote();
3703     if (parent != nullptr) {
3704         parent->mRequestBufferSM.onSubmittingRequest();
3705     }
3706 
3707     bool submitRequestSuccess = false;
3708     nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
3709     submitRequestSuccess = sendRequestsBatch();
3710 
3711     nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3712     mRequestLatency.add(tRequestStart, tRequestEnd);
3713 
3714     if (useFlushLock) {
3715         mFlushLock.unlock();
3716     }
3717 
3718     // Unset as current request
3719     {
3720         Mutex::Autolock l(mRequestLock);
3721         mNextRequests.clear();
3722     }
3723     mRequestSubmittedSignal.signal();
3724 
3725     return submitRequestSuccess;
3726 }
3727 
removeFwkOnlyRegionKeys(CameraMetadata * request)3728 status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3729     static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3730         ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3731         ANDROID_SCALER_CROP_REGION_SET};
3732     if (request == nullptr) {
3733         ALOGE("%s request metadata nullptr", __FUNCTION__);
3734         return BAD_VALUE;
3735     }
3736     status_t res = OK;
3737     for (const auto &key : kFwkOnlyRegionKeys) {
3738         if (request->exists(key)) {
3739             res = request->erase(key);
3740             if (res != OK) {
3741                 return res;
3742             }
3743         }
3744     }
3745     return OK;
3746 }
3747 
prepareHalRequests()3748 status_t Camera3Device::RequestThread::prepareHalRequests() {
3749     ATRACE_CALL();
3750 
3751     bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
3752     for (size_t i = 0; i < mNextRequests.size(); i++) {
3753         auto& nextRequest = mNextRequests.editItemAt(i);
3754         sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3755         camera_capture_request_t* halRequest = &nextRequest.halRequest;
3756         Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
3757 
3758         // Prepare a request to HAL
3759         halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3760 
3761         // Insert any queued triggers (before metadata is locked)
3762         status_t res = insertTriggers(captureRequest);
3763         if (res < 0) {
3764             SET_ERR("RequestThread: Unable to insert triggers "
3765                     "(capture request %d, HAL device: %s (%d)",
3766                     halRequest->frame_number, strerror(-res), res);
3767             return INVALID_OPERATION;
3768         }
3769 
3770         int triggerCount = res;
3771         bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3772         mPrevTriggers = triggerCount;
3773 
3774         bool settingsOverrideChanged = overrideSettingsOverride(captureRequest);
3775 
3776         // If the request is the same as last, or we had triggers now or last time or
3777         // changing overrides this time
3778         bool newRequest =
3779                 (mPrevRequest != captureRequest || triggersMixedIn ||
3780                          captureRequest->mRotateAndCropChanged ||
3781                          captureRequest->mAutoframingChanged ||
3782                          captureRequest->mTestPatternChanged || settingsOverrideChanged ||
3783                          (flags::inject_session_params() && mForceNewRequestAfterReconfigure)) &&
3784                 // Request settings are all the same within one batch, so only treat the first
3785                 // request in a batch as new
3786                 !(batchedRequest && i > 0);
3787 
3788         if (newRequest) {
3789             std::set<std::string> cameraIdsWithZoom;
3790 
3791             if (flags::inject_session_params() && mForceNewRequestAfterReconfigure) {
3792                 // This only needs to happen once.
3793                 mForceNewRequestAfterReconfigure = false;
3794             }
3795 
3796             /**
3797              * HAL workaround:
3798              * Insert a fake trigger ID if a trigger is set but no trigger ID is
3799              */
3800             res = addFakeTriggerIds(captureRequest);
3801             if (res != OK) {
3802                 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
3803                         "(capture request %d, HAL device: %s (%d)",
3804                         halRequest->frame_number, strerror(-res), res);
3805                 return INVALID_OPERATION;
3806             }
3807 
3808             {
3809                 sp<Camera3Device> parent = mParent.promote();
3810                 if (parent != nullptr) {
3811                     List<PhysicalCameraSettings>::iterator it;
3812                     for (it = captureRequest->mSettingsList.begin();
3813                             it != captureRequest->mSettingsList.end(); it++) {
3814                         if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3815                                 parent->mUHRCropAndMeteringRegionMappers.end()) {
3816                             if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3817                                 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3818                                         "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3819                                         res);
3820                                 return INVALID_OPERATION;
3821                             }
3822                             continue;
3823                         }
3824 
3825                         if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3826                             res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3827                                     updateCaptureRequest(&(it->metadata));
3828                             if (res != OK) {
3829                                 SET_ERR("RequestThread: Unable to correct capture requests "
3830                                         "for scaler crop region and metering regions for request "
3831                                         "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3832                                         res);
3833                                 return INVALID_OPERATION;
3834                             }
3835                             captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
3836                             if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3837                                 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3838                                         "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3839                                         res);
3840                                 return INVALID_OPERATION;
3841                             }
3842                         }
3843                     }
3844 
3845                     // Correct metadata regions for distortion correction if enabled
3846                     for (it = captureRequest->mSettingsList.begin();
3847                             it != captureRequest->mSettingsList.end(); it++) {
3848                         if (parent->mDistortionMappers.find(it->cameraId) ==
3849                                 parent->mDistortionMappers.end()) {
3850                             continue;
3851                         }
3852 
3853                         if (!captureRequest->mDistortionCorrectionUpdated) {
3854                             res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3855                                     &(it->metadata));
3856                             if (res != OK) {
3857                                 SET_ERR("RequestThread: Unable to correct capture requests "
3858                                         "for lens distortion for request %d: %s (%d)",
3859                                         halRequest->frame_number, strerror(-res), res);
3860                                 return INVALID_OPERATION;
3861                             }
3862                             captureRequest->mDistortionCorrectionUpdated = true;
3863                         }
3864                     }
3865 
3866                     for (it = captureRequest->mSettingsList.begin();
3867                             it != captureRequest->mSettingsList.end(); it++) {
3868                         if (parent->mZoomRatioMappers.find(it->cameraId) ==
3869                                 parent->mZoomRatioMappers.end()) {
3870                             continue;
3871                         }
3872 
3873                         if (!captureRequest->mZoomRatioIs1x) {
3874                             cameraIdsWithZoom.insert(it->cameraId);
3875                         }
3876 
3877                         if (!captureRequest->mZoomRatioUpdated) {
3878                             res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3879                                     &(it->metadata));
3880                             if (res != OK) {
3881                                 SET_ERR("RequestThread: Unable to correct capture requests "
3882                                         "for zoom ratio for request %d: %s (%d)",
3883                                         halRequest->frame_number, strerror(-res), res);
3884                                 return INVALID_OPERATION;
3885                             }
3886                             captureRequest->mZoomRatioUpdated = true;
3887                         }
3888                     }
3889                     if (captureRequest->mRotateAndCropAuto &&
3890                             !captureRequest->mRotationAndCropUpdated) {
3891                         for (it = captureRequest->mSettingsList.begin();
3892                                 it != captureRequest->mSettingsList.end(); it++) {
3893                             auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3894                             if (mapper != parent->mRotateAndCropMappers.end()) {
3895                                 res = mapper->second.updateCaptureRequest(&(it->metadata));
3896                                 if (res != OK) {
3897                                     SET_ERR("RequestThread: Unable to correct capture requests "
3898                                             "for rotate-and-crop for request %d: %s (%d)",
3899                                             halRequest->frame_number, strerror(-res), res);
3900                                     return INVALID_OPERATION;
3901                                 }
3902                             }
3903                         }
3904                         captureRequest->mRotationAndCropUpdated = true;
3905                     }
3906 
3907                     for (it = captureRequest->mSettingsList.begin();
3908                             it != captureRequest->mSettingsList.end(); it++) {
3909                         res = filterVndkKeys(mVndkVersion, it->metadata, false /*isStatic*/);
3910                         if (res != OK) {
3911                             SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3912                                     "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3913                             return INVALID_OPERATION;
3914                         }
3915 
3916                         if (!parent->mSupportsExtensionKeys) {
3917                             res = filterExtensionKeys(&it->metadata);
3918                             if (res != OK) {
3919                                 SET_ERR("RequestThread: Failed during extension filter of capture "
3920                                         "requests %d: %s (%d)", halRequest->frame_number,
3921                                         strerror(-res), res);
3922                                 return INVALID_OPERATION;
3923                             }
3924                         }
3925                     }
3926                 }
3927             }
3928 
3929             /**
3930              * The request should be presorted so accesses in HAL
3931              *   are O(logn). Sidenote, sorting a sorted metadata is nop.
3932              */
3933             captureRequest->mSettingsList.begin()->metadata.sort();
3934             halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3935             mPrevRequest = captureRequest;
3936             mPrevCameraIdsWithZoom = cameraIdsWithZoom;
3937             ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3938 
3939             IF_ALOGV() {
3940                 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3941                 find_camera_metadata_ro_entry(
3942                         halRequest->settings,
3943                         ANDROID_CONTROL_AF_TRIGGER,
3944                         &e
3945                 );
3946                 if (e.count > 0) {
3947                     ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3948                           __FUNCTION__,
3949                           halRequest->frame_number,
3950                           e.data.u8[0]);
3951                 }
3952             }
3953         } else {
3954             // leave request.settings NULL to indicate 'reuse latest given'
3955             ALOGVV("%s: Request settings are REUSED",
3956                    __FUNCTION__);
3957         }
3958 
3959         if (captureRequest->mSettingsList.size() > 1) {
3960             halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3961             halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
3962             if (newRequest) {
3963                 halRequest->physcam_settings =
3964                     new const camera_metadata* [halRequest->num_physcam_settings];
3965             } else {
3966                 halRequest->physcam_settings = nullptr;
3967             }
3968             auto it = ++captureRequest->mSettingsList.begin();
3969             size_t i = 0;
3970             for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3971                 halRequest->physcam_id[i] = it->cameraId.c_str();
3972                 if (newRequest) {
3973                     it->metadata.sort();
3974                     halRequest->physcam_settings[i] = it->metadata.getAndLock();
3975                 }
3976             }
3977         }
3978 
3979         uint32_t totalNumBuffers = 0;
3980 
3981         // Fill in buffers
3982         if (captureRequest->mInputStream != NULL) {
3983             halRequest->input_buffer = &captureRequest->mInputBuffer;
3984 
3985             halRequest->input_width = captureRequest->mInputBufferSize.width;
3986             halRequest->input_height = captureRequest->mInputBufferSize.height;
3987             totalNumBuffers += 1;
3988         } else {
3989             halRequest->input_buffer = NULL;
3990         }
3991 
3992         outputBuffers->insertAt(camera_stream_buffer_t(), 0,
3993                 captureRequest->mOutputStreams.size());
3994         halRequest->output_buffers = outputBuffers->array();
3995         std::set<std::set<std::string>> requestedPhysicalCameras;
3996 
3997         sp<Camera3Device> parent = mParent.promote();
3998         if (parent == NULL) {
3999             // Should not happen, and nowhere to send errors to, so just log it
4000             CLOGE("RequestThread: Parent is gone");
4001             return INVALID_OPERATION;
4002         }
4003         nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4004 
4005         SurfaceMap uniqueSurfaceIdMap;
4006         bool containsHalBufferManagedStream = false;
4007         for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4008             sp<Camera3OutputStreamInterface> outputStream =
4009                     captureRequest->mOutputStreams.editItemAt(j);
4010             int streamId = outputStream->getId();
4011             if (!containsHalBufferManagedStream) {
4012                 containsHalBufferManagedStream =
4013                         contains(mHalBufManagedStreamIds, streamId);
4014             }
4015             // Prepare video buffers for high speed recording on the first video request.
4016             if (mPrepareVideoStream && outputStream->isVideoStream()) {
4017                 // Only try to prepare video stream on the first video request.
4018                 mPrepareVideoStream = false;
4019 
4020                 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4021                         false /*blockRequest*/);
4022                 while (res == NOT_ENOUGH_DATA) {
4023                     res = outputStream->prepareNextBuffer();
4024                 }
4025                 if (res != OK) {
4026                     ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4027                         __FUNCTION__, strerror(-res), res);
4028                     outputStream->cancelPrepare();
4029                 }
4030             }
4031 
4032             std::vector<size_t> uniqueSurfaceIds;
4033             res = outputStream->getUniqueSurfaceIds(
4034                     captureRequest->mOutputSurfaces[streamId],
4035                     &uniqueSurfaceIds);
4036             // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4037             if (res != OK && res != INVALID_OPERATION) {
4038                 ALOGE("%s: failed to query stream %d unique surface IDs",
4039                         __FUNCTION__, streamId);
4040                 return res;
4041             }
4042             if (res == OK) {
4043                 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4044             }
4045 
4046             if (parent->isHalBufferManagedStream(streamId)) {
4047                 if (outputStream->isAbandoned()) {
4048                     ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
4049                     return TIMED_OUT;
4050                 }
4051                 // HAL will request buffer through requestStreamBuffer API
4052                 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4053                 buffer.stream = outputStream->asHalStream();
4054                 buffer.buffer = nullptr;
4055                 buffer.status = CAMERA_BUFFER_STATUS_OK;
4056                 buffer.acquire_fence = -1;
4057                 buffer.release_fence = -1;
4058                 // Mark the output stream as unpreparable to block clients from calling
4059                 // 'prepare' after this request reaches CameraHal and before the respective
4060                 // buffers are requested.
4061                 outputStream->markUnpreparable();
4062             } else {
4063                 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4064                         waitDuration,
4065                         captureRequest->mOutputSurfaces[streamId]);
4066                 if (res != OK) {
4067                     // Can't get output buffer from gralloc queue - this could be due to
4068                     // abandoned queue or other consumer misbehavior, so not a fatal
4069                     // error
4070                     ALOGV("RequestThread: Can't get output buffer, skipping request:"
4071                             " %s (%d)", strerror(-res), res);
4072 
4073                     return TIMED_OUT;
4074                 }
4075             }
4076 
4077             {
4078                 sp<Camera3Device> parent = mParent.promote();
4079                 if (parent != nullptr) {
4080                     const std::string& streamCameraId = outputStream->getPhysicalCameraId();
4081                     // Consider the case where clients are sending a single logical camera request
4082                     // to physical output/outputs
4083                     bool singleRequest = captureRequest->mSettingsList.size() == 1;
4084                     for (const auto& settings : captureRequest->mSettingsList) {
4085                         if (((streamCameraId.empty() || singleRequest) &&
4086                                 parent->getId() == settings.cameraId) ||
4087                                 streamCameraId == settings.cameraId) {
4088                             outputStream->fireBufferRequestForFrameNumber(
4089                                     captureRequest->mResultExtras.frameNumber,
4090                                     settings.metadata);
4091                         }
4092                     }
4093                 }
4094             }
4095 
4096             const std::string &physicalCameraId = outputStream->getPhysicalCameraId();
4097             int32_t streamGroupId = outputStream->getHalStreamGroupId();
4098             if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
4099                 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
4100             } else if (!physicalCameraId.empty()) {
4101                 requestedPhysicalCameras.insert(std::set<std::string>({physicalCameraId}));
4102             }
4103             halRequest->num_output_buffers++;
4104         }
4105         totalNumBuffers += halRequest->num_output_buffers;
4106 
4107         // Log request in the in-flight queue
4108         // If this request list is for constrained high speed recording (not
4109         // preview), and the current request is not the last one in the batch,
4110         // do not send callback to the app.
4111         bool hasCallback = true;
4112         if (batchedRequest && i != mNextRequests.size()-1) {
4113             hasCallback = false;
4114         }
4115         bool isStillCapture = false;
4116         bool isZslCapture = false;
4117         const camera_metadata_t* settings = halRequest->settings;
4118         bool shouldUnlockSettings = false;
4119         if (settings == nullptr) {
4120             shouldUnlockSettings = true;
4121             settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4122         }
4123         if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4124             camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4125             find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4126             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4127                 isStillCapture = true;
4128                 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4129             }
4130 
4131             e = camera_metadata_ro_entry_t();
4132             find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4133             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4134                 isZslCapture = true;
4135             }
4136         }
4137         bool passSurfaceMap =
4138                 mUseHalBufManager ||
4139                         (flags::session_hal_buf_manager() && containsHalBufferManagedStream);
4140         auto expectedDurationInfo = calculateExpectedDurationRange(settings);
4141         res = parent->registerInFlight(halRequest->frame_number,
4142                 totalNumBuffers, captureRequest->mResultExtras,
4143                 /*hasInput*/halRequest->input_buffer != NULL,
4144                 hasCallback,
4145                 expectedDurationInfo.minDuration,
4146                 expectedDurationInfo.maxDuration,
4147                 expectedDurationInfo.isFixedFps,
4148                 requestedPhysicalCameras, isStillCapture, isZslCapture,
4149                 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
4150                 mPrevCameraIdsWithZoom,
4151                 passSurfaceMap ? uniqueSurfaceIdMap :
4152                                       SurfaceMap{}, captureRequest->mRequestTimeNs);
4153         ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4154                ", burstId = %" PRId32 ".",
4155                 __FUNCTION__,
4156                 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4157                 captureRequest->mResultExtras.burstId);
4158 
4159         if (shouldUnlockSettings) {
4160             captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4161         }
4162 
4163         if (res != OK) {
4164             SET_ERR("RequestThread: Unable to register new in-flight request:"
4165                     " %s (%d)", strerror(-res), res);
4166             return INVALID_OPERATION;
4167         }
4168     }
4169 
4170     return OK;
4171 }
4172 
getLatestRequest() const4173 CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
4174     ATRACE_CALL();
4175     Mutex::Autolock al(mLatestRequestMutex);
4176 
4177     ALOGV("RequestThread::%s", __FUNCTION__);
4178 
4179     return mLatestRequest;
4180 }
4181 
isStreamPending(sp<Camera3StreamInterface> & stream)4182 bool Camera3Device::RequestThread::isStreamPending(
4183         sp<Camera3StreamInterface>& stream) {
4184     ATRACE_CALL();
4185     Mutex::Autolock l(mRequestLock);
4186 
4187     for (const auto& nextRequest : mNextRequests) {
4188         if (!nextRequest.submitted) {
4189             for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4190                 if (stream == s) return true;
4191             }
4192             if (stream == nextRequest.captureRequest->mInputStream) return true;
4193         }
4194     }
4195 
4196     for (const auto& request : mRequestQueue) {
4197         for (const auto& s : request->mOutputStreams) {
4198             if (stream == s) return true;
4199         }
4200         if (stream == request->mInputStream) return true;
4201     }
4202 
4203     for (const auto& request : mRepeatingRequests) {
4204         for (const auto& s : request->mOutputStreams) {
4205             if (stream == s) return true;
4206         }
4207         if (stream == request->mInputStream) return true;
4208     }
4209 
4210     return false;
4211 }
4212 
isOutputSurfacePending(int streamId,size_t surfaceId)4213 bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4214     ATRACE_CALL();
4215     Mutex::Autolock l(mRequestLock);
4216 
4217     for (const auto& nextRequest : mNextRequests) {
4218         for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4219             if (s.first == streamId) {
4220                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4221                 if (it != s.second.end()) {
4222                     return true;
4223                 }
4224             }
4225         }
4226     }
4227 
4228     for (const auto& request : mRequestQueue) {
4229         for (const auto& s : request->mOutputSurfaces) {
4230             if (s.first == streamId) {
4231                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4232                 if (it != s.second.end()) {
4233                     return true;
4234                 }
4235             }
4236         }
4237     }
4238 
4239     for (const auto& request : mRepeatingRequests) {
4240         for (const auto& s : request->mOutputSurfaces) {
4241             if (s.first == streamId) {
4242                 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4243                 if (it != s.second.end()) {
4244                     return true;
4245                 }
4246             }
4247         }
4248     }
4249 
4250     return false;
4251 }
4252 
signalPipelineDrain(const std::vector<int> & streamIds)4253 void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4254     if (!mUseHalBufManager &&
4255             (flags::session_hal_buf_manager() && mHalBufManagedStreamIds.size() == 0)) {
4256         ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4257         return;
4258     }
4259 
4260     Mutex::Autolock pl(mPauseLock);
4261     if (mPaused) {
4262         mInterface->signalPipelineDrain(streamIds);
4263         return;
4264     }
4265     // If request thread is still busy, wait until paused then notify HAL
4266     mNotifyPipelineDrain = true;
4267     mStreamIdsToBeDrained = streamIds;
4268 }
4269 
resetPipelineDrain()4270 void Camera3Device::RequestThread::resetPipelineDrain() {
4271     Mutex::Autolock pl(mPauseLock);
4272     mNotifyPipelineDrain = false;
4273     mStreamIdsToBeDrained.clear();
4274 }
4275 
clearPreviousRequest()4276 void Camera3Device::RequestThread::clearPreviousRequest() {
4277     Mutex::Autolock l(mRequestLock);
4278     mPrevRequest.clear();
4279 }
4280 
setRotateAndCropAutoBehavior(camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue)4281 status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4282         camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4283     ATRACE_CALL();
4284     Mutex::Autolock l(mTriggerMutex);
4285     mRotateAndCropOverride = rotateAndCropValue;
4286     return OK;
4287 }
4288 
setAutoframingAutoBehaviour(camera_metadata_enum_android_control_autoframing_t autoframingValue)4289 status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4290         camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4291     ATRACE_CALL();
4292     Mutex::Autolock l(mTriggerMutex);
4293     mAutoframingOverride = autoframingValue;
4294     return OK;
4295 }
4296 
setComposerSurface(bool composerSurfacePresent)4297 status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4298     ATRACE_CALL();
4299     Mutex::Autolock l(mTriggerMutex);
4300     mComposerOutput = composerSurfacePresent;
4301     return OK;
4302 }
4303 
setCameraMute(int32_t muteMode)4304 status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
4305     ATRACE_CALL();
4306     Mutex::Autolock l(mTriggerMutex);
4307     if (muteMode != mCameraMute) {
4308         mCameraMute = muteMode;
4309     }
4310     return OK;
4311 }
4312 
setZoomOverride(int32_t zoomOverride)4313 status_t Camera3Device::RequestThread::setZoomOverride(int32_t zoomOverride) {
4314     ATRACE_CALL();
4315     Mutex::Autolock l(mTriggerMutex);
4316     mSettingsOverride = zoomOverride;
4317     return OK;
4318 }
4319 
getExpectedInFlightDuration()4320 nsecs_t Camera3Device::getExpectedInFlightDuration() {
4321     ATRACE_CALL();
4322     std::lock_guard<std::mutex> l(mInFlightLock);
4323     return mExpectedInflightDuration > kMinInflightDuration ?
4324             mExpectedInflightDuration : kMinInflightDuration;
4325 }
4326 
cleanupPhysicalSettings(sp<CaptureRequest> request,camera_capture_request_t * halRequest)4327 void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4328         camera_capture_request_t *halRequest) {
4329     if ((request == nullptr) || (halRequest == nullptr)) {
4330         ALOGE("%s: Invalid request!", __FUNCTION__);
4331         return;
4332     }
4333 
4334     if (halRequest->num_physcam_settings > 0) {
4335         if (halRequest->physcam_id != nullptr) {
4336             delete [] halRequest->physcam_id;
4337             halRequest->physcam_id = nullptr;
4338         }
4339         if (halRequest->physcam_settings != nullptr) {
4340             auto it = ++(request->mSettingsList.begin());
4341             size_t i = 0;
4342             for (; it != request->mSettingsList.end(); it++, i++) {
4343                 it->metadata.unlock(halRequest->physcam_settings[i]);
4344             }
4345             delete [] halRequest->physcam_settings;
4346             halRequest->physcam_settings = nullptr;
4347         }
4348     }
4349 }
4350 
setCameraServiceWatchdog(bool enabled)4351 status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4352     Mutex::Autolock il(mInterfaceLock);
4353     Mutex::Autolock l(mLock);
4354 
4355     if (mCameraServiceWatchdog != NULL) {
4356         mCameraServiceWatchdog->setEnabled(enabled);
4357     }
4358 
4359     return OK;
4360 }
4361 
setStreamUseCaseOverrides(const std::vector<int64_t> & useCaseOverrides)4362 void Camera3Device::setStreamUseCaseOverrides(
4363         const std::vector<int64_t>& useCaseOverrides) {
4364     Mutex::Autolock il(mInterfaceLock);
4365     Mutex::Autolock l(mLock);
4366     mStreamUseCaseOverrides = useCaseOverrides;
4367 }
4368 
clearStreamUseCaseOverrides()4369 void Camera3Device::clearStreamUseCaseOverrides() {
4370     Mutex::Autolock il(mInterfaceLock);
4371     Mutex::Autolock l(mLock);
4372     mStreamUseCaseOverrides.clear();
4373 }
4374 
hasDeviceError()4375 bool Camera3Device::hasDeviceError() {
4376     Mutex::Autolock il(mInterfaceLock);
4377     Mutex::Autolock l(mLock);
4378     return mStatus == STATUS_ERROR;
4379 }
4380 
cleanUpFailedRequests(bool sendRequestError)4381 void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4382     if (mNextRequests.empty()) {
4383         return;
4384     }
4385 
4386     for (auto& nextRequest : mNextRequests) {
4387         // Skip the ones that have been submitted successfully.
4388         if (nextRequest.submitted) {
4389             continue;
4390         }
4391 
4392         sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4393         camera_capture_request_t* halRequest = &nextRequest.halRequest;
4394         Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4395 
4396         if (halRequest->settings != NULL) {
4397             captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
4398         }
4399 
4400         cleanupPhysicalSettings(captureRequest, halRequest);
4401 
4402         if (captureRequest->mInputStream != NULL) {
4403             captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
4404             captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4405         }
4406 
4407         for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4408             //Buffers that failed processing could still have
4409             //valid acquire fence.
4410             Camera3Stream *stream = Camera3Stream::cast((*outputBuffers)[i].stream);
4411             int32_t streamId = stream->getId();
4412             bool skipBufferForStream =
4413                     mUseHalBufManager || (flags::session_hal_buf_manager() &&
4414                             contains(mHalBufManagedStreamIds, streamId));
4415             if (skipBufferForStream) {
4416                 // No output buffer can be returned when using HAL buffer manager for its stream
4417                 continue;
4418             }
4419             int acquireFence = (*outputBuffers)[i].acquire_fence;
4420             if (0 <= acquireFence) {
4421                 close(acquireFence);
4422                 outputBuffers->editItemAt(i).acquire_fence = -1;
4423             }
4424             outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
4425             captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4426                     /*timestamp*/0, /*readoutTimestamp*/0,
4427                     /*timestampIncreasing*/true, std::vector<size_t> (),
4428                     captureRequest->mResultExtras.frameNumber);
4429         }
4430 
4431         if (sendRequestError) {
4432             Mutex::Autolock l(mRequestLock);
4433             sp<NotificationListener> listener = mListener.promote();
4434             if (listener != NULL) {
4435                 listener->notifyError(
4436                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
4437                         captureRequest->mResultExtras);
4438             }
4439             wakeupLatestRequest(/*failedRequestId*/true, captureRequest->mResultExtras.requestId);
4440         }
4441 
4442         // Remove yet-to-be submitted inflight request from inflightMap
4443         {
4444           sp<Camera3Device> parent = mParent.promote();
4445           if (parent != NULL) {
4446               std::lock_guard<std::mutex> l(parent->mInFlightLock);
4447               ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4448               if (idx >= 0) {
4449                   ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4450                         __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4451                   parent->removeInFlightMapEntryLocked(idx);
4452               }
4453           }
4454         }
4455     }
4456 
4457     Mutex::Autolock l(mRequestLock);
4458     mNextRequests.clear();
4459 }
4460 
waitForNextRequestBatch()4461 void Camera3Device::RequestThread::waitForNextRequestBatch() {
4462     ATRACE_CALL();
4463     // Optimized a bit for the simple steady-state case (single repeating
4464     // request), to avoid putting that request in the queue temporarily.
4465     Mutex::Autolock l(mRequestLock);
4466 
4467     assert(mNextRequests.empty());
4468 
4469     NextRequest nextRequest;
4470     nextRequest.captureRequest = waitForNextRequestLocked();
4471     if (nextRequest.captureRequest == nullptr) {
4472         return;
4473     }
4474 
4475     nextRequest.halRequest = camera_capture_request_t();
4476     nextRequest.submitted = false;
4477     mNextRequests.add(nextRequest);
4478 
4479     // Wait for additional requests
4480     const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4481 
4482     for (size_t i = 1; i < batchSize; i++) {
4483         NextRequest additionalRequest;
4484         additionalRequest.captureRequest = waitForNextRequestLocked();
4485         if (additionalRequest.captureRequest == nullptr) {
4486             break;
4487         }
4488 
4489         additionalRequest.halRequest = camera_capture_request_t();
4490         additionalRequest.submitted = false;
4491         mNextRequests.add(additionalRequest);
4492     }
4493 
4494     if (mNextRequests.size() < batchSize) {
4495         ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
4496                 mNextRequests.size(), batchSize);
4497         cleanUpFailedRequests(/*sendRequestError*/true);
4498     }
4499 
4500     return;
4501 }
4502 
4503 sp<Camera3Device::CaptureRequest>
waitForNextRequestLocked()4504         Camera3Device::RequestThread::waitForNextRequestLocked() {
4505     status_t res;
4506     sp<CaptureRequest> nextRequest;
4507 
4508     while (mRequestQueue.empty()) {
4509         if (!mRepeatingRequests.empty()) {
4510             // Always atomically enqueue all requests in a repeating request
4511             // list. Guarantees a complete in-sequence set of captures to
4512             // application.
4513             const RequestList &requests = mRepeatingRequests;
4514             if (mFirstRepeating) {
4515                 mFirstRepeating = false;
4516             } else {
4517                 for (auto& request : requests) {
4518                     // For repeating requests, override timestamp request using
4519                     // the time a request is inserted into the request queue,
4520                     // because the original repeating request will have an old
4521                     // fixed timestamp.
4522                     request->mRequestTimeNs = systemTime();
4523                 }
4524             }
4525             RequestList::const_iterator firstRequest =
4526                     requests.begin();
4527             nextRequest = *firstRequest;
4528             mRequestQueue.insert(mRequestQueue.end(),
4529                     ++firstRequest,
4530                     requests.end());
4531             // No need to wait any longer
4532 
4533             mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
4534 
4535             break;
4536         }
4537 
4538         if (!mRequestClearing) {
4539             res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4540         }
4541 
4542         if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4543                 exitPending()) {
4544             Mutex::Autolock pl(mPauseLock);
4545             if (mPaused == false) {
4546                 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
4547                 mPaused = true;
4548                 if (mNotifyPipelineDrain) {
4549                     mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4550                     mNotifyPipelineDrain = false;
4551                     mStreamIdsToBeDrained.clear();
4552                 }
4553                 // Let the tracker know
4554                 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4555                 if (statusTracker != 0) {
4556                     statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4557                 }
4558                 sp<Camera3Device> parent = mParent.promote();
4559                 if (parent != nullptr) {
4560                     parent->mRequestBufferSM.onRequestThreadPaused();
4561                 }
4562             }
4563             mRequestClearing = false;
4564             // Stop waiting for now and let thread management happen
4565             return NULL;
4566         }
4567     }
4568 
4569     if (nextRequest == NULL) {
4570         // Don't have a repeating request already in hand, so queue
4571         // must have an entry now.
4572         RequestList::iterator firstRequest =
4573                 mRequestQueue.begin();
4574         nextRequest = *firstRequest;
4575         mRequestQueue.erase(firstRequest);
4576         if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4577             sp<NotificationListener> listener = mListener.promote();
4578             if (listener != NULL) {
4579                 listener->notifyRequestQueueEmpty();
4580             }
4581         }
4582     }
4583 
4584     // In case we've been unpaused by setPaused clearing mDoPause, need to
4585     // update internal pause state (capture/setRepeatingRequest unpause
4586     // directly).
4587     Mutex::Autolock pl(mPauseLock);
4588     if (mPaused) {
4589         ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4590         sp<StatusTracker> statusTracker = mStatusTracker.promote();
4591         if (statusTracker != 0) {
4592             statusTracker->markComponentActive(mStatusId);
4593         }
4594     }
4595     mPaused = false;
4596 
4597     // Check if we've reconfigured since last time, and reset the preview
4598     // request if so. Can't use 'NULL request == repeat' across configure calls.
4599     if (mReconfigured) {
4600         mPrevRequest.clear();
4601         mReconfigured = false;
4602     }
4603 
4604     if (nextRequest != NULL) {
4605         nextRequest->mResultExtras.frameNumber = mFrameNumber++;
4606         nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4607         nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
4608 
4609         // Since RequestThread::clear() removes buffers from the input stream,
4610         // get the right buffer here before unlocking mRequestLock
4611         if (nextRequest->mInputStream != NULL) {
4612             res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4613                     &nextRequest->mInputBufferSize);
4614             if (res != OK) {
4615                 // Can't get input buffer from gralloc queue - this could be due to
4616                 // disconnected queue or other producer misbehavior, so not a fatal
4617                 // error
4618                 ALOGE("%s: Can't get input buffer, skipping request:"
4619                         " %s (%d)", __FUNCTION__, strerror(-res), res);
4620 
4621                 sp<NotificationListener> listener = mListener.promote();
4622                 if (listener != NULL) {
4623                     listener->notifyError(
4624                             hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
4625                             nextRequest->mResultExtras);
4626                 }
4627                 return NULL;
4628             }
4629         }
4630     }
4631 
4632     return nextRequest;
4633 }
4634 
waitIfPaused()4635 bool Camera3Device::RequestThread::waitIfPaused() {
4636     ATRACE_CALL();
4637     status_t res;
4638     Mutex::Autolock l(mPauseLock);
4639     while (mDoPause) {
4640         if (mPaused == false) {
4641             mPaused = true;
4642             ALOGV("%s: RequestThread: Paused", __FUNCTION__);
4643             if (mNotifyPipelineDrain) {
4644                 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4645                 mNotifyPipelineDrain = false;
4646                 mStreamIdsToBeDrained.clear();
4647             }
4648             // Let the tracker know
4649             sp<StatusTracker> statusTracker = mStatusTracker.promote();
4650             if (statusTracker != 0) {
4651                 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4652             }
4653             sp<Camera3Device> parent = mParent.promote();
4654             if (parent != nullptr) {
4655                 parent->mRequestBufferSM.onRequestThreadPaused();
4656             }
4657         }
4658 
4659         res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
4660         if (res == TIMED_OUT || exitPending()) {
4661             return true;
4662         }
4663     }
4664     // We don't set mPaused to false here, because waitForNextRequest needs
4665     // to further manage the paused state in case of starvation.
4666     return false;
4667 }
4668 
unpauseForNewRequests()4669 void Camera3Device::RequestThread::unpauseForNewRequests() {
4670     ATRACE_CALL();
4671     // With work to do, mark thread as unpaused.
4672     // If paused by request (setPaused), don't resume, to avoid
4673     // extra signaling/waiting overhead to waitUntilPaused
4674     mRequestSignal.signal();
4675     Mutex::Autolock p(mPauseLock);
4676     if (!mDoPause) {
4677         ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4678         if (mPaused) {
4679             sp<StatusTracker> statusTracker = mStatusTracker.promote();
4680             if (statusTracker != 0) {
4681                 statusTracker->markComponentActive(mStatusId);
4682             }
4683         }
4684         mPaused = false;
4685     }
4686 }
4687 
setErrorState(const char * fmt,...)4688 void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4689     sp<Camera3Device> parent = mParent.promote();
4690     if (parent != NULL) {
4691         va_list args;
4692         va_start(args, fmt);
4693 
4694         parent->setErrorStateV(fmt, args);
4695 
4696         va_end(args);
4697     }
4698 }
4699 
insertTriggers(const sp<CaptureRequest> & request)4700 status_t Camera3Device::RequestThread::insertTriggers(
4701         const sp<CaptureRequest> &request) {
4702     ATRACE_CALL();
4703     Mutex::Autolock al(mTriggerMutex);
4704 
4705     sp<Camera3Device> parent = mParent.promote();
4706     if (parent == NULL) {
4707         CLOGE("RequestThread: Parent is gone");
4708         return DEAD_OBJECT;
4709     }
4710 
4711     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4712     size_t count = mTriggerMap.size();
4713 
4714     for (size_t i = 0; i < count; ++i) {
4715         RequestTrigger trigger = mTriggerMap.valueAt(i);
4716         uint32_t tag = trigger.metadataTag;
4717 
4718         if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4719             bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4720             uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
4721             if (isAeTrigger) {
4722                 request->mResultExtras.precaptureTriggerId = triggerId;
4723                 mCurrentPreCaptureTriggerId = triggerId;
4724             } else {
4725                 request->mResultExtras.afTriggerId = triggerId;
4726                 mCurrentAfTriggerId = triggerId;
4727             }
4728             continue;
4729         }
4730 
4731         camera_metadata_entry entry = metadata.find(tag);
4732 
4733         if (entry.count > 0) {
4734             /**
4735              * Already has an entry for this trigger in the request.
4736              * Rewrite it with our requested trigger value.
4737              */
4738             RequestTrigger oldTrigger = trigger;
4739 
4740             oldTrigger.entryValue = entry.data.u8[0];
4741 
4742             mTriggerReplacedMap.add(tag, oldTrigger);
4743         } else {
4744             /**
4745              * More typical, no trigger entry, so we just add it
4746              */
4747             mTriggerRemovedMap.add(tag, trigger);
4748         }
4749 
4750         status_t res;
4751 
4752         switch (trigger.getTagType()) {
4753             case TYPE_BYTE: {
4754                 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4755                 res = metadata.update(tag,
4756                                       &entryValue,
4757                                       /*count*/1);
4758                 break;
4759             }
4760             case TYPE_INT32:
4761                 res = metadata.update(tag,
4762                                       &trigger.entryValue,
4763                                       /*count*/1);
4764                 break;
4765             default:
4766                 ALOGE("%s: Type not supported: 0x%x",
4767                       __FUNCTION__,
4768                       trigger.getTagType());
4769                 return INVALID_OPERATION;
4770         }
4771 
4772         if (res != OK) {
4773             ALOGE("%s: Failed to update request metadata with trigger tag %s"
4774                   ", value %d", __FUNCTION__, trigger.getTagName(),
4775                   trigger.entryValue);
4776             return res;
4777         }
4778 
4779         ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4780               trigger.getTagName(),
4781               trigger.entryValue);
4782     }
4783 
4784     mTriggerMap.clear();
4785 
4786     return count;
4787 }
4788 
removeTriggers(const sp<CaptureRequest> & request)4789 status_t Camera3Device::RequestThread::removeTriggers(
4790         const sp<CaptureRequest> &request) {
4791     ATRACE_CALL();
4792     Mutex::Autolock al(mTriggerMutex);
4793 
4794     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4795 
4796     /**
4797      * Replace all old entries with their old values.
4798      */
4799     for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4800         RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4801 
4802         status_t res;
4803 
4804         uint32_t tag = trigger.metadataTag;
4805         switch (trigger.getTagType()) {
4806             case TYPE_BYTE: {
4807                 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4808                 res = metadata.update(tag,
4809                                       &entryValue,
4810                                       /*count*/1);
4811                 break;
4812             }
4813             case TYPE_INT32:
4814                 res = metadata.update(tag,
4815                                       &trigger.entryValue,
4816                                       /*count*/1);
4817                 break;
4818             default:
4819                 ALOGE("%s: Type not supported: 0x%x",
4820                       __FUNCTION__,
4821                       trigger.getTagType());
4822                 return INVALID_OPERATION;
4823         }
4824 
4825         if (res != OK) {
4826             ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4827                   ", trigger value %d", __FUNCTION__,
4828                   trigger.getTagName(), trigger.entryValue);
4829             return res;
4830         }
4831     }
4832     mTriggerReplacedMap.clear();
4833 
4834     /**
4835      * Remove all new entries.
4836      */
4837     for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4838         RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4839         status_t res = metadata.erase(trigger.metadataTag);
4840 
4841         if (res != OK) {
4842             ALOGE("%s: Failed to erase metadata with trigger tag %s"
4843                   ", trigger value %d", __FUNCTION__,
4844                   trigger.getTagName(), trigger.entryValue);
4845             return res;
4846         }
4847     }
4848     mTriggerRemovedMap.clear();
4849 
4850     return OK;
4851 }
4852 
addFakeTriggerIds(const sp<CaptureRequest> & request)4853 status_t Camera3Device::RequestThread::addFakeTriggerIds(
4854         const sp<CaptureRequest> &request) {
4855     // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
4856     static const int32_t fakeTriggerId = 1;
4857     status_t res;
4858 
4859     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4860 
4861     // If AF trigger is active, insert a fake AF trigger ID if none already
4862     // exists
4863     camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4864     camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4865     if (afTrigger.count > 0 &&
4866             afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4867             afId.count == 0) {
4868         res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
4869         if (res != OK) return res;
4870     }
4871 
4872     // If AE precapture trigger is active, insert a fake precapture trigger ID
4873     // if none already exists
4874     camera_metadata_entry pcTrigger =
4875             metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4876     camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4877     if (pcTrigger.count > 0 &&
4878             pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4879             pcId.count == 0) {
4880         res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
4881                 &fakeTriggerId, 1);
4882         if (res != OK) return res;
4883     }
4884 
4885     return OK;
4886 }
4887 
overrideAutoRotateAndCrop(const sp<CaptureRequest> & request)4888 bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4889     ATRACE_CALL();
4890     Mutex::Autolock l(mTriggerMutex);
4891     return Camera3Device::overrideAutoRotateAndCrop(request, this->mRotationOverride,
4892             this->mRotateAndCropOverride);
4893 }
4894 
overrideAutoRotateAndCrop(const sp<CaptureRequest> & request,int rotationOverride,camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride)4895 bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4896         int rotationOverride,
4897         camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
4898     ATRACE_CALL();
4899 
4900     if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE) {
4901         uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4902         CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4903         metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4904                 &rotateAndCrop_u8, 1);
4905         return true;
4906     }
4907 
4908     if (request->mRotateAndCropAuto) {
4909         CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4910 
4911         auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4912         if (rotateAndCropEntry.count > 0) {
4913             if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
4914                 return false;
4915             } else {
4916                 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
4917                 return true;
4918             }
4919         } else {
4920             uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4921             metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
4922             return true;
4923         }
4924     }
4925 
4926     return false;
4927 }
4928 
overrideAutoframing(const sp<CaptureRequest> & request,camera_metadata_enum_android_control_autoframing_t autoframingOverride)4929 bool Camera3Device::overrideAutoframing(const sp<CaptureRequest> &request /*out*/,
4930         camera_metadata_enum_android_control_autoframing_t autoframingOverride) {
4931     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4932     auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4933     if (autoframingEntry.count > 0) {
4934         if (autoframingEntry.data.u8[0] == autoframingOverride) {
4935             return false;
4936         } else {
4937             autoframingEntry.data.u8[0] = autoframingOverride;
4938             return true;
4939         }
4940     } else {
4941         uint8_t autoframing_u8 = autoframingOverride;
4942         metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4943                 &autoframing_u8, 1);
4944         return true;
4945     }
4946 
4947     return false;
4948 }
4949 
overrideAutoframing(const sp<CaptureRequest> & request)4950 bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4951     ATRACE_CALL();
4952 
4953     if (request->mAutoframingAuto) {
4954         Mutex::Autolock l(mTriggerMutex);
4955         return Camera3Device::overrideAutoframing(request, mAutoframingOverride);
4956     }
4957 
4958     return false;
4959 }
4960 
injectSessionParams(const sp<CaptureRequest> & request,const CameraMetadata & injectedSessionParams)4961 void Camera3Device::RequestThread::injectSessionParams(
4962     const sp<CaptureRequest> &request,
4963     const CameraMetadata& injectedSessionParams) {
4964     CameraMetadata &requestMetadata = request->mSettingsList.begin()->metadata;
4965     uint32_t tag_section;
4966     camera_metadata_ro_entry entry;
4967     for (auto tag : mSessionParamKeys) {
4968         tag_section = tag >> 16;
4969         if (tag_section < VENDOR_SECTION) {
4970             // Only allow injection of vendor tags.
4971             continue;
4972         }
4973         entry = injectedSessionParams.find(tag);
4974         if (entry.count > 0) {
4975             requestMetadata.update(entry);
4976         }
4977     }
4978 }
4979 
setInjectedSessionParams(const CameraMetadata & injectedSessionParams)4980 status_t Camera3Device::RequestThread::setInjectedSessionParams(
4981         const CameraMetadata& injectedSessionParams) {
4982     ATRACE_CALL();
4983     Mutex::Autolock l(mTriggerMutex);
4984     mInjectedSessionParams = injectedSessionParams;
4985     return OK;
4986 }
4987 
injectSessionParams(const CameraMetadata & injectedSessionParams)4988 status_t Camera3Device::injectSessionParams(const CameraMetadata& injectedSessionParams) {
4989     ATRACE_CALL();
4990     Mutex::Autolock il(mInterfaceLock);
4991     Mutex::Autolock l(mLock);
4992 
4993     if (mRequestThread == nullptr) {
4994         return INVALID_OPERATION;
4995     }
4996 
4997     return mRequestThread->setInjectedSessionParams(injectedSessionParams);
4998 }
4999 
overrideTestPattern(const sp<CaptureRequest> & request)5000 bool Camera3Device::RequestThread::overrideTestPattern(
5001         const sp<CaptureRequest> &request) {
5002     ATRACE_CALL();
5003 
5004     if (!mSupportCameraMute) return false;
5005 
5006     Mutex::Autolock l(mTriggerMutex);
5007 
5008     bool changed = false;
5009 
5010     // For a multi-camera, the physical cameras support the same set of
5011     // test pattern modes as the logical camera.
5012     for (auto& settings : request->mSettingsList) {
5013         CameraMetadata &metadata = settings.metadata;
5014 
5015         int32_t testPatternMode = settings.mOriginalTestPatternMode;
5016         int32_t testPatternData[4] = {
5017             settings.mOriginalTestPatternData[0],
5018             settings.mOriginalTestPatternData[1],
5019             settings.mOriginalTestPatternData[2],
5020             settings.mOriginalTestPatternData[3]
5021         };
5022         if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5023             testPatternMode = mCameraMute;
5024             testPatternData[0] = 0;
5025             testPatternData[1] = 0;
5026             testPatternData[2] = 0;
5027             testPatternData[3] = 0;
5028         }
5029 
5030         auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5031         bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
5032         if (testPatternEntry.count > 0) {
5033             if (testPatternEntry.data.i32[0] != testPatternMode) {
5034                 testPatternEntry.data.i32[0] = testPatternMode;
5035                 changed = true;
5036             }
5037         } else if (supportTestPatternModeKey) {
5038             metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5039                     &testPatternMode, 1);
5040             changed = true;
5041         }
5042 
5043         auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5044         bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
5045         if (testPatternColor.count >= 4) {
5046             for (size_t i = 0; i < 4; i++) {
5047                 if (testPatternColor.data.i32[i] != testPatternData[i]) {
5048                     testPatternColor.data.i32[i] = testPatternData[i];
5049                     changed = true;
5050                 }
5051             }
5052         } else if (supportTestPatternDataKey) {
5053             metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5054                     testPatternData, 4);
5055             changed = true;
5056         }
5057     }
5058 
5059     return changed;
5060 }
5061 
overrideSettingsOverride(const sp<CaptureRequest> & request)5062 bool Camera3Device::RequestThread::overrideSettingsOverride(
5063         const sp<CaptureRequest> &request) {
5064     ATRACE_CALL();
5065 
5066     if (!mSupportSettingsOverride) return false;
5067 
5068     Mutex::Autolock l(mTriggerMutex);
5069 
5070     // For a multi-camera, only override the logical camera's metadata.
5071     CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5072     camera_metadata_entry entry = metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
5073     int32_t originalValue = request->mSettingsList.begin()->mOriginalSettingsOverride;
5074     if (mSettingsOverride != -1 &&
5075             (entry.count == 0 || entry.data.i32[0] != mSettingsOverride)) {
5076         metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
5077                 &mSettingsOverride, 1);
5078         return true;
5079     } else if (mSettingsOverride == -1 &&
5080             (entry.count == 0 || entry.data.i32[0] != originalValue)) {
5081         metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
5082                 &originalValue, 1);
5083         return true;
5084     }
5085 
5086     return false;
5087 }
5088 
setHalInterface(sp<HalInterface> newHalInterface)5089 status_t Camera3Device::RequestThread::setHalInterface(
5090         sp<HalInterface> newHalInterface) {
5091     if (newHalInterface.get() == nullptr) {
5092         ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5093         return DEAD_OBJECT;
5094     }
5095 
5096     mInterface = newHalInterface;
5097 
5098     return OK;
5099 }
5100 
wakeupLatestRequest(bool latestRequestFailed,int32_t latestRequestId)5101 void  Camera3Device::RequestThread::wakeupLatestRequest(
5102         bool latestRequestFailed,
5103         int32_t latestRequestId) {
5104     Mutex::Autolock al(mLatestRequestMutex);
5105 
5106     if (latestRequestFailed) {
5107         mLatestFailedRequestId = latestRequestId;
5108     } else {
5109         mLatestRequestId = latestRequestId;
5110     }
5111     mLatestRequestSignal.signal();
5112 }
5113 
5114 
5115 /**
5116  * PreparerThread inner class methods
5117  */
5118 
PreparerThread()5119 Camera3Device::PreparerThread::PreparerThread() :
5120         Thread(/*canCallJava*/false), mListener(nullptr),
5121         mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
5122 }
5123 
~PreparerThread()5124 Camera3Device::PreparerThread::~PreparerThread() {
5125     Thread::requestExitAndWait();
5126     if (mCurrentStream != nullptr) {
5127         mCurrentStream->cancelPrepare();
5128         ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5129         mCurrentStream.clear();
5130     }
5131     clear();
5132 }
5133 
prepare(int maxCount,sp<Camera3StreamInterface> & stream)5134 status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
5135     ATRACE_CALL();
5136     status_t res;
5137 
5138     Mutex::Autolock l(mLock);
5139     sp<NotificationListener> listener = mListener.promote();
5140 
5141     res = stream->startPrepare(maxCount, true /*blockRequest*/);
5142     if (res == OK) {
5143         // No preparation needed, fire listener right off
5144         ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
5145         if (listener != NULL) {
5146             listener->notifyPrepared(stream->getId());
5147         }
5148         return OK;
5149     } else if (res != NOT_ENOUGH_DATA) {
5150         return res;
5151     }
5152 
5153     // Need to prepare, start up thread if necessary
5154     if (!mActive) {
5155         // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5156         // isn't running
5157         Thread::requestExitAndWait();
5158         res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5159         if (res != OK) {
5160             ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
5161             if (listener != NULL) {
5162                 listener->notifyPrepared(stream->getId());
5163             }
5164             return res;
5165         }
5166         mCancelNow = false;
5167         mActive = true;
5168         ALOGV("%s: Preparer stream started", __FUNCTION__);
5169     }
5170 
5171     // queue up the work
5172     mPendingStreams.push_back(
5173             std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
5174     ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5175 
5176     return OK;
5177 }
5178 
pause()5179 void Camera3Device::PreparerThread::pause() {
5180     ATRACE_CALL();
5181 
5182     Mutex::Autolock l(mLock);
5183 
5184     std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
5185     pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
5186     sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5187     int currentMaxCount = mCurrentMaxCount;
5188     mPendingStreams.clear();
5189     mCancelNow = true;
5190     while (mActive) {
5191         auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5192         if (res == TIMED_OUT) {
5193             ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5194             return;
5195         } else if (res != OK) {
5196             ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5197             return;
5198         }
5199     }
5200 
5201     //Check whether the prepare thread was able to complete the current
5202     //stream. In case work is still pending emplace it along with the rest
5203     //of the streams in the pending list.
5204     if (currentStream != nullptr) {
5205         if (!mCurrentPrepareComplete) {
5206             pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
5207         }
5208     }
5209 
5210     mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
5211     for (const auto& it : mPendingStreams) {
5212         std::get<1>(it)->cancelPrepare();
5213     }
5214 }
5215 
resume()5216 status_t Camera3Device::PreparerThread::resume() {
5217     ATRACE_CALL();
5218     ALOGV("%s: PreparerThread", __FUNCTION__);
5219     status_t res;
5220 
5221     Mutex::Autolock l(mLock);
5222     sp<NotificationListener> listener = mListener.promote();
5223 
5224     if (mActive) {
5225         ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5226         return NO_INIT;
5227     }
5228 
5229     auto it = mPendingStreams.begin();
5230     for (; it != mPendingStreams.end();) {
5231         res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
5232         if (res == OK) {
5233             if (listener != NULL) {
5234                 listener->notifyPrepared(std::get<1>(*it)->getId());
5235             }
5236             it = mPendingStreams.erase(it);
5237         } else if (res != NOT_ENOUGH_DATA) {
5238             ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5239                     res, strerror(-res));
5240             it = mPendingStreams.erase(it);
5241         } else {
5242             it++;
5243         }
5244     }
5245 
5246     if (mPendingStreams.empty()) {
5247         return OK;
5248     }
5249 
5250     res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5251     if (res != OK) {
5252         ALOGE("%s: Unable to start preparer stream: %d (%s)",
5253                 __FUNCTION__, res, strerror(-res));
5254         return res;
5255     }
5256     mCancelNow = false;
5257     mActive = true;
5258     ALOGV("%s: Preparer stream started", __FUNCTION__);
5259 
5260     return OK;
5261 }
5262 
clear()5263 status_t Camera3Device::PreparerThread::clear() {
5264     ATRACE_CALL();
5265     Mutex::Autolock l(mLock);
5266 
5267     for (const auto& it : mPendingStreams) {
5268         std::get<1>(it)->cancelPrepare();
5269     }
5270     mPendingStreams.clear();
5271     mCancelNow = true;
5272 
5273     return OK;
5274 }
5275 
setNotificationListener(wp<NotificationListener> listener)5276 void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
5277     ATRACE_CALL();
5278     Mutex::Autolock l(mLock);
5279     mListener = listener;
5280 }
5281 
threadLoop()5282 bool Camera3Device::PreparerThread::threadLoop() {
5283     status_t res;
5284     {
5285         Mutex::Autolock l(mLock);
5286         if (mCurrentStream == nullptr) {
5287             // End thread if done with work
5288             if (mPendingStreams.empty()) {
5289                 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5290                 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5291                 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5292                 mActive = false;
5293                 mThreadActiveSignal.signal();
5294                 return false;
5295             }
5296 
5297             // Get next stream to prepare
5298             auto it = mPendingStreams.begin();
5299             mCurrentMaxCount = std::get<0>(*it);
5300             mCurrentStream = std::get<1>(*it);
5301             mCurrentPrepareComplete = false;
5302             mPendingStreams.erase(it);
5303             ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5304             ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5305         } else if (mCancelNow) {
5306             mCurrentStream->cancelPrepare();
5307             ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5308             ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5309             mCurrentStream.clear();
5310             mCancelNow = false;
5311             return true;
5312         }
5313     }
5314 
5315     res = mCurrentStream->prepareNextBuffer();
5316     if (res == NOT_ENOUGH_DATA) return true;
5317     if (res != OK) {
5318         // Something bad happened; try to recover by cancelling prepare and
5319         // signalling listener anyway
5320         ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5321                 mCurrentStream->getId(), res, strerror(-res));
5322         mCurrentStream->cancelPrepare();
5323     }
5324 
5325     // This stream has finished, notify listener
5326     Mutex::Autolock l(mLock);
5327     sp<NotificationListener> listener = mListener.promote();
5328     if (listener != NULL) {
5329         ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5330                 mCurrentStream->getId());
5331         listener->notifyPrepared(mCurrentStream->getId());
5332     }
5333 
5334     ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5335     mCurrentStream.clear();
5336     mCurrentPrepareComplete = true;
5337 
5338     return true;
5339 }
5340 
initialize(sp<camera3::StatusTracker> statusTracker)5341 status_t Camera3Device::RequestBufferStateMachine::initialize(
5342         sp<camera3::StatusTracker> statusTracker) {
5343     if (statusTracker == nullptr) {
5344         ALOGE("%s: statusTracker is null", __FUNCTION__);
5345         return BAD_VALUE;
5346     }
5347 
5348     std::lock_guard<std::mutex> lock(mLock);
5349     mStatusTracker = statusTracker;
5350     mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
5351     return OK;
5352 }
5353 
deInit()5354 status_t Camera3Device::RequestBufferStateMachine::deInit() {
5355     std::lock_guard<std::mutex> lock(mLock);
5356     sp<StatusTracker> statusTracker = mStatusTracker.promote();
5357     if (statusTracker == nullptr) {
5358         ALOGE("%s: statusTracker is null", __FUNCTION__);
5359         return INVALID_OPERATION;
5360     }
5361     if (mRequestBufferStatusId == StatusTracker::NO_STATUS_ID) {
5362         ALOGE("%s: RequestBufferStateMachine not initialized", __FUNCTION__);
5363         return INVALID_OPERATION;
5364     }
5365     statusTracker->removeComponent(mRequestBufferStatusId);
5366     // Bring back to de-initialized state
5367     mRequestBufferStatusId = StatusTracker::NO_STATUS_ID;
5368     mRequestThreadPaused = true;
5369     mInflightMapEmpty = true;
5370     mRequestBufferOngoing = false;
5371     mSwitchedToOffline = false;
5372     return OK;
5373 }
5374 
startRequestBuffer()5375 bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5376     std::lock_guard<std::mutex> lock(mLock);
5377     if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
5378         mRequestBufferOngoing = true;
5379         notifyTrackerLocked(/*active*/true);
5380         return true;
5381     }
5382     return false;
5383 }
5384 
endRequestBuffer()5385 void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5386     std::lock_guard<std::mutex> lock(mLock);
5387     if (!mRequestBufferOngoing) {
5388         ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5389         return;
5390     }
5391     mRequestBufferOngoing = false;
5392     if (mStatus == RB_STATUS_PENDING_STOP) {
5393         checkSwitchToStopLocked();
5394     }
5395     notifyTrackerLocked(/*active*/false);
5396 }
5397 
onStreamsConfigured()5398 void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5399     std::lock_guard<std::mutex> lock(mLock);
5400     mSwitchedToOffline = false;
5401     mStatus = RB_STATUS_READY;
5402     return;
5403 }
5404 
onSubmittingRequest()5405 void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
5406     std::lock_guard<std::mutex> lock(mLock);
5407     mRequestThreadPaused = false;
5408     // inflight map register actually happens in prepareHalRequest now, but it is close enough
5409     // approximation.
5410     mInflightMapEmpty = false;
5411     if (mStatus == RB_STATUS_STOPPED) {
5412         mStatus = RB_STATUS_READY;
5413     }
5414     return;
5415 }
5416 
onRequestThreadPaused()5417 void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5418     std::lock_guard<std::mutex> lock(mLock);
5419     mRequestThreadPaused = true;
5420     if (mStatus == RB_STATUS_PENDING_STOP) {
5421         checkSwitchToStopLocked();
5422     }
5423     return;
5424 }
5425 
onInflightMapEmpty()5426 void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5427     std::lock_guard<std::mutex> lock(mLock);
5428     mInflightMapEmpty = true;
5429     if (mStatus == RB_STATUS_PENDING_STOP) {
5430         checkSwitchToStopLocked();
5431     }
5432     return;
5433 }
5434 
onWaitUntilIdle()5435 void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5436     std::lock_guard<std::mutex> lock(mLock);
5437     if (!checkSwitchToStopLocked()) {
5438         mStatus = RB_STATUS_PENDING_STOP;
5439     }
5440     return;
5441 }
5442 
onSwitchToOfflineSuccess()5443 bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5444     std::lock_guard<std::mutex> lock(mLock);
5445     if (mRequestBufferOngoing) {
5446         ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5447                 __FUNCTION__);
5448         return false;
5449     }
5450     mSwitchedToOffline = true;
5451     mInflightMapEmpty = true;
5452     mRequestThreadPaused = true;
5453     mStatus = RB_STATUS_STOPPED;
5454     return true;
5455 }
5456 
notifyTrackerLocked(bool active)5457 void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5458     sp<StatusTracker> statusTracker = mStatusTracker.promote();
5459     if (statusTracker != nullptr) {
5460         if (active) {
5461             statusTracker->markComponentActive(mRequestBufferStatusId);
5462         } else {
5463             statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5464         }
5465     }
5466 }
5467 
checkSwitchToStopLocked()5468 bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5469     if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5470         mStatus = RB_STATUS_STOPPED;
5471         return true;
5472     }
5473     return false;
5474 }
5475 
startRequestBuffer()5476 bool Camera3Device::startRequestBuffer() {
5477     return mRequestBufferSM.startRequestBuffer();
5478 }
5479 
endRequestBuffer()5480 void Camera3Device::endRequestBuffer() {
5481     mRequestBufferSM.endRequestBuffer();
5482 }
5483 
getWaitDuration()5484 nsecs_t Camera3Device::getWaitDuration() {
5485     return kBaseGetBufferWait + getExpectedInFlightDuration();
5486 }
5487 
getInflightBufferKeys(std::vector<std::pair<int32_t,int32_t>> * out)5488 void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5489     mInterface->getInflightBufferKeys(out);
5490 }
5491 
getInflightRequestBufferKeys(std::vector<uint64_t> * out)5492 void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5493     mInterface->getInflightRequestBufferKeys(out);
5494 }
5495 
getAllStreams()5496 std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5497     std::vector<sp<Camera3StreamInterface>> ret;
5498     bool hasInputStream = mInputStream != nullptr;
5499     ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5500     if (hasInputStream) {
5501         ret.push_back(mInputStream);
5502     }
5503     for (size_t i = 0; i < mOutputStreams.size(); i++) {
5504         ret.push_back(mOutputStreams[i]);
5505     }
5506     for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5507         ret.push_back(mDeletedStreams[i]);
5508     }
5509     return ret;
5510 }
5511 
getOfflineStreamIds(std::vector<int> * offlineStreamIds)5512 void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5513     ATRACE_CALL();
5514 
5515     if (offlineStreamIds == nullptr) {
5516         return;
5517     }
5518 
5519     Mutex::Autolock il(mInterfaceLock);
5520 
5521     auto streamIds = mOutputStreams.getStreamIds();
5522     bool hasInputStream = mInputStream != nullptr;
5523     if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5524         offlineStreamIds->push_back(mInputStream->getId());
5525     }
5526 
5527     for (const auto & streamId : streamIds) {
5528         sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5529         // Streams that use the camera buffer manager are currently not supported in
5530         // offline mode
5531         if (stream->getOfflineProcessingSupport() &&
5532                 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5533             offlineStreamIds->push_back(streamId);
5534         }
5535     }
5536 }
5537 
setRotateAndCropAutoBehavior(camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue,bool fromHal)5538 status_t Camera3Device::setRotateAndCropAutoBehavior(
5539     camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue, bool fromHal) {
5540     ATRACE_CALL();
5541     // We shouldn't hold mInterfaceLock when called as an effect of a HAL
5542     // callback since this can lead to a deadlock : b/299348355.
5543     // mLock still protects state.
5544     std::optional<Mutex::Autolock> maybeMutex =
5545         fromHal ? std::nullopt : std::optional<Mutex::Autolock>(mInterfaceLock);
5546     Mutex::Autolock l(mLock);
5547     if (mRequestThread == nullptr) {
5548         return INVALID_OPERATION;
5549     }
5550     if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5551         return BAD_VALUE;
5552     }
5553     mRotateAndCropOverride = rotateAndCropValue;
5554     return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5555 }
5556 
setAutoframingAutoBehavior(camera_metadata_enum_android_control_autoframing_t autoframingValue)5557 status_t Camera3Device::setAutoframingAutoBehavior(
5558     camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5559     ATRACE_CALL();
5560     Mutex::Autolock il(mInterfaceLock);
5561     Mutex::Autolock l(mLock);
5562     if (mRequestThread == nullptr) {
5563         return INVALID_OPERATION;
5564     }
5565     if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
5566         return BAD_VALUE;
5567     }
5568     mAutoframingOverride = autoframingValue;
5569     return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5570 }
5571 
supportsCameraMute()5572 bool Camera3Device::supportsCameraMute() {
5573     Mutex::Autolock il(mInterfaceLock);
5574     Mutex::Autolock l(mLock);
5575 
5576     return mSupportCameraMute;
5577 }
5578 
setCameraMute(bool enabled)5579 status_t Camera3Device::setCameraMute(bool enabled) {
5580     ATRACE_CALL();
5581     Mutex::Autolock il(mInterfaceLock);
5582     Mutex::Autolock l(mLock);
5583     return setCameraMuteLocked(enabled);
5584 }
5585 
setCameraMuteLocked(bool enabled)5586 status_t Camera3Device::setCameraMuteLocked(bool enabled) {
5587     if (mRequestThread == nullptr) {
5588         mCameraMuteInitial = enabled;
5589         return OK;
5590     }
5591 
5592     if (!mSupportCameraMute) {
5593         return INVALID_OPERATION;
5594     }
5595 
5596     int32_t muteMode =
5597             !enabled                      ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5598             mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5599                                             ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5600     return mRequestThread->setCameraMute(muteMode);
5601 }
5602 
supportsZoomOverride()5603 bool Camera3Device::supportsZoomOverride() {
5604     Mutex::Autolock il(mInterfaceLock);
5605     Mutex::Autolock l(mLock);
5606 
5607     return mSupportZoomOverride;
5608 }
5609 
setZoomOverride(int32_t zoomOverride)5610 status_t Camera3Device::setZoomOverride(int32_t zoomOverride) {
5611     ATRACE_CALL();
5612     Mutex::Autolock il(mInterfaceLock);
5613     Mutex::Autolock l(mLock);
5614 
5615     if (mRequestThread == nullptr || !mSupportZoomOverride) {
5616         return INVALID_OPERATION;
5617     }
5618 
5619     return mRequestThread->setZoomOverride(zoomOverride);
5620 }
5621 
injectCamera(const std::string & injectedCamId,sp<CameraProviderManager> manager)5622 status_t Camera3Device::injectCamera(const std::string& injectedCamId,
5623                                      sp<CameraProviderManager> manager) {
5624     ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.c_str());
5625     ATRACE_CALL();
5626     Mutex::Autolock il(mInterfaceLock);
5627     // When the camera device is active, injectCamera() and stopInjection() will call
5628     // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5629     // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5630     // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5631     // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5632     // waitUntilStateThenRelock().
5633     Mutex::Autolock l(mLock);
5634 
5635     status_t res = NO_ERROR;
5636     if (mInjectionMethods->isInjecting()) {
5637         if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5638             return OK;
5639         } else {
5640             res = mInjectionMethods->stopInjection();
5641             if (res != OK) {
5642                 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5643                         __FUNCTION__, res);
5644                 return res;
5645             }
5646         }
5647     }
5648 
5649     res = injectionCameraInitialize(injectedCamId, manager);
5650     if (res != OK) {
5651         ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5652                 __FUNCTION__, res);
5653         return res;
5654     }
5655 
5656     // When the second display of android is cast to the remote device, and the opened camera is
5657     // also cast to the second display, in this case, because the camera has configured the streams
5658     // at this time, we can directly call injectCamera() to replace the internal camera with
5659     // injection camera.
5660     if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5661         ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5662 
5663         camera3::camera_stream_configuration injectionConfig;
5664         std::vector<uint32_t> injectionBufferSizes;
5665         mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5666         if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5667                     || injectionBufferSizes.size() <= 0) {
5668             ALOGE("Failed to inject camera due to abandoned configuration! "
5669                     "mOperatingMode: %d injectionConfig.num_streams: %d "
5670                     "injectionBufferSizes.size(): %zu", mOperatingMode,
5671                     injectionConfig.num_streams, injectionBufferSizes.size());
5672             return DEAD_OBJECT;
5673         }
5674 
5675         res = mInjectionMethods->injectCamera(
5676                 injectionConfig, injectionBufferSizes);
5677         if (res != OK) {
5678             ALOGE("Can't finish inject camera process!");
5679             return res;
5680         }
5681     }
5682 
5683     return OK;
5684 }
5685 
stopInjection()5686 status_t Camera3Device::stopInjection() {
5687     ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5688     Mutex::Autolock il(mInterfaceLock);
5689     Mutex::Autolock l(mLock);
5690     return mInjectionMethods->stopInjection();
5691 }
5692 
overrideStreamUseCaseLocked()5693 void Camera3Device::overrideStreamUseCaseLocked() {
5694     if (mStreamUseCaseOverrides.size() == 0) {
5695         return;
5696     }
5697 
5698     // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5699     // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5700     // Refer to CameraService::printHelp for details.
5701     std::vector<int> outputStreamsIndices(mOutputStreams.size());
5702     for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5703         outputStreamsIndices[i] = i;
5704     }
5705 
5706     std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5707             [&](int a, int b) -> bool {
5708 
5709                 auto formatScore = [](int format) {
5710                     switch (format) {
5711                     case HAL_PIXEL_FORMAT_BLOB:
5712                         return 4;
5713                     case HAL_PIXEL_FORMAT_RAW16:
5714                     case HAL_PIXEL_FORMAT_RAW10:
5715                     case HAL_PIXEL_FORMAT_RAW12:
5716                         return 3;
5717                     case HAL_PIXEL_FORMAT_YCBCR_420_888:
5718                         return 2;
5719                     case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5720                         return 1;
5721                     default:
5722                         return 0;
5723                     }
5724                 };
5725 
5726                 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5727                 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5728                 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5729                 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5730                 if (sizeA > sizeB ||
5731                         (sizeA == sizeB && formatAScore >= formatBScore)) {
5732                     return true;
5733                 } else {
5734                     return false;
5735                 }
5736             });
5737 
5738     size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5739     for (size_t i = 0; i < mOutputStreams.size(); i++) {
5740         mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5741                 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5742     }
5743 }
5744 
5745 }; // namespace android
5746