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